/**
 * CI guard: every user-facing server error must have a Chinese translation.
 *
 * Walks apps/api/src for `throw new *Exception(...)` and `throw new TRPCError({
 * message })`, and checks each message is either in the errors i18n catalog
 * (apps/admin/src/i18n/locales/en/errors.json) or on the ALLOW_INTERNAL list of
 * intentionally-English dev/config signals. Plain `throw new Error(...)` is
 * treated as internal (invariant/programmer) and not required to be translated.
 *
 * Exit 1 (with a report) if any user-facing message is uncovered, so adding a
 * new error forces a catalog entry (or an explicit allowlist decision).
 *
 * Run: cd apps/api && npx ts-node -P tsconfig.json scripts/check-error-i18n.ts
 */
import * as fs from 'fs';
import * as path from 'path';
import ts from 'typescript';

const SRC = path.resolve(__dirname, '../src');
const CATALOG_EN = path.resolve(__dirname, '../../admin/src/i18n/locales/en/errors.json');
const MARK = '\uFFFF';

// Messages intentionally kept in English — internal config / invariants / dev
// signals a normal user never triggers. Keep in sync with the audit's decision.
const ALLOW_INTERNAL: string[] = [
  'Charge type for line "${x}" has no GL account; set one before issuing.',
  'No ledger posting found for this receipt',
  'No ledger posting found for this application',
  'The ${x} account is not set up in the chart of accounts',
  'Each deduction needs a charge type with a GL account',
  'Repairs & Maintenance (RM) charge type is not configured',
  'No step at the current position',
  'Invalid billing period "${x}", expected YYYY-MM',
  'Unknown attachment owner type',
];

/** Collapse ${...} and {{...}} placeholders to a single marker for comparison. */
const skeleton = (s: string): string => s.replace(/\$\{[^}]*\}/g, MARK).replace(/\{\{[^}]*\}\}/g, MARK);

function walk(dir: string, out: string[]): void {
  for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
    const p = path.join(dir, entry.name);
    if (entry.isDirectory()) walk(p, out);
    // Tests throw on purpose, and never at a user. This repo's are *.test.ts
    // (vitest.config.ts), so skipping only *.spec.ts skipped nothing.
    else if (entry.name.endsWith('.ts') && !entry.name.endsWith('.d.ts') && !/\.(spec|test)\.ts$/.test(entry.name)) out.push(p);
  }
}

/** The literal text of a string/template node, with ${...} kept as a marker. */
function messageOf(node: ts.Node): string | null {
  if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) return node.text;
  if (ts.isTemplateExpression(node)) {
    return node.head.text + node.templateSpans.map((s) => MARK + s.literal.text).join('');
  }
  return null; // non-literal (variable/expression) — can't check statically
}

interface Found { file: string; line: number; message: string; }

function extract(file: string): Found[] {
  const sf = ts.createSourceFile(file, fs.readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, true);
  const found: Found[] = [];
  const visit = (node: ts.Node): void => {
    if (ts.isNewExpression(node) && ts.isIdentifier(node.expression)) {
      const cls = node.expression.text;
      const args = node.arguments ?? [];
      if (/Exception$/.test(cls) && args.length > 0) {
        const msg = messageOf(args[0]);
        if (msg !== null) found.push(mk(sf, file, node, msg));
      } else if (cls === 'TRPCError' && args[0] && ts.isObjectLiteralExpression(args[0])) {
        for (const prop of args[0].properties) {
          if (ts.isPropertyAssignment(prop) && prop.name.getText() === 'message') {
            const msg = messageOf(prop.initializer);
            if (msg !== null) found.push(mk(sf, file, node, msg));
          }
        }
      }
    }
    ts.forEachChild(node, visit);
  };
  visit(sf);
  return found;
}

function mk(sf: ts.SourceFile, file: string, node: ts.Node, message: string): Found {
  const { line } = sf.getLineAndCharacterOfPosition(node.getStart());
  return { file: path.relative(SRC, file), line: line + 1, message };
}

function main(): void {
  const catalog = JSON.parse(fs.readFileSync(CATALOG_EN, 'utf8')) as Record<string, string>;
  const covered = new Set(Object.values(catalog).map(skeleton));
  const allowed = new Set(ALLOW_INTERNAL.map(skeleton));

  const files: string[] = [];
  walk(SRC, files);
  const all = files.flatMap(extract);

  const missing = all.filter((f) => !covered.has(skeleton(f.message)) && !allowed.has(skeleton(f.message)));

  console.log(`Scanned ${files.length} files, ${all.length} user-facing throws.`);
  console.log(`Catalog codes: ${Object.keys(catalog).length}, allowlist: ${ALLOW_INTERNAL.length}.`);

  if (missing.length === 0) {
    console.log('\n✓ Every user-facing server error has a translation (or is allowlisted).');
    process.exit(0);
  }

  console.log(`\n✗ ${missing.length} user-facing error message(s) have no zh translation:\n`);
  for (const m of missing) console.log(`  ${m.file}:${m.line}\n    ${JSON.stringify(m.message)}`);
  console.log('\nFix: add each to the four errors.json catalogs, or to ALLOW_INTERNAL if it must stay English.');
  process.exit(1);
}

main();
