#!/usr/bin/env node
/** Bulk-update Healthcare module import paths after migration to src/modules/healthcare. */
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/healthcare/ui", "@/src/modules/healthcare/design-system"],
  ["@/components/healthcare/design-system", "@/src/modules/healthcare/design-system"],
  ["@/components/healthcare/pages/", "@/src/modules/healthcare/pages/"],
  ["@/components/healthcare/HealthcarePortalShell", "@/src/modules/healthcare/components/HealthcarePortalShell"],
  ["@/components/healthcare/PublicHealthcareLayout", "@/src/modules/healthcare/components/PublicHealthcareLayout"],
  ["@/components/healthcare/createPortalLayout", "@/src/modules/healthcare/components/createPortalLayout"],
  ["@/lib/healthcare-api", "@/src/modules/healthcare/services/healthcare-api"],
  ["@/lib/healthcare-portals", "@/src/modules/healthcare/constants/portals"],
  ["@/hooks/useHealthcareLookups", "@/src/modules/healthcare/hooks/useHealthcareLookups"],
  ["@/hooks/useHealthcarePatientContext", "@/src/modules/healthcare/hooks/useHealthcarePatientContext"],
  ["@/hooks/useHealthcareDoctorContext", "@/src/modules/healthcare/hooks/useHealthcareDoctorContext"],
];

const HEALTHCARE_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 isHealthcareScope(rel) {
  return rel.startsWith("app/healthcare/") || rel.startsWith("src/modules/healthcare/");
}

let changed = 0;
for (const file of walk(ROOT)) {
  const rel = relative(ROOT, file).replace(/\\/g, "/");
  if (rel.startsWith("scripts/migrate-healthcare-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 (isHealthcareScope(rel)) {
    for (const [from, to] of HEALTHCARE_SCOPE_REPLACEMENTS) {
      content = content.split(from).join(to);
    }
  }
  if (content !== original) {
    writeFileSync(file, content, "utf8");
    changed++;
  }
}

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