#!/usr/bin/env node
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { loadIntentCanonical } from './lib/intent-canonical.mjs';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(__dirname, '..');

function ensureDir(dir) {
  fs.mkdirSync(dir, { recursive: true });
}

function buildMarkdown(canonical) {
  const lines = [];
  lines.push('# Intent Canonical Snapshot');
  lines.push('');
  lines.push(`- version: ${canonical.version}`);
  lines.push(`- schemaVersion: ${canonical.schemaVersion}`);
  lines.push(`- confidence: high>=${canonical.confidenceBands.high}, medium>=${canonical.confidenceBands.medium}`);
  lines.push('');
  lines.push('| Intent | Priority | Route | 强触发词(中文) |');
  lines.push('|---|---|---|---|');
  for (const it of canonical.intents) {
    lines.push(`| ${it.id} | ${it.priority} | ${it.routes_to} | ${(it.strongTriggersZh || []).slice(0, 4).join('、')} |`);
  }
  lines.push('');
  lines.push('> Generated by `scripts/build-intent-canonical-assets.mjs`.');
  lines.push('');
  return lines.join('\n');
}

function main() {
  const canonical = loadIntentCanonical();
  const generatedDir = path.join(ROOT, 'scripts', 'generated');
  const refDir = path.join(ROOT, 'references', '01-core');
  ensureDir(generatedDir);
  ensureDir(refDir);

  const jsonOut = path.join(generatedDir, 'intent-canonical.snapshot.json');
  const mdOut = path.join(refDir, 'intent-canonical.generated.md');
  fs.writeFileSync(jsonOut, JSON.stringify(canonical, null, 2) + '\n', 'utf8');
  fs.writeFileSync(mdOut, buildMarkdown(canonical) + '\n', 'utf8');

  console.log(JSON.stringify({
    ok: true,
    intentCount: canonical.intents.length,
    jsonOut,
    mdOut,
  }, null, 2));
}

main();
