import { spawn, spawnSync } from "node:child_process";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createServer } from "node:net";
import { rootPath } from "./src/config";

type JsonRecord = Record<string, unknown>;

const mdtodoCommit = "595de3d320b73ec006794440b32db48b3ad14d2b";
const mdtodoRepo = "https://github.com/pikasTech/unidesk";
const mdtodoSourcePath = "src/components/microservices/mdtodo/src/index.ts";

function assertCondition(condition: unknown, message: string, detail: unknown = {}): void {
  if (!condition) throw new Error(`${message}: ${JSON.stringify(detail)}`);
}

function asRecord(value: unknown, label: string): JsonRecord {
  assertCondition(typeof value === "object" && value !== null && !Array.isArray(value), `${label} must be an object`, value);
  return value as JsonRecord;
}

function manifestService(manifest: JsonRecord, environment: "dev" | "prod", serviceId: string): JsonRecord {
  const environments = asRecord(manifest.environments, "deploy.json.environments");
  const env = asRecord(environments[environment], `deploy.json.environments.${environment}`);
  const services = Array.isArray(env.services) ? env.services.map((item, index) => asRecord(item, `${environment}.services[${index}]`)) : [];
  const service = services.find((item) => item.id === serviceId);
  assertCondition(service !== undefined, `deploy.json ${environment} must include ${serviceId}`, env);
  return service as JsonRecord;
}

async function reservePort(): Promise<number> {
  const server = createServer();
  await new Promise<void>((resolve, reject) => {
    server.once("error", reject);
    server.listen(0, "127.0.0.1", resolve);
  });
  const address = server.address();
  const port = typeof address === "object" && address !== null ? address.port : 0;
  await new Promise<void>((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
  assertCondition(port > 0, "failed to reserve a local port", address);
  return port;
}

async function fetchJson(url: string): Promise<JsonRecord> {
  const response = await fetch(url);
  const text = await response.text();
  let body: unknown;
  try {
    body = JSON.parse(text) as unknown;
  } catch {
    body = { raw: text };
  }
  assertCondition(response.ok, `request failed: ${url}`, { status: response.status, body });
  return asRecord(body, `response ${url}`);
}

function assertDeployMetadata(body: JsonRecord, endpoint: "/health" | "/live"): void {
  const deploy = asRecord(body.deploy, `${endpoint}.deploy`);
  assertCondition(body.ok === true, `${endpoint} must be ok`, body);
  assertCondition(body.service === "mdtodo", `${endpoint} service mismatch`, body);
  assertCondition(deploy.serviceId === "mdtodo", `${endpoint} deploy service id mismatch`, deploy);
  assertCondition(deploy.repo === mdtodoRepo, `${endpoint} deploy repo mismatch`, deploy);
  assertCondition(deploy.commit === mdtodoCommit, `${endpoint} deploy commit mismatch`, deploy);
  assertCondition(deploy.requestedCommit === mdtodoCommit, `${endpoint} requested commit mismatch`, deploy);
}

function assertDesiredCommitIncludesHealthMetadata(): void {
  const manifest = asRecord(JSON.parse(readFileSync(rootPath("deploy.json"), "utf8")) as unknown, "deploy.json");
  for (const environment of ["dev", "prod"] as const) {
    const service = manifestService(manifest, environment, "mdtodo");
    assertCondition(service.repo === mdtodoRepo, `mdtodo ${environment} repo mismatch`, service);
    assertCondition(service.commitId === mdtodoCommit, `mdtodo ${environment} desired commit must include health deploy metadata`, service);
  }

  const desiredSource = spawnSync("git", ["show", `${mdtodoCommit}:${mdtodoSourcePath}`], {
    cwd: rootPath(),
    encoding: "utf8",
    maxBuffer: 4 * 1024 * 1024,
  });
  assertCondition(desiredSource.status === 0, "must be able to inspect the desired mdtodo source commit", {
    status: desiredSource.status,
    stderr: desiredSource.stderr.slice(-1000),
  });
  assertCondition(desiredSource.stdout.includes("UNIDESK_DEPLOY_SERVICE_ID"), "desired mdtodo source must read deploy service id", {});
  assertCondition(desiredSource.stdout.includes("UNIDESK_DEPLOY_COMMIT"), "desired mdtodo source must read deploy commit", {});
  assertCondition(desiredSource.stdout.includes("UNIDESK_DEPLOY_REQUESTED_COMMIT"), "desired mdtodo source must read deploy requested commit", {});
  assertCondition(desiredSource.stdout.includes("deploy:"), "desired mdtodo source must expose deploy metadata in health/live payloads", {});
}

async function main(): Promise<void> {
  assertDesiredCommitIncludesHealthMetadata();

  const port = await reservePort();
  const tempRoot = mkdtempSync(join(tmpdir(), "unidesk-mdtodo-health-"));
  const workspace = join(tempRoot, "workspace");
  const logDir = join(tempRoot, "logs");
  mkdirSync(workspace, { recursive: true });
  mkdirSync(logDir, { recursive: true });
  writeFileSync(join(workspace, "issue-9-mdtodo.md"), "# Issue 9 MDTODO\n\n## R1 Health metadata proof\n\nLocal contract seed.\n", "utf8");

  const stdout: string[] = [];
  const stderr: string[] = [];
  const child = spawn("bun", ["run", "src/index.ts"], {
    cwd: rootPath("src", "components", "microservices", "mdtodo"),
    env: {
      ...process.env,
      HOST: "127.0.0.1",
      PORT: String(port),
      MDTODO_ROOT_DIR: workspace,
      LOG_FILE: join(logDir, "mdtodo.jsonl"),
      UNIDESK_DEPLOY_SERVICE_ID: "mdtodo",
      UNIDESK_DEPLOY_REPO: mdtodoRepo,
      UNIDESK_DEPLOY_COMMIT: mdtodoCommit,
      UNIDESK_DEPLOY_REQUESTED_COMMIT: mdtodoCommit,
    },
    stdio: ["ignore", "pipe", "pipe"],
  });
  child.stdout.setEncoding("utf8");
  child.stderr.setEncoding("utf8");
  child.stdout.on("data", (chunk) => stdout.push(String(chunk)));
  child.stderr.on("data", (chunk) => stderr.push(String(chunk)));

  try {
    let health: JsonRecord | null = null;
    for (let attempt = 1; attempt <= 80; attempt += 1) {
      if (child.exitCode !== null) break;
      try {
        health = await fetchJson(`http://127.0.0.1:${port}/health`);
        break;
      } catch {
        await new Promise((resolve) => setTimeout(resolve, 100));
      }
    }
    assertCondition(health !== null, "mdtodo local health endpoint did not become ready", {
      exitCode: child.exitCode,
      stdout: stdout.join("").slice(-2000),
      stderr: stderr.join("").slice(-2000),
    });
    assertDeployMetadata(health as JsonRecord, "/health");
    assertCondition((health as JsonRecord).fileCount === 1, "/health should scan the seeded MDTODO file", health);

    const live = await fetchJson(`http://127.0.0.1:${port}/live`);
    assertDeployMetadata(live, "/live");
    assertCondition(existsSync(join(logDir, "mdtodo.jsonl")) || stdout.join("").includes("service_started"), "local service should produce visible startup output", {
      stdout: stdout.join("").slice(-1200),
      stderr: stderr.join("").slice(-1200),
    });
  } finally {
    child.kill("SIGTERM");
    await new Promise((resolve) => setTimeout(resolve, 100));
    if (child.exitCode === null) child.kill("SIGKILL");
    rmSync(tempRoot, { recursive: true, force: true });
  }

  process.stdout.write(`${JSON.stringify({
    ok: true,
    checks: [
      "deploy.json dev/prod mdtodo desired commit points at a health-metadata-capable source commit",
      "desired mdtodo source commit reads UNIDESK_DEPLOY_* metadata",
      "local /health exposes deploy.serviceId, repo, commit and requestedCommit",
      "local /live exposes the same deploy metadata",
      "local /health proves a readable seeded MDTODO markdown workspace",
    ],
    serviceId: "mdtodo",
    desiredCommit: mdtodoCommit,
  }, null, 2)}\n`);
}

if (import.meta.main) {
  await main();
}
