import { cpSync, mkdirSync, rmSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { codeQueueSourceImportPreflight, codeQueueSourceSubdir } from "./src/code-queue-source-guard";

function assert(condition: boolean, message: string): void {
  if (!condition) throw new Error(message);
}

const repoRoot = process.cwd();
const current = codeQueueSourceImportPreflight(repoRoot);
assert(current.ok, `current source should pass guard: ${JSON.stringify(current.missing.slice(0, 3))}`);

const tmpRoot = join(tmpdir(), `unidesk-code-queue-source-guard-${process.pid}`);
rmSync(tmpRoot, { recursive: true, force: true });
mkdirSync(join(tmpRoot, codeQueueSourceSubdir), { recursive: true });
cpSync(join(repoRoot, codeQueueSourceSubdir), join(tmpRoot, codeQueueSourceSubdir), { recursive: true });
mkdirSync(join(tmpRoot, "src/components/shared/src"), { recursive: true });
cpSync(join(repoRoot, "src/components/shared/src"), join(tmpRoot, "src/components/shared/src"), { recursive: true });
rmSync(join(tmpRoot, codeQueueSourceSubdir, "runtime-preflight.ts"));

const missing = codeQueueSourceImportPreflight(tmpRoot);
assert(!missing.ok, "guard should fail when runtime-preflight.ts is missing");
assert(missing.degradedReason === "missing-relative-import-target", `unexpected degradedReason: ${missing.degradedReason}`);
assert(missing.missing.some((item) => item.importer.endsWith("index.ts") && item.specifier === "./runtime-preflight"), "missing runtime-preflight import was not reported");

rmSync(tmpRoot, { recursive: true, force: true });

process.stdout.write(`${JSON.stringify({
  ok: true,
  current: {
    checkedFiles: current.checkedFiles,
    checkedImports: current.checkedImports,
  },
  missingRuntimePreflight: {
    ok: missing.ok,
    degradedReason: missing.degradedReason,
    missing: missing.missing.map((item) => ({ importer: item.importer, specifier: item.specifier })).slice(0, 5),
  },
}, null, 2)}\n`);
