#!/usr/bin/env node
/** Ensure app/healthcare routes remain wired; URLs unchanged. */
import { existsSync, readFileSync, 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 HC = join(ROOT, "app", "healthcare");

const LAYOUTS = [
  "layout.tsx",
  "patient/layout.tsx",
  "doctor/layout.tsx",
  "reception/layout.tsx",
  "clinic/layout.tsx",
  "hospital/layout.tsx",
  "pharmacy-portal/layout.tsx",
  "admin/layout.tsx",
  "site/layout.tsx",
];

/** @type {string[]} */
const issues = [];

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

if (!existsSync(HC)) {
  console.error("❌ app/healthcare missing");
  process.exit(1);
}

for (const l of LAYOUTS) {
  if (!existsSync(join(HC, l))) issues.push(`Missing layout: app/healthcare/${l}`);
}

const pages = walkPages(HC);
if (pages.length < 90) issues.push(`Expected ~100 pages, found ${pages.length}`);

for (const page of pages) {
  const rel = relative(ROOT, page).split(sep).join("/");
  const content = readFileSync(page, "utf8");
  if (!/export\s+(default|\{)/.test(content)) {
    issues.push(`${rel}: missing default export`);
  }
  const lines = content.split("\n").length;
  if (lines > 20 && !content.includes("@/src/modules/healthcare") && !content.includes("router.replace")) {
    issues.push(`${rel}: route file should re-export from src/modules/healthcare (${lines} lines)`);
  }
}

console.log("Healthcare Route Validation\n");
console.log(`Pages: ${pages.length}`);

if (issues.length) {
  console.error(`\n❌ ${issues.length} issue(s):`);
  for (const i of issues) console.error(`   - ${i}`);
  process.exit(1);
}
console.log("\n✅ Routes and layouts intact");
process.exit(0);
