import path from 'node:path';
import { collectScanTargets, exists, read, rel } from './contract-scan-core.mjs';

function collectVoipBoundaryHits(text) {
  const hits = [];
  if (/@tfdesign\/b-end\b/.test(text)) hits.push('@tfdesign/b-end');
  if (/@tfdesign\/c-end\b|ImAiExploreFrame|Handleframe/i.test(text)) hits.push('C端 IM 包组件/模板');
  if (/<Table\b|<NavBar\b|<Filter\b/.test(text)) hits.push('B端后台组件');
  return [...new Set(hits)].slice(0, 8);
}

function collectRemoteMediaHits(text) {
  return (text.match(/<(?:Avatar|img)\b[^>]*\bsrc\s*=\s*["']https?:\/\/[^"']+["'][^>]*>/gi) || []).slice(0, 6);
}

/**
 * @param {object} opts
 * @param {string} opts.projectRoot
 */
export function runCVoipContract({ projectRoot }) {
  const issues = [];
  const ok = [];
  const pkgPath = path.join(projectRoot, 'package.json');

  if (!exists(pkgPath)) {
    issues.push(`未找到 package.json（当前检测根目录：${projectRoot}）。`);
    return { issues, ok };
  }

  const { scanRoots, targets } = collectScanTargets(projectRoot);
  if (scanRoots.length === 0) {
    issues.push('未找到可扫描的源码目录，跳过规则扫描。');
    return { issues, ok };
  }
  ok.push(`将扫描：${scanRoots.map((r) => rel(projectRoot, r)).join(', ')}`);

  const hit = new Map();
  for (const f of targets) {
    const t = read(f);
    if (!t) continue;
    const boundary = collectVoipBoundaryHits(t);
    const remote = collectRemoteMediaHits(t);
    if (boundary.length || remote.length) hit.set(f, { boundary, remote });
  }

  if (hit.size === 0) {
    ok.push('未发现明显的 VoIP 误用信号（启发式）');
    return { issues, ok };
  }

  for (const [f, v] of hit.entries()) {
    if (v.boundary.length) {
      issues.push(`[${rel(projectRoot, f)}] 包边界疑似错误：${v.boundary.join(', ')}。VoIP 页仅用 @tfdesign/c-voip-end。`);
    }
    if (v.remote.length) {
      issues.push(`[${rel(projectRoot, f)}] 疑似外链图片：${v.remote.join(', ')}。`);
    }
  }

  issues.push('建议：生成前执行 `npx tfds-voip spec <id>`。');
  return { issues, ok };
}
