import { expect } from "e2e";
import { readFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { test, WEB, makeState, runPromise } from "./t3.ts";
import { T3_HOME } from "../e2e.config.ts";

test("A queued child follow-up waits for its nested delegate and delivers FINAL once", WEB, async ({t3, app, screen}) => {
  const project = await t3.project("delegation-proof");
  const { cli } = makeState(T3_HOME);
  const started = await runPromise(cli(["thread", "start", project, "Run the delegation proof as parent A.", "--title", "Nested delegation follow-up", "--provider", "proofReplay", "--model", "delegation", "--json"]));
  const thread = JSON.parse(started.stdout);
  await t3.open(thread);
  await screen.getByText("During C:", {exact:false}).waitFor({state:"visible",timeout:90000});
  await app.screenshot("while-nested-delegate-runs");
  const duringC = await screen.getByText("During C:", {exact:false}).textContent();
  const state = JSON.parse(await readFile(join(dirname(process.env.T3_PROOF_AGENT_PATH!), `session-${thread.threadId}.json`), "utf8"));
  await t3.open({threadId:state.original.childThreadId});
  await screen.getByText("INTERIM", {exact:true}).waitFor({state:"visible"});
  await app.screenshot("child-waits-for-nested-check");
  await t3.open(thread);
  await screen.getByText("During B wake:", {exact:false}).waitFor({state:"visible",timeout:90000});
  await app.screenshot("while-child-processes-completion-wake");
  const duringWake = await screen.getByText("During B wake:", {exact:false}).textContent();
  await new Promise(resolve=>setTimeout(resolve,25000));
  await app.screenshot("automatic-final-delivery");
  await t3.open({threadId:state.original.childThreadId});
  await screen.getByText("FINAL with CHECK", {exact:true}).waitFor({state:"visible",timeout:30000});
  await app.screenshot("child-final-reply");
  await t3.open(thread);
  expect(duringC).toContain("During C: follow-up status=running; summary=null; original=READY");
  expect(duringWake).toContain("During B wake: follow-up status=running; summary=null; original=READY");
  await expect(screen.getByText("Automatic follow-up delivery: FINAL with CHECK",{exact:false})).toHaveCount(1);
  await expect(screen.getByText("Original result remains: READY",{exact:false})).toBeVisible();
});
