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

const reHex = /#[0-9a-fA-F]{3,8}\b/g;

function collectChartLibraryHits(text) {
  const hits = [];
  if (/from\s+['"]recharts['"]|from\s+['"]echarts|from\s+['"]@antv\//i.test(text)) {
    hits.push('直连三方图表库 import');
  }
  if (/<ResponsiveContainer\b/.test(text)) hits.push('<ResponsiveContainer>');
  if (/<(?:BarChart|LineChart|PieChart)\b/.test(text) && !/Smart(?:Bar|Line|Pie)Chart/.test(text)) {
    hits.push('疑似 Recharts 直出组件标签');
  }
  return [...new Set(hits)].slice(0, 8);
}

function collectChartHexHits(text) {
  const looksLikeChart = /Smart\w*Chart|ChartTooltip|useChartChrome|chart-chrome/i.test(text);
  if (!looksLikeChart) return [];
  return (text.match(reHex) || []).slice(0, 8);
}

function collectBEndDriftHits(text) {
  const hits = [];
  const reTabsLarge = /<Tabs\b[^>]*\bsize\s*=\s*["'](?:md|lg)["'][^>]*>/gi;
  for (const m of text.matchAll(reTabsLarge)) {
    const before = text.slice(Math.max(0, m.index - 360), m.index);
    if (!/(TopBar|顶导|一级导航)/i.test(before)) hits.push(m[0]);
    if (hits.length >= 4) break;
  }
  if (/<h[2-4]\b/.test(text) && !/<FormTitle\b/.test(text)) {
    hits.push('原生 h2-h4 标题（应优先 FormTitle）');
  }
  return hits;
}

/**
 * @param {object} opts
 * @param {string} opts.projectRoot
 */
export function runDashboardContract({ 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 chartLib = collectChartLibraryHits(t);
    const chartHex = collectChartHexHits(t);
    const bEnd = collectBEndDriftHits(t);
    if (chartLib.length || chartHex.length || bEnd.length) {
      hit.set(f, { chartLib, chartHex, bEnd });
    }
  }

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

  for (const [f, v] of hit.entries()) {
    if (v.chartLib.length) {
      issues.push(`[${rel(projectRoot, f)}] 图表须走 @tfdesign/dashboard 封装：${v.chartLib.join(', ')}。改用 Smart*Chart / useChartChrome。`);
    }
    if (v.chartHex.length) {
      issues.push(`[${rel(projectRoot, f)}] 图表区域 hex 硬编码：${v.chartHex.join(', ')}。改用 --color-data-* / resolveColorToken。`);
    }
    if (v.bEnd.length) {
      issues.push(`[${rel(projectRoot, f)}] 内嵌 B端基础件疑似误用：${v.bEnd.join(', ')}。`);
    }
  }

  issues.push('建议：生成前执行 `npx tfds-dashboard spec <id>`；图表配色见 GLOBAL_DESIGN_RULES.md §2。');
  return { issues, ok };
}
