import { writeFileSync } from "node:fs";
import { expect } from "e2e";
import { APP_DIR } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test(
  "Running ACP tools publish added, replaced, and cleared locations",
  WEB,
  async ({ t3, app, screen, browser }) => {
    const frames: unknown[] = [];
    const prompt = () =>
      frames.push({
        type: "expect_outbound",
        frame: { kind: "request", method: "session/prompt" },
      });
    const update = (update: unknown, afterMs = 250) =>
      frames.push({
        type: "emit_inbound",
        afterMs,
        frame: {
          kind: "notification",
          method: "session/update",
          params: { sessionId: "recorded", update },
        },
      });
    const end = () =>
      frames.push({
        type: "emit_inbound",
        frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } },
      });
    prompt();
    update({
      sessionUpdate: "agent_message_chunk",
      content: { type: "text", text: "Ready for location proof." },
    });
    end();
    prompt();
    update({
      sessionUpdate: "tool_call",
      toolCallId: "edit-1",
      title: "Edit",
      kind: "edit",
      status: "in_progress",
    });
    const phases = [
      ["added", [{ path: "<workspace>/src/location-proof.ts" }]],
      ["replaced", [{ path: "<workspace>/src/other-file.ts" }]],
      ["cleared", []],
    ] as const;
    for (const [label, locations] of phases) {
      update({ sessionUpdate: "tool_call_update", toolCallId: "edit-1", locations });
      update(
        {
          sessionUpdate: "agent_message_chunk",
          content: { type: "text", text: `\n\nLocations ${label}.\n\n` },
        },
        1000,
      );
      for (let i = 0; i < 8; i++)
        update(
          { sessionUpdate: "agent_thought_chunk", content: { type: "text", text: "." } },
          2000,
        );
    }
    update({ sessionUpdate: "tool_call_update", toolCallId: "edit-1", status: "completed" });
    end();
    writeFileSync(
      `${APP_DIR}/apps/server/scripts/dev-replay/showcase_transcript.ndjson`,
      frames.map((f) => JSON.stringify(f)).join("\n"),
    );
    const controlFrames = frames.slice(0, 2);
    controlFrames.push({
      type: "emit_inbound",
      frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } },
    });
    controlFrames.push({
      type: "expect_outbound",
      frame: { kind: "request", method: "session/prompt" },
    });
    for (const update of [
      {
        sessionUpdate: "tool_call",
        toolCallId: "edit-1",
        title: "Edit",
        kind: "edit",
        status: "in_progress",
      },
      {
        sessionUpdate: "tool_call_update",
        toolCallId: "edit-1",
        locations: [{ path: "<workspace>/src/location-proof.ts" }],
      },
      {
        sessionUpdate: "tool_call_update",
        toolCallId: "edit-1",
        locations: [{ path: "<workspace>/src/other-file.ts" }],
      },
      { sessionUpdate: "tool_call_update", toolCallId: "edit-1", status: "completed" },
      {
        sessionUpdate: "agent_message_chunk",
        content: { type: "text", text: "Control completed." },
      },
    ])
      controlFrames.push({
        type: "emit_inbound",
        afterMs: 2000,
        frame: {
          kind: "notification",
          method: "session/update",
          params: { sessionId: "recorded", update },
        },
      });
    controlFrames.push({
      type: "emit_inbound",
      frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } },
    });
    writeFileSync(
      `${APP_DIR}/apps/server/scripts/dev-replay/command_output_transcript.ndjson`,
      controlFrames.map((f) => JSON.stringify(f)).join("\n"),
    );
    const project = await t3.project("demo", {
      "src/location-proof.ts": "export const proof = 1;\n",
      "src/other-file.ts": "export const other = 2;\n",
    });
    const thread = await t3.thread({
      project,
      title: "ACP location proof",
      messages: ["Prepare proof"],
      model: "showcase",
    });
    const control = await t3.thread({
      project,
      title: "Completed location control",
      messages: ["Prepare proof"],
      model: "command-output",
    });
    await t3.open(thread);
    await screen.getByRole("textbox").fill("Run location-only updates");
    await screen.getByRole("textbox").press("Enter");
    const observed: boolean[] = [];
    for (const [label] of phases) {
      await screen.getByText(`Locations ${label}.`, { exact: false }).waitFor();
      if (label === "replaced") await browser.reload();
      await screen.getByText(`Locations ${label}.`, { exact: false }).waitFor();
      await app.screenshot(`locations-${label}`);
      const text = await browser.evaluate(() => document.body.innerText);
      observed.push(
        label === "added"
          ? text.includes("src/location-proof.ts")
          : label === "replaced"
            ? text.includes("src/other-file.ts") && !text.includes("src/location-proof.ts")
            : !text.includes("src/other-file.ts") && !text.includes("src/location-proof.ts"),
      );
    }
    await t3.open(control);
    await screen.getByRole("textbox").fill("Run completed location control");
    await screen.getByRole("textbox").press("Enter");
    await screen.getByText("Control completed.", { exact: false }).waitFor();
    await screen.getByRole("button", "Stop generation").waitFor({ state: "hidden" });
    await screen.getByRole("button", /^Worked for/).tap();
    const grouped = await browser.evaluate(() =>
      [...document.querySelectorAll('button,[role="button"]')].some(
        (e) =>
          e.getAttribute("aria-label") === "Changed 1 file" ||
          e.textContent?.trim() === "Changed 1 file",
      ),
    );
    if (grouped) await screen.getByRole("button", "Changed 1 file", { exact: true }).tap();
    await app.screenshot("completed-control");
    expect(observed).toEqual([true, true, true]);
  },
);
