#!/usr/bin/env tsx
/**
 * 依赖 / 脚本规范扫描器 (Dependency Scanner)
 *
 * 覆盖 review-spec §6.6 / §7.4 / §7.5 的可固化项：
 *   - CF-003 第三方 import 仅限宿主白名单（auto；P0 命中 / P1 未声明原因）
 *   - CF-008 .ts 后缀 / ESM import / shebang `#!/usr/bin/env node`（auto；P1）
 *
 * 宿主依赖白名单 = `js-yaml` / `jszip` / `@easbot/utils` / `@easbot/llm` / `@easbot/plugin`
 * （与 AGENTS.md §12「scripts/ 依赖白名单」对齐；评审显式豁免：`ai` / `@ai-sdk/provider` 仅 `eas-agent-creation/scripts/llm.ts`）
 *
 * 白名单说明：本技能 MUST NOT 与宿主 AGENTS.md 耦合；白名单值以**本规范内置常量**维护，
 * 宿主项目覆盖时通过命令行参数 `--allow-deps a,b,c` 扩展（review.ts 转发）。
 */

import { promises as fs } from 'fs';
import * as path from 'path';
import type { Finding, Scanner } from '../types.js';

/**
 * 默认依赖白名单——**只放跨项目通用的包**（任何宿主都可能用到）：
 * - `js-yaml`：YAML 解析（AgentSkills frontmatter 标准解析器）
 * - `jszip`：ZIP 打包（`.skill` 文件标准格式）
 *
 * 宿主项目专属白名单（如 `AGENTS.md §12` 中的 `@easbot/utils` / `@easbot/llm` /
 * `@easbot/plugin`）MUST 由评审者通过 CLI `--allow-deps a,b,c` 显式传入，本工具
 * 不内嵌任何项目专属白名单——保持通用工具属性，可被任意宿主 Agent 应用。
 *
 * 豁免路径（`EXEMPT_PATHS`）同理只放通用场景：
 * - `__tests__/` 下的 vitest 引用：测试目录对所有项目通用
 * - `*.test.ts` / `*.spec.ts`：测试文件通用
 */
const DEFAULT_ALLOWED = new Set(['js-yaml', 'jszip']);

/** Node 内置模块清单（按 Node 22 LTS；不要求完整，新增内置模块时补一行） */
const NODE_BUILTIN = new Set([
  'assert',
  'async_hooks',
  'buffer',
  'child_process',
  'cluster',
  'console',
  'constants',
  'crypto',
  'dgram',
  'diagnostics_channel',
  'dns',
  'domain',
  'events',
  'fs',
  'http',
  'http2',
  'https',
  'inspector',
  'module',
  'net',
  'os',
  'path',
  'perf_hooks',
  'process',
  'punycode',
  'querystring',
  'readline',
  'repl',
  'stream',
  'string_decoder',
  'sys',
  'timers',
  'tls',
  'trace_events',
  'tty',
  'url',
  'util',
  'v8',
  'vm',
  'wasi',
  'worker_threads',
  'zlib',
]);

/** 文件级豁免：通用模式（不绑宿主项目） */
const EXEMPT_PATTERNS = [
  /\/(?:__tests__|tests?|test)\//, // 测试目录（任意项目通用）
  /\.(test|spec)\.(ts|js|tsx|jsx)$/, // 测试文件
];

export interface DependencyScannerOptions {
  extraAllowed?: string[];
  exemptPaths?: string[];
}

function extractImportTargets(line: string): string[] {
  // 仅匹配 `import ... from 'xxx'` / `import 'xxx'`；排除字符串模板内的 `from '${var}'`
  // 要求行首或行首空格后是 `import` 关键字
  if (!/^\s*import(\s|\(|$)/.test(line)) return [];
  const m = line.match(/from\s+['"]([^'"]+)['"]/);
  if (m && m[1] && !m[1].startsWith('.') && !m[1].startsWith('node:')) {
    return [m[1]];
  }
  return [];
}

function packageRoot(spec: string): string {
  // 处理 @scope/pkg/sub 与 pkg/sub
  if (spec.startsWith('@')) {
    return spec.split('/').slice(0, 2).join('/');
  }
  return spec.split('/')[0] ?? spec;
}

function isBuiltin(spec: string): boolean {
  // 处理裸名与 node: 协议
  const name = spec.startsWith('node:') ? spec.slice(5) : spec;
  if (name.startsWith('.') || name.startsWith('/')) return true;
  // 兼容 `fs/promises` / `path/posix` 这类 Node 内置子模块
  if (NODE_BUILTIN.has(name.split('/')[0] ?? '')) return true;
  return false;
}

export class DependencyScanner implements Scanner {
  name = 'dependency';
  description = '扫描第三方 import 是否在白名单（含默认通用集 + CLI --allow-deps 扩展）+ 脚本规范（后缀 / ESM / shebang）';
  private allowed: Set<string>;
  private exemptPatterns: RegExp[];

  constructor(opts: DependencyScannerOptions = {}) {
    this.allowed = new Set([...DEFAULT_ALLOWED, ...(opts.extraAllowed ?? [])]);
    this.exemptPatterns = [...EXEMPT_PATTERNS, ...(opts.exemptPaths ?? []).map((p) => new RegExp(p))];
  }

  async scan(skillDir: string): Promise<Finding[]> {
    const findings: Finding[] = [];

    async function* walk(d: string): AsyncGenerator<string> {
      let entries: import('fs').Dirent[];
      try {
        entries = await fs.readdir(d, { withFileTypes: true });
      } catch {
        return;
      }
      for (const e of entries) {
        const full = path.join(d, e.name);
        if (e.isDirectory()) {
          if (e.name === 'node_modules' || e.name === 'dist' || e.name.startsWith('.')) continue;
          yield* walk(full);
        } else if (e.isFile() && e.name.endsWith('.ts')) {
          yield full;
        }
      }
    }

    for await (const file of walk(skillDir)) {
      const rel = path.relative(skillDir, file).split(path.sep).join('/');
      let content: string;
      try {
        content = await fs.readFile(file, 'utf8');
      } catch {
        continue;
      }

      const isExempt = this.exemptPatterns.some((rx) => rx.test(rel));

      // CF-003：第三方 import 白名单
      const lines = content.split(/\r?\n/);
      for (let i = 0; i < lines.length; i++) {
        const l = lines[i] ?? '';
        const targets = extractImportTargets(l);
        for (const t of targets) {
          if (isBuiltin(t)) continue; // Node 内置永远放行
          const root = packageRoot(t);
          if (this.allowed.has(root) || isExempt) continue;
          findings.push({
            id: 'CF-003',
            dimension: 'CF',
            severity: 'P0',
            checkMethod: 'auto',
            message: `引入白名单外第三方依赖：${t}`,
            evidence: `${rel}:${i + 1}`,
            fix: '优先改用 Node 内置模块；或申请加入白名单（评审显式豁免）',
          });
        }
      }

      // CF-008：脚本规范
      // .ts 后缀：本扫描器只枚举 .ts，已满足
      // ESM import：扫任意 `import ` 语句即合规（无 ESM 检查）
      // shebang：要求文件首行 `#!/usr/bin/env node` 或 `#!/usr/bin/env tsx`
      if (lines.length > 0) {
        const first = (lines[0] ?? '').trim();
        if (first.startsWith('#!') && !/^#!\/usr\/bin\/env\s+(node|tsx)$/.test(first)) {
          findings.push({
            id: 'CF-008',
            dimension: 'CF',
            severity: 'P1',
            checkMethod: 'auto',
            message: `shebang 应使用 \`#!/usr/bin/env node\` 或 \`#!/usr/bin/env tsx\`（当前：${first}）`,
            evidence: `${rel}:1`,
            fix: '改为 `#!/usr/bin/env node`',
          });
        }
      }
    }

    return findings;
  }
}

export function createDependencyScanner(opts: DependencyScannerOptions = {}): DependencyScanner {
  return new DependencyScanner(opts);
}

export default createDependencyScanner;
