#!/usr/bin/env node
/** Bulk-update Accounting module import paths after migration to src/modules/accounting. */
import { readFileSync, writeFileSync, readdirSync, statSync } from "node:fs";
import { join, relative } from "node:path";
import { fileURLToPath } from "node:url";

const ROOT = join(fileURLToPath(new URL(".", import.meta.url)), "..");
const EXT = new Set([".ts", ".tsx"]);
const SKIP = new Set(["node_modules", ".next"]);

const GLOBAL_REPLACEMENTS = [
  ["@/components/accounting/", "@/src/modules/accounting/components/"],
  ["@/lib/accounting-api", "@/src/modules/accounting/services/accounting-api"],
  ["@/lib/accounting-nav", "@/src/modules/accounting/constants/accounting-nav"],
  ["@/lib/accounting-scoreboard", "@/src/modules/accounting/utils/accounting-scoreboard"],
];

const ACCOUNTING_SCOPE_REPLACEMENTS = [
  ["@/components/ds", "@/src/shared/ui"],
];

function walk(dir, files = []) {
  for (const entry of readdirSync(dir)) {
    if (SKIP.has(entry)) continue;
    const full = join(dir, entry);
    if (statSync(full).isDirectory()) walk(full, files);
    else if (EXT.has(entry.slice(entry.lastIndexOf(".")))) files.push(full);
  }
  return files;
}

function isAccountingScope(rel) {
  return rel.startsWith("app/accounting/") || rel.startsWith("src/modules/accounting/");
}

let changed = 0;
for (const file of walk(ROOT)) {
  const rel = relative(ROOT, file).replace(/\\/g, "/");
  if (rel.startsWith("scripts/migrate-accounting-imports.mjs")) continue;
  let content = readFileSync(file, "utf8");
  const original = content;
  for (const [from, to] of GLOBAL_REPLACEMENTS) {
    content = content.split(from).join(to);
  }
  if (isAccountingScope(rel)) {
    for (const [from, to] of ACCOUNTING_SCOPE_REPLACEMENTS) {
      content = content.split(from).join(to);
    }
  }
  if (content !== original) {
    writeFileSync(file, content, "utf8");
    changed++;
  }
}

console.log(`Updated imports in ${changed} files.`);
