/**
 * generate-field-registry.js
 *
 * One-time import script: parses ai-workspace/reference-data/treedata5.txt
 * and writes core/src/builtins/fieldRegistry.js.
 *
 * Run from the architect-language-tools/ directory:
 *   node scripts/generate-field-registry.js
 *
 * Commit the output file. Re-run when the source data is updated.
 */

import * as fs from "fs";
import * as path from "path";

import { fileURLToPath } from "url";
import { dirname } from "path";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const INPUT  = path.join(__dirname, "../../ai-workspace/reference-data/treedata5.txt");
const OUTPUT = path.join(__dirname, "../core/src/builtins/fieldRegistry.js");

// Field entries appear at multiple nesting depths (8–11+ digit IDs).
// Standard convention: hXXy_Name  (XX = 2-character table code (letters or digits), y = type prefix, underscore separator)
// Some CR-table fields use camelCase without underscore: hCRfFieldName
// Both patterns are captured.
const FIELD_NAME_PATTERN = /^h[A-Z][A-Z0-9][a-z](_|[A-Z])/;
const ENTRY_ID_PATTERN   = /^\s*[0-9]+:/;

const entries = {};

const lines = fs.readFileSync(INPUT, "utf8").split(/\r?\n/);
for (const line of lines) {
    if (!ENTRY_ID_PATTERN.test(line)) continue;

    const trimmed = line.trim();
    const cols = trimmed.split(":");
    // cols: [entry_id, parent_id, name, type, description, help_url]
    if (cols.length < 4) continue;

    const name = cols[2].trim();
    if (!FIELD_NAME_PATTERN.test(name)) continue;

    const type      = cols[3].trim() || "STRING";
    const tableCode = name.slice(1, 3).toUpperCase();
    const key       = name.toLowerCase();

    if (!entries[key]) {
        entries[key] = { canonical: name, type, tableCode };
    }
}

const entryCount = Object.keys(entries).length;

// Build sorted output for stable diffs
const sortedKeys = Object.keys(entries).sort();

const lines_out = [
    "/**",
    " * fieldRegistry.js — database field handle registry.",
    " *",
    ` * Generated from ai-workspace/reference-data/treedata5.txt (${entryCount} entries).`,
    " * Re-generate with: node scripts/generate-field-registry.js",
    " *",
    " * Key:   lowercase field name",
    " * Value: { canonical: string, type: string, tableCode: string }",
    " */",
    "",
    "\"use strict\";",
    "",
    "const FIELD_REGISTRY = {"
];

for (const key of sortedKeys) {
    const { canonical, type, tableCode } = entries[key];
    lines_out.push(`    ${JSON.stringify(key)}: { canonical: ${JSON.stringify(canonical)}, type: ${JSON.stringify(type)}, tableCode: ${JSON.stringify(tableCode)} },`);
}

lines_out.push("};");
lines_out.push("");
lines_out.push("/**");
lines_out.push(" * Returns true if `name` (any casing) is a known field handle.");
lines_out.push(" */");
lines_out.push("function isKnownFieldHandle(name) {");
lines_out.push("    return Object.prototype.hasOwnProperty.call(FIELD_REGISTRY, name.toLowerCase());");
lines_out.push("}");
lines_out.push("");
lines_out.push("/**");
lines_out.push(" * Returns { canonical, type, tableCode } for a field handle, or null if unknown.");
lines_out.push(" */");
lines_out.push("function getFieldEntry(name) {");
lines_out.push("    return FIELD_REGISTRY[name.toLowerCase()] || null;");
lines_out.push("}");
lines_out.push("");
lines_out.push("module.exports = { FIELD_REGISTRY, isKnownFieldHandle, getFieldEntry };");
lines_out.push("");

fs.writeFileSync(OUTPUT, lines_out.join("\n"), "utf8");
console.log(`Written ${entryCount} field entries to ${OUTPUT}`);
