import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { hostname } from "node:os";
import { setTimeout as delay } from "node:timers/promises";
import postgres from "postgres";

const databaseUrl = process.env.AWP_TEST_POSTGRES_URL;
const namespace = process.env.AWP_WORKSPACE_NAMESPACE ?? "awp-golive";
if (!databaseUrl) throw new Error("AWP_TEST_POSTGRES_URL is required");

function kubectl(args: string[]): string {
  return execFileSync("kubectl", args, { encoding: "utf8" }).trim();
}

const sql = postgres(databaseUrl, { max: 1 });
const [run] = await sql<{ id: string }[]>`
  select id from agent_runs order by created_at desc limit 1
`;
assert.ok(run?.id, "a canonical AgentRun must exist before AC-12 verification");
const agentRunId = run.id;
const [attemptCount] = await sql<{ count: number }[]>`
  select count(*)::int as count
  from attempts
  where agent_run_id = ${agentRunId}
    and provider_id is not null
    and account_id is not null
    and model is not null
`;
assert.equal(attemptCount?.count, 1);
await sql.end({ timeout: 5 });

const deadline = Date.now() + 120_000;
let podJson = "";
while (Date.now() < deadline) {
  try {
    podJson = kubectl([
      "-n",
      namespace,
      "get",
      "pods",
      "-l",
      `awp.agent-run-id=${agentRunId}`,
      "-o",
      "json",
    ]);
    const parsed = JSON.parse(podJson) as {
      items: Array<{
        metadata: { name: string };
        spec: { nodeName?: string };
        status: { phase?: string };
      }>;
    };
    if (parsed.items.length === 1 && parsed.items[0]?.status.phase === "Running") {
      const pod = parsed.items[0];
      assert.ok(pod);
      assert.ok(pod.spec.nodeName, "AgentRun pod must be assigned to a cluster node");
      assert.notEqual(pod.spec.nodeName, hostname());
      assert.match(pod.metadata.name, /^awp-/);
      process.stdout.write(
        `AC-12 PASS: AgentRun ${agentRunId} is Running in pod ${pod.metadata.name} on cluster node ${pod.spec.nodeName}\n`,
      );
      process.exit(0);
    }
  } catch {
    // Kubernetes may not have observed the newly committed AgentRun yet.
  }
  await delay(500);
}

throw new Error(
  `AC-12 timed out waiting for exactly one Running pod labelled awp.agent-run-id=${agentRunId}: ${podJson}`,
);
