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

import { loginBrowser, requireOperatorPassword } from "./auth.js";
import { approvedJourneyEnvironment, requiredEnvironment } from "./exact-journey.js";

const webUrl = requiredEnvironment(process.env, "AWP_WEB_URL");
const databaseUrl = requiredEnvironment(process.env, "AWP_TEST_POSTGRES_URL");
const playwrightModule = requiredEnvironment(process.env, "AWP_PLAYWRIGHT_MODULE");
const operatorPassword = requireOperatorPassword();
const { factoryRunId, firstTaskId } = approvedJourneyEnvironment();
const timeoutMs = Number(process.env.AWP_GOLIVE_TIMEOUT_MS ?? "120000");

const sql = postgres(databaseUrl, { max: 1 });
let rows: Array<{
  agent_run_id: string;
  project_id: string;
  attempt_id: string;
  reason: string | null;
}> = [];
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
  rows = await sql<
    { agent_run_id: string; project_id: string; attempt_id: string; reason: string | null }[]
  >`
    select ar.id as agent_run_id, fr.project_id, a.id as attempt_id, a.reason
    from factory_runs fr
    join agent_runs ar
      on ar.factory_run_id = fr.id
     and ar.task_id = fr.task_id
    join attempts a on a.agent_run_id = ar.id
    where fr.id = ${factoryRunId}
      and fr.task_id = ${firstTaskId}
      and a.status = 'terminal'
      and a.selection_provenance->>'kind' = 'initial'
      and a.reason = 'injected non-zero agent exit 17'
    order by a.created_at, a.id
  `;
  if (rows.length > 0) break;
  await delay(100);
}
await sql.end({ timeout: 5 });
assert.equal(
  rows.length,
  1,
  "the canonical first Task must retain exactly one injected failed Attempt",
);
const row = rows[0]!;
assert.ok(row.reason);

const { chromium } = await import(playwrightModule);
const browser = await chromium.launch({ headless: true });
try {
  const page = await browser.newPage();
  await loginBrowser(page, webUrl, operatorPassword);
  await page.goto(
    `${webUrl}/factory-runs/${encodeURIComponent(factoryRunId)}?project=${encodeURIComponent(row.project_id)}&tab=agent-runs`,
    { waitUntil: "networkidle" },
  );
  const run = page.locator(
    `[data-agent-run-id="${row.agent_run_id}"][data-run-health="failure-recorded"]`,
  );
  await run.getByText("Failure recorded", { exact: true }).first().waitFor();
  await run.getByText("Attempt failure", { exact: true }).first().waitFor();
  await run.getByText(row.reason, { exact: true }).first().waitFor();
  assert.equal(await run.locator(`[data-attempt-id="${row.attempt_id}"]`).count(), 1);
  process.stdout.write(
    `AC-25 PASS: exact FactoryRun ${factoryRunId} AgentRun ${row.agent_run_id} visibly distinguishes injected Attempt ${row.attempt_id} and its reason\n`,
  );
} finally {
  await browser.close();
}
