/// <reference lib="dom" />
import { spawn, type ChildProcess } from "node:child_process";
import { mkdir, writeFile } from "node:fs/promises";
import { createServer } from "node:net";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { prepareHome } from "./start-app.ts";
import { environmentId, makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

// Proof viewport: 1440 × 1100, light theme (configured in e2e.config.ts).
const pause = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
const freePort = () => new Promise<number>((resolve) => {
  const server = createServer();
  server.listen(0, "127.0.0.1", () => {
    const port = (server.address() as {port: number}).port;
    server.close(() => resolve(port));
  });
});
async function until<T>(read: () => Promise<T>, done: (value: T) => boolean, label: string) {
  const deadline = Date.now() + 180_000;
  while (Date.now() < deadline) {
    const value = await read();
    if (done(value)) return value;
    await pause(150);
  }
  throw new Error(`STEP_TIMEOUT: ${label}`);
}

test("Linked workflow recovers its full reply after newer turns push it onto older pages", WEB,
 async ({ t3, app, screen, browser }) => {
  const home = `${T3_HOME}-workflow-origin`;
  const port = await freePort();
  const origin = `http://127.0.0.1:${port}`;
  const remoteOrigin = app.baseUrl ?? "";
  const remote = makeState(T3_HOME);
  const local = makeState(home);
  const project = await t3.project("linked-reply-demo");
  await runPromise(prepareHome(home));
  let child: ChildProcess | undefined;
  const start = async () => {
    child = spawn(process.execPath, ["apps/server/src/bin.ts", "serve", "--host", "127.0.0.1", "--port", String(port), "--base-dir", home, "--dev-url", remoteOrigin], {
      cwd: APP_DIR,
      env: {...process.env, T3CODE_DEV_SEED: "0", T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "0", T3CODE_ENVIRONMENT_LABEL: "Workflow origin", T3CODE_ENVIRONMENT_MACHINE_KIND: "laptop"},
      stdio: ["ignore", "pipe", "pipe"],
    });
    child.stdout?.on("data", () => {});
    child.stderr?.on("data", () => {});
    await until(async () => {
      if (child?.exitCode != null) throw new Error(`origin server exited ${child.exitCode}`);
      try { return (await fetch(`${origin}/.well-known/t3/environment`)).ok; } catch { return false; }
    }, Boolean, "origin server ready");
  };
  const stop = async () => {
    const stopping = child;
    if (!stopping || stopping.exitCode !== null) return;
    const ended = new Promise<void>((resolve) => stopping.once("exit", () => resolve()));
    stopping.kill("SIGTERM");
    await ended;
    child = undefined;
  };
  const cliJson = async (args: string[]) => JSON.parse((await runPromise(local.cli([...args, "--json"]))).stdout);
  const pairCode = async (home: string, url: string, purpose: string) => {
    const token = (await runPromise(makeState(home).cli(["auth", "session", "issue", "--token-only"]))).stdout.trim();
    const response = await fetch(`${url}/api/auth/pairing-token`, {method: "POST", headers: {authorization: `Bearer ${token}`, "content-type": "application/json"}, body: JSON.stringify(purpose === "peer-link" ? {purpose, access: "full-access"} : {})});
    if (!response.ok) throw new Error(`pairing failed: ${response.status}`);
    return (await response.json()).credential as string;
  };
  try {
    await start();
    const code = await pairCode(T3_HOME, remoteOrigin, "peer-link");
    await runPromise(Effect.gen(function* () {
      const a = yield* rpcClient(home, origin);
      const b = yield* rpcClient(T3_HOME, remoteOrigin);
      yield* a["server.updateSettings"]({patch: {linkedEnvironmentsEnabled: true, workflowsEnabled: true}});
      yield* b["server.updateSettings"]({patch: {linkedEnvironmentsEnabled: true}});
      yield* a["peerLinks.link"]({url: remoteOrigin, pairingCode: code, access: "full-access"});
    }).pipe(Effect.scoped));
    const remoteEnvironment = await runPromise(environmentId(remoteOrigin));
    const definition = `export default T3.workflow("linkedreply", {version: 1, payload: Schema.Struct({}), returns: Schema.Struct({length: Schema.Number, reply: Schema.String})}, Effect.fn(function* () {
      const result = yield* T3.agent("remote", {brief: "Demonstrate the completed change.", project: ${JSON.stringify(project)}, environment: ${JSON.stringify(remoteEnvironment)}, title: "Linked reply pagination", model: {instanceId: "devReplay", model: "showcase"}});
      return yield* T3.step("record", {returns: Schema.Struct({length: Schema.Number, reply: Schema.String})}, Effect.succeed({length: result.value.length, reply: result.value}));
    }));`;
    await mkdir(`${home}/workflows`, {recursive: true});
    await writeFile(`${home}/workflows/linkedreply.ts`, definition);
    // Restart loads the same definition deterministically before either run.
    await stop();
    await start();
    console.log("Control: origin stays connected");
    const control = await cliJson(["workflow", "start", "linkedreply", "--key", "control"]);
    const controlDone = await until(() => cliJson(["workflow", "show", control.run.runId]), x => x.run.status === "completed", "control completed");
    const expected = controlDone.run.result.reply as string;
    if (!expected.length) throw new Error("Control returned no reply");
    console.log(`Control completed: ${expected.length} characters`);
    const started = await cliJson(["workflow", "start", "linkedreply", "--key", "reconnect"]);
    const running = await until(() => cliJson(["workflow", "show", started.run.runId]), x => x.steps.some((s: any) => s.threadId), "remote turn starts");
    const step = running.steps.find((s: any) => s.name === "remote");
    await stop();
    console.log("Origin stopped; queueing 31 newer turns on the remote thread");
    for (let i = 0; i < 30; i++) await runPromise(remote.cli(["thread", "send", step.threadId, `Follow-up ${i + 1}`, "--json"]));
    await runPromise(remote.cli(["thread", "send", step.threadId, "Final follow-up", "--wait", "--json"]));
    console.log("All newer turns completed; restart origin");
    await start();
    const completed = await until(() => cliJson(["workflow", "show", started.run.runId]), x => x.run.status === "completed", "resumed workflow completed");
    console.log(`Recovered reply: ${completed.run.result.length} characters (expected ${expected.length})`);
    // Connect the real browser to the workflow's originating environment.
    const browserCode = await pairCode(home, origin, "browser");
    await t3.open("/settings/connections");
    await screen.getByRole("button", "Add environment").tap();
    const dialog = screen.getByRole("dialog");
    await dialog.getByPlaceholder("backend.example.com").fill(origin);
    // Mask the one-time credential in the recording.
    await browser.evaluate(() => {
      document.querySelector<HTMLInputElement>('input[placeholder="PAIRCODE"]')!.type = "password";
    });
    await dialog.getByPlaceholder("PAIRCODE").fill(browserCode);
    await dialog.getByRole("button", "Add environment").tap();
    await screen.getByText("Workflow origin", {exact: true}).waitFor({timeout: 60_000});
    const env = await runPromise(environmentId(origin));
    await t3.open(`/workflows?env=${env}&run=${started.run.runId}`);
    await screen.getByRole("heading", "linkedreply", {exact: false}).waitFor({timeout: 60_000});
    await screen.getByText("Finished", {exact: true}).first().waitFor();
    // Keep the completed result visible long enough for the video to capture it.
    await pause(2500);
    await app.screenshot("recovered-linked-reply");
    await pause(2500);
    expect(completed.run.result.reply, "The resumed step returns its original turn's complete final assistant reply").toBe(expected);
  } finally {
    await stop();
  }
 });
