/**
 * SET 50 — emit per-build web version identity.
 *
 * Writes BEFORE vite so `web/public/version.json` is copied into dist.
 * Also bakes `web/src/generated/webVersion.ts` so the mounted bundle knows
 * its own buildId (boot-only fetch would miss a deploy that landed before
 * the first successful poll).
 */
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { randomBytes } from 'node:crypto';

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
export const DEFAULT_VERSION_JSON = path.join(ROOT, 'web', 'public', 'version.json');
export const DEFAULT_GENERATED_TS = path.join(ROOT, 'web', 'src', 'generated', 'webVersion.ts');

export type WebVersionEmit = { buildId: string; generatedAt: string };

export function makeWebVersion(now = new Date()): WebVersionEmit {
  const generatedAt = now.toISOString();
  const buildId = `${now.getTime().toString(36)}-${randomBytes(3).toString('hex')}`;
  return { buildId, generatedAt };
}

export function emitWebVersion(opts?: {
  outJson?: string;
  outTs?: string;
  version?: WebVersionEmit;
}): WebVersionEmit {
  const version = opts?.version ?? makeWebVersion();
  const outJson = opts?.outJson ?? DEFAULT_VERSION_JSON;
  const outTs = opts?.outTs ?? DEFAULT_GENERATED_TS;
  fs.mkdirSync(path.dirname(outJson), { recursive: true });
  fs.mkdirSync(path.dirname(outTs), { recursive: true });
  fs.writeFileSync(outJson, `${JSON.stringify(version, null, 2)}\n`, 'utf8');
  fs.writeFileSync(
    outTs,
    `/** SET 50 — baked by scripts/emit-web-version.ts (do not edit by hand). */\n`
      + `export const WEB_BUILD_ID = ${JSON.stringify(version.buildId)};\n`
      + `export const WEB_GENERATED_AT = ${JSON.stringify(version.generatedAt)};\n`,
    'utf8',
  );
  return version;
}

if (import.meta.url === `file://${process.argv[1]}` || process.argv[1]?.endsWith('emit-web-version.ts')) {
  const v = emitWebVersion();
  console.log(`[emit-web-version] buildId=${v.buildId}`);
}
