#!/usr/bin/env node
/**
 * Generates contact-rules.ts from contact-rules.jsonc.
 *
 * The .jsonc is the source-of-truth (editable, comments, versioned in
 * source). The .ts is what mailx-store and mailx-store-web import — Android
 * has no `fs` to parse JSONC at runtime, and inlining the parsed object
 * sidesteps that constraint cleanly.
 *
 * Run via `npm run build` (prebuild hook) or directly: `node build-rules.js`.
 * Both .jsonc and generated .ts are checked in; the .ts is regenerated on
 * every build so its mtime is deterministic relative to the .jsonc.
 */
import fs from "node:fs";
import path from "node:path";

const __dirname = import.meta.dirname;
const srcPath = path.join(__dirname, "contact-rules.jsonc");
const outPath = path.join(__dirname, "contact-rules.ts");

const raw = fs.readFileSync(srcPath, "utf-8");
// Loose JSONC handler: strip // line comments and trailing commas. Avoids
// pulling in jsonc-parser as a dep for what's effectively config.
const stripped = raw
    .replace(/^\s*\/\/.*$/gm, "")
    .replace(/,(\s*[}\]])/g, "$1");
const obj = JSON.parse(stripped);

const banner = "// AUTO-GENERATED from contact-rules.jsonc — do not edit.\n" +
               "// Edit the .jsonc and run `node build-rules.js` (or `npm run build`).\n\n";
const ts = banner + `export const CONTACT_RULES = ${JSON.stringify(obj, null, 4)} as const;\n`;
fs.writeFileSync(outPath, ts);
console.log(`[mailx-types] regenerated ${path.basename(outPath)}`);
