import fs from 'node:fs';
import path from 'node:path';

export function readJson(p) {
  if (!fs.existsSync(p)) {
    throw new Error(`找不到文件：${p}`);
  }
  return JSON.parse(fs.readFileSync(p, 'utf8'));
}

export function resolveSkillDir(pkgRoot, skillName) {
  return path.join(pkgRoot, 'skills', skillName);
}

export function loadSummary(skillDir) {
  return readJson(path.join(skillDir, 'components.summary.json'));
}

export function loadIndex(skillDir) {
  const data = readJson(path.join(skillDir, 'components.index.json'));
  return data.components || data.entries || [];
}

export function loadIconsSummary(skillDir) {
  const p = path.join(skillDir, 'icons.summary.json');
  if (!fs.existsSync(p)) return null;
  return readJson(p);
}

export function summaryEntries(summary) {
  return summary.entries || summary.components || [];
}

export function matchEntry(pool, query) {
  const q = String(query).toLowerCase();
  return (
    pool.find((e) => e.id === q) ||
    pool.find((e) => String(e.import?.default || '').toLowerCase() === q) ||
    pool.find((e) => String(e.name || '').toLowerCase() === q) ||
    pool.find((e) => e.id.includes(q) || String(e.name || '').toLowerCase().includes(q)) ||
    pool.find((e) => (e.keywords || []).some((k) => String(k).toLowerCase().includes(q))) ||
    null
  );
}

export function printEntryDetail(d) {
  const lines = [];
  lines.push(`# ${d.name}  (${d.id} · ${d.kind || 'component'})`);
  if (d.description) lines.push(d.description);
  if (d.import) {
    const named = d.import.named?.length ? `, { ${d.import.named.join(', ')} }` : '';
    lines.push(`\nimport ${d.import.default}${named} from '${d.import.from}';`);
  }
  if (d.props?.length) {
    lines.push('\n## props');
    for (const p of d.props) {
      const opt = p.options ? ` = ${p.options.join(' | ')}` : '';
      const def = p.default !== undefined && p.default !== null ? `  (default: ${JSON.stringify(p.default)})` : '';
      lines.push(`- ${p.name}: ${p.type}${opt}${def}`);
    }
  }
  if (d.rules?.length) {
    lines.push('\n## rules');
    d.rules.forEach((r, i) => lines.push(`${i + 1}. ${r}`));
  }
  if (d.examples?.length) {
    lines.push('\n## examples');
    for (const ex of d.examples) lines.push(`- ${ex.label}: ${ex.code}`);
  }
  if (d.starterSnippet) {
    lines.push('\n## starterSnippet');
    lines.push(d.starterSnippet);
  }
  console.log(lines.join('\n'));
}

/**
 * @param {object} opts
 * @param {string} opts.skillDir
 * @param {string} opts.query
 * @param {boolean} [opts.patternMode]
 * @param {string} [opts.cliName]
 */
export function cmdSpec({ skillDir, query, patternMode = false, cliName = 'tfds' }) {
  if (!query) {
    throw new Error(`用法：${cliName} spec <id>  ·  ${cliName} spec --pattern <关键词>`);
  }

  const summary = loadSummary(skillDir);
  const entries = summaryEntries(summary);
  const indexEntries = loadIndex(skillDir);

  let entry = null;
  if (patternMode) {
    const pool = entries.filter((e) => e.kind === 'page-pattern' || e.kind === 'page-template');
    entry = matchEntry(pool, query) || matchEntry(entries, query);
  } else {
    entry = entries.find((e) => e.id === query) || matchEntry(entries, query);
  }

  if (!entry) {
    const sugg = entries
      .map((e) => e.id)
      .filter((id) => id.includes(String(query).toLowerCase()))
      .slice(0, 8);
    throw new Error(
      `未命中条目「${query}」。${sugg.length ? `相近 id：${sugg.join(', ')}` : `用 \`${cliName} list\` 查看全部。`}`,
    );
  }

  const detailPath = path.join(skillDir, 'detail', `${entry.id}.json`);
  if (fs.existsSync(detailPath)) {
    printEntryDetail(readJson(detailPath));
    return;
  }

  const full = indexEntries.find((e) => e.id === entry.id) || entry;
  printEntryDetail(full);
}

/**
 * @param {object} opts
 * @param {string} opts.skillDir
 * @param {string} [opts.kind]
 */
export function cmdList({ skillDir, kind }) {
  const summary = loadSummary(skillDir);
  const entries = summaryEntries(summary).filter((e) => !kind || e.kind === kind);
  const byKind = {};
  for (const e of entries) (byKind[e.kind] ||= []).push(e);
  for (const k of Object.keys(byKind)) {
    console.log(`\n# ${k} (${byKind[k].length})`);
    for (const e of byKind[k]) console.log(`  ${e.id}  —  ${e.name}`);
  }
}

function flattenIcons(iconsSummary) {
  const out = [];
  for (const item of iconsSummary.imCommon || []) out.push(item);
  for (const item of iconsSummary.entries || []) out.push(item);
  return out;
}

/**
 * @param {object} opts
 * @param {string} opts.skillDir
 * @param {string} opts.query
 * @param {string} [opts.cliName]
 */
export function cmdIcons({ skillDir, query, cliName = 'tfds' }) {
  const iconsSummary = loadIconsSummary(skillDir);
  if (!iconsSummary) {
    throw new Error(`本包 Skill 不含 icons.summary.json，无法执行 ${cliName} icons。`);
  }

  const all = flattenIcons(iconsSummary);
  if (!query) {
    console.log(`# Icon 目录（共 ${iconsSummary.total || all.length} 个）\n`);
    console.log('imCommon:');
    for (const item of iconsSummary.imCommon || []) {
      console.log(`  ${item.name}  —  ${item.label}  [${(item.sizes || []).join(', ')}]`);
    }
    console.log('\n用法：');
    console.log(`  ${cliName} icons <关键词>`);
    console.log(`  ${cliName} icons imCommon`);
    return;
  }

  if (query.toLowerCase() === 'imcommon') {
    console.log('# imCommon 常用图标\n');
    for (const item of iconsSummary.imCommon || []) {
      console.log(`## ${item.name}  —  ${item.label}`);
      console.log(`   sizes: ${(item.sizes || []).join(', ')}`);
      console.log(`   <Icon name="${item.name}" size={${(item.sizes || [16])[0]}} />\n`);
    }
    return;
  }

  const q = query.toLowerCase();
  const hits = all.filter(
    (item) =>
      String(item.name || '').toLowerCase().includes(q) ||
      String(item.label || '').toLowerCase().includes(q),
  );

  if (hits.length === 0) {
    throw new Error(`未命中图标「${query}」。请先执行 \`${cliName} icons\` 浏览目录，禁止猜测 Icon name。`);
  }

  console.log(`# 命中 ${hits.length} 个图标\n`);
  for (const item of hits.slice(0, 12)) {
    console.log(`## ${item.name}  —  ${item.label}`);
    console.log(`   sizes: ${(item.sizes || []).join(', ')}`);
    console.log(`   <Icon name="${item.name}" size={${(item.sizes || [16])[0]}} />\n`);
  }
}

export function printCliHelp(cliName, extraLines = []) {
  const lines = [
    `${cliName} CLI`,
    '',
    `  ${cliName} spec <id>              组件/模板完整契约`,
    `  ${cliName} spec --pattern <kw>   模糊查找页面模板`,
    `  ${cliName} list [kind]            列出条目`,
    ...extraLines,
    `  ${cliName} help                   显示帮助`,
  ];
  console.log(lines.join('\n'));
}
