import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "e2e";
import { APP_DIR } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("Local commands send; ordinary drafts steer; queued edits update", WEB, async ({ t3, app, screen, browser }) => {
  const recording = join(APP_DIR, "apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/registry_transcript.ndjson");
  const original = await readFile(recording, "utf8");
  const prompt = {type: "expect_outbound", frame: {kind: "request", method: "session/prompt", params: "<any>"}};
  const response = {type: "emit_inbound", frame: {kind: "response", method: "session/prompt", result: {stopReason: "end_turn"}}};
  const message = (text: string) => ({type: "emit_inbound", frame: {kind: "notification", method: "session/update", params: {sessionId: "replay", update: {sessionUpdate: "agent_message_chunk", content: {type: "text", text}}}}});
  try {
    const project = await t3.project("Composer demo");
    const thread = await t3.thread({project, title: "Local command actions", messages: ["Review the sample project"], model: "multi-turn"});
  await writeFile(recording, [prompt, message("Reviewing the synthetic project. ".repeat(800)), response].map(x => JSON.stringify(x)).join("\n") + "\n");
    await t3.open(thread);
    const composer = screen.getByRole("textbox");
    const send = browser.locator('button[type="submit"]').last();
    await composer.fill("Review the project again");
    await composer.press("Enter");
    await screen.getByRole("button", "Stop generation").waitFor({state:"visible"});
    await composer.fill("/clear");
    await composer.press("Escape");
    await composer.hover();
    await send.hover();
    await browser.locator('[data-slot="tooltip-popup"]').waitFor({state:"visible"});
    await browser.locator('[data-slot="tooltip-popup"]:not([data-starting-style])').waitFor({state:"visible"});
    await browser.evaluate(async () => {
      const popup = document.querySelector('[data-slot="tooltip-popup"]');
      if (popup) {
        getComputedStyle(popup).opacity;
        await Promise.all(popup.getAnimations().map(animation => animation.finished));
      }
      return null;
    });
    await app.screenshot("clear-running-tooltip");
    const clearLabel = await send.getAttribute("aria-label");
    await composer.fill("Check the project formatting");
    await composer.hover();
    await send.hover();
    await browser.locator('[data-slot="tooltip-popup"]').waitFor({state:"visible"});
    await browser.locator('[data-slot="tooltip-popup"]:not([data-starting-style])').waitFor({state:"visible"});
    await browser.evaluate(async () => {
      const popup = document.querySelector('[data-slot="tooltip-popup"]');
      if (popup) {
        getComputedStyle(popup).opacity;
        await Promise.all(popup.getAnimations().map(animation => animation.finished));
      }
      return null;
    });
    await app.screenshot("ordinary-running-tooltip");
    const ordinaryLabel = await send.getAttribute("aria-label");
    await send.tap({modifiers:["Control"]});
    await screen.getByRole("button", "Edit queued message").waitFor({state:"visible"});
    await composer.fill("/clear");
    await composer.press("Escape");
    await composer.hover();
    await send.hover();
    await browser.locator('[data-slot="tooltip-popup"]').waitFor({state:"visible"});
    await browser.locator('[data-slot="tooltip-popup"]:not([data-starting-style])').waitFor({state:"visible"});
    await browser.evaluate(async () => {
      const popup = document.querySelector('[data-slot="tooltip-popup"]');
      if (popup) {
        getComputedStyle(popup).opacity;
        await Promise.all(popup.getAnimations().map(animation => animation.finished));
      }
      return null;
    });
    await app.screenshot("clear-with-queued-message");
    const queuedClearLabel = await send.getAttribute("aria-label");
    await screen.getByRole("button", "Edit queued message").tap();
    await composer.fill("/clear");
    await composer.press("Escape");
    await composer.hover();
    await send.hover();
    await browser.locator('[data-slot="tooltip-popup"]').waitFor({state:"visible"});
    await browser.locator('[data-slot="tooltip-popup"]:not([data-starting-style])').waitFor({state:"visible"});
    await browser.evaluate(async () => {
      const popup = document.querySelector('[data-slot="tooltip-popup"]');
      if (popup) {
        getComputedStyle(popup).opacity;
        await Promise.all(popup.getAnimations().map(animation => animation.finished));
      }
      return null;
    });
    await app.screenshot("queued-edit-update");
    const editLabel = await send.getAttribute("aria-label");
    await expect(ordinaryLabel).toBe("Steer message");
    await expect(editLabel).toBe("Update queued message");
    await expect(clearLabel).toBe("Submit message");
    await expect(queuedClearLabel).toBe("Submit message");
  } finally { await writeFile(recording, original); }
});
