/**
 * generate-help-registry.js
 *
 * Generates core/src/builtins/helpRegistry.js from
 * ai-workspace/reference-data/treedata5.txt.
 *
 * Run from the architect-language-tools/ directory:
 *   node scripts/generate-help-registry.js
 *
 * Commit the output file. Re-run when the source data is updated.
 *
 * Field handles (hXXy_Name / hCRfName pattern) are NOT stored in the
 * generated map — getHelpPage() derives their page from the table code
 * at runtime so the registry stays compact.
 */

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/helpRegistry.js");

// treedata5 column layout (colon-separated):
//   0: entry_id   1: parent_id   2: name   3: type   4: description   5: help_url
const NAME_COL     = 2;
const HELP_URL_COL = 5;

// Field handles are resolved dynamically — skip them here.
const FIELD_HANDLE_RE = /^h[A-Z][A-Z0-9][a-z]/;

const entries = {};  // UPPERCASE name → help_url (first wins)

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

    // Skip the file header (starts with *)
    if (trimmed.startsWith("*")) continue;

    // Must look like an entry (starts with a digit)
    if (!/^[0-9]/.test(trimmed)) continue;

    const cols = trimmed.split(":");
    if (cols.length < 6) continue;

    let name    = cols[NAME_COL].trim();
    const page  = cols[HELP_URL_COL].trim();

    if (!name || !page) continue;

    // Skip category/group labels — they contain spaces (e.g. "Chart of Accounts")
    if (name.includes(" ")) continue;

    // Strip leading # so cursor-word lookup (which never includes #) works.
    // "#IF" → "IF", "#VAR" → "VAR", plain "LENGTH" stays "LENGTH".
    if (name.startsWith("#")) name = name.slice(1);
    if (!name) continue;

    // Skip field handles — getHelpPage() handles these via pattern matching.
    if (FIELD_HANDLE_RE.test(name)) continue;

    const key = name.toUpperCase();
    if (!entries[key]) {
        entries[key] = page;
    }
}

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

const out = [
    "/**",
    " * helpRegistry.js — contextual help page map for the Acurity language.",
    " *",
    ` * Generated from ai-workspace/reference-data/treedata5.txt (${entryCount} entries).`,
    " * Re-generate with: node scripts/generate-help-registry.js",
    " *",
    " * Key:   UPPERCASE token name (# prefix stripped)",
    " * Value: help page filename, optionally with #anchor (e.g. Time.htm,",
    " *        Global_Variables.htm#DB_STATUS)",
    " *",
    " * Field handles (hXXy_... / hCRfName...) are NOT stored here — getHelpPage()",
    " * derives their page from the table code at runtime.",
    " */",
    "",
    "\"use strict\";",
    "",
    "const HELP_REGISTRY = {"
];

for (const key of sortedKeys) {
    out.push(`    ${JSON.stringify(key)}: ${JSON.stringify(entries[key])},`);
}

out.push("};");
out.push("");
out.push("/** Field handle pattern — same as fieldRegistry generator. */");
out.push("const FIELD_HANDLE_RE = /^h[A-Z][A-Z0-9][a-z]/i;");
out.push("");
out.push("/**");
out.push(" * Returns the help page filename (possibly with #anchor) for a token name,");
out.push(" * or null if no documentation is available.");
out.push(" *");
out.push(" * Accepts any casing — lookup is case-insensitive.");
out.push(" * The # prefix used in HASH-ON mode (e.g. #IF, #VAR) should be stripped");
out.push(" * before calling; pass just the bare keyword.");
out.push(" *");
out.push(" * Field handles (e.g. hCAz_Account_Code) are handled by deriving the");
out.push(" * table page from chars 1–2 of the handle (hCA.htm, hMM.htm, etc.).");
out.push(" */");
out.push("function getHelpPage(name) {");
out.push("    if (!name) return null;");
out.push("    const upper = name.toUpperCase();");
out.push("    if (Object.prototype.hasOwnProperty.call(HELP_REGISTRY, upper)) {");
out.push("        return HELP_REGISTRY[upper];");
out.push("    }");
out.push("    // Field handle fallback: hCAz_Account_Code → hCA.htm");
out.push("    if (FIELD_HANDLE_RE.test(name)) {");
out.push("        return `h${name.slice(1, 3).toUpperCase()}.htm`;");
out.push("    }");
out.push("    return null;");
out.push("}");
out.push("");
out.push("module.exports = { getHelpPage };");
out.push("");

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