#!/usr/bin/env node
/** Align module page export names with route re-export adapters. */
import { readFileSync, writeFileSync, readdirSync, statSync } from "node:fs";
import { join, relative, sep } from "node:path";
import { fileURLToPath } from "node:url";

const ROOT = join(fileURLToPath(new URL(".", import.meta.url)), "..");
const APP = join(ROOT, "app", "accounting");

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

let fixed = 0;
for (const pageFile of walkPages(APP)) {
  const routeContent = readFileSync(pageFile, "utf8");
  const match = routeContent.match(
    /export\s+\{\s*(\w+)\s+as\s+default\s+\}\s+from\s+["'](@\/src\/modules\/accounting\/pages\/[^"']+)["']/
  );
  if (!match) continue;

  const exportName = match[1];
  let importPath = match[2].replace("@/src/modules/accounting/pages/", "");
  if (!importPath || importPath.endsWith("/")) importPath = "dashboard";

  const moduleFile = join(ROOT, "src", "modules", "accounting", "pages", `${importPath}.tsx`);
  if (!statSync(moduleFile, { throwIfNotFound: false })?.isFile()) {
    console.error(`Missing module file: ${moduleFile}`);
    continue;
  }

  let moduleContent = readFileSync(moduleFile, "utf8");
  const original = moduleContent;

  if (moduleContent.includes(`export function ${exportName}`)) continue;

  if (/export function Page\b/.test(moduleContent)) {
    moduleContent = moduleContent.replace(/export function Page\b/, `export function ${exportName}`);
  } else if (/export default function Page\b/.test(moduleContent)) {
    moduleContent = moduleContent.replace(/export default function Page\b/, `export function ${exportName}`);
  } else if (/export default function (\w+)/.test(moduleContent)) {
    moduleContent = moduleContent.replace(/export default function (\w+)/, `export function $1`);
  }

  if (moduleContent !== original) {
    writeFileSync(moduleFile, moduleContent, "utf8");
    fixed++;
  }

  const fixedRoute = `"use client";\n\nexport { ${exportName} as default } from "@/src/modules/accounting/pages/${importPath}";\n`;
  if (routeContent !== fixedRoute) {
    writeFileSync(pageFile, fixedRoute, "utf8");
  }
}

console.log(`Fixed export names in ${fixed} module pages.`);
