import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

// The standard replay agent, with a 90-second tool recording instead of the short showcase.
const replaySource = await runPromise(Effect.gen(function* () {
  const fs = yield* FileSystem.FileSystem;
  return (yield* fs.readFileString(new URL("../../apps/server/scripts/dev-replay-agent.ts", import.meta.url).pathname))
    .replace('file: "./dev-replay/showcase_transcript.ndjson"', 'file: "./clock.ndjson"')
    .replace("const MAX_RECORDED_DELAY_MS = 2_000;", "const MAX_RECORDED_DELAY_MS = 120_000;");
}));
const update = (value: object, afterMs?: number) => ({ type: "emit_inbound", afterMs, frame: { kind: "notification", method: "session/update", params: { sessionId: "clock", update: value } } });
const transcript = [
  { type: "expect_outbound", frame: { kind: "request", method: "session/prompt" } },
  update({ sessionUpdate: "tool_call", toolCallId: "sleep", kind: "execute", title: "sleep 90", status: "in_progress", rawInput: { command: "sleep 90" } }),
  update({ sessionUpdate: "tool_call_update", toolCallId: "sleep", status: "completed" }, 90_000),
  update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "done" } }),
  { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
].map(frame => JSON.stringify(frame)).join("\n");

test("A steering restart preserves elapsed work in the same run", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Clock demo", { "replay.ts": replaySource, "clock.ndjson": transcript });
  await runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    const file = (yield* Path.Path).join(T3_HOME, "userdata/settings.json");
    const settings = JSON.parse(yield* fs.readFileString(file));
    yield* fs.writeFileString(file, JSON.stringify({ ...settings, providerInstances: { ...settings.providerInstances,
      clockReplay: { displayName: "Clock replay", driver: "acpRegistry", enabled: true, config: { source: "local", customModels: ["showcase"], commandPath: process.execPath, commandArgs: [`${project}/replay.ts`] } },
    } }));
  }));
  const { cli } = makeState(T3_HOME);
  const result = await runPromise(cli(["thread", "start", project, 'Run sleep 90 then reply with just done.', "--title", "Steering clock", "--provider", "clockReplay", "--model", "showcase", "--json"]));
  const thread = JSON.parse(result.stdout);
  await t3.open(thread);
  await screen.getByText("Syncing messages…", { exact: false }).waitFor({ state: "hidden" });
  const clock = screen.getByText(/^Working for /).first();
  await screen.getByText(/^Working for (1[2-9]|[2-9][0-9])s$/).first().waitFor({ timeout: 60_000 });
  const seconds = (text: string | null) => {
    const match = text?.match(/Working for (?:(\d+)m )?(\d+)s/);
    if (!match) throw new Error(`Clock missing: ${text}`);
    return Number(match[1] ?? 0) * 60 + Number(match[2]);
  };
  const before = seconds(await clock.textContent());
  await app.screenshot("before-steer");
  await screen.getByRole("textbox").fill("Also explain the command after the sleep.");
  await screen.getByRole("button", "Steer message", { exact: true }).tap();
  await screen.getByText("Superseded attempt", { exact: false }).first().waitFor({ timeout: 30_000 });
  await browser.evaluate(() => new Promise(resolve => setTimeout(resolve, 2000)));
  await app.screenshot("after-steer");
  const after = seconds(await clock.textContent());
  expect(after, `Elapsed work must survive steering: before=${before}s, after=${after}s`).toBeGreaterThanOrEqual(before);
});
