import { existsSync, readFileSync } from "node:fs";
import { join, resolve } from "node:path";

export interface DoctorCheck {
  name: string;
  ok: boolean;
  detail: string;
}

export function inspectProject(appRoot: string): DoctorCheck[] {
  const root = resolve(appRoot);
  const checks: DoctorCheck[] = [];
  const pkgPath = join(root, "package.json");
  checks.push({
    name: "Bun runtime",
    ok: typeof Bun !== "undefined",
    detail: typeof Bun !== "undefined" ? `v${Bun.version}` : "Bun is required",
  });
  checks.push({
    name: "package.json",
    ok: existsSync(pkgPath),
    detail: existsSync(pkgPath) ? pkgPath : "Run this command from a WrNexus project root",
  });
  const app = join(root, "app");
  checks.push({
    name: "app/pages",
    ok: existsSync(join(app, "pages")),
    detail: existsSync(join(app, "pages")) ? "page directory found" : "Create app/pages",
  });
  const config = ["wrnexus.config.ts", "wrnexus.config.mjs", "wrnexus.config.js"].find((name) =>
    existsSync(join(root, name)),
  );
  checks.push({
    name: "configuration",
    ok: !!config,
    detail: config ?? "No wrnexus.config file; framework defaults will be used",
  });
  const mobilePkg = join(root, "mobile", "package.json");
  if (existsSync(mobilePkg)) {
    try {
      const mobile = JSON.parse(readFileSync(mobilePkg, "utf8")) as {
        wrnexus?: { mode?: string };
      };
      checks.push({
        name: "mobile project",
        ok: mobile.wrnexus?.mode === "webview" || mobile.wrnexus?.mode === "native",
        detail: `mode: ${mobile.wrnexus?.mode ?? "missing"}`,
      });
    } catch {
      checks.push({
        name: "mobile project",
        ok: false,
        detail: "mobile/package.json is invalid JSON",
      });
    }
  }
  return checks;
}

export function runDoctor(appRoot: string): boolean {
  const checks = inspectProject(appRoot);
  console.log("WrNexus doctor\n");
  for (const check of checks)
    console.log(`  ${check.ok ? "✓" : "✗"} ${check.name}: ${check.detail}`);
  console.log("\n  Security dependencies: run `bun audit`");
  console.log("  Complete verification: run `bun run check`");
  return checks.every((check) => check.ok || check.name === "configuration");
}
