#!/usr/bin/env node
/** Resolve import/export name collisions in thin accounting page wrappers. */
import { readFileSync, writeFileSync, readdirSync, statSync } from "node:fs";
import { join } from "node:path";
import { fileURLToPath } from "node:url";

const ROOT = join(fileURLToPath(new URL(".", import.meta.url)), "..");
const PAGES = join(ROOT, "src", "modules", "accounting", "pages");

function walk(dir, files = []) {
  for (const entry of readdirSync(dir)) {
    const full = join(dir, entry);
    if (statSync(full).isDirectory()) walk(full, files);
    else if (entry.endsWith(".tsx")) files.push(full);
  }
  return files;
}

const re =
  /^((?:\s*"use client";\s*)?)import \{ (\w+) \} from ([^;]+);\s*export function \2\(\) \{ return <\2 \/>; \}\s*$/s;

let fixed = 0;
for (const file of walk(PAGES)) {
  const content = readFileSync(file, "utf8");
  const m = content.match(re);
  if (!m) continue;
  const [, prefix, name, from] = m;
  const alias = `${name}Screen`;
  const next = `${prefix || ""}import { ${name} as ${alias} } from ${from};\nexport function ${name}() { return <${alias} />; }\n`;
  writeFileSync(file, next, "utf8");
  fixed++;
}

console.log(`Fixed ${fixed} import/export collisions.`);
