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

test("Resume after switching Codex Luna to Claude Haiku continues the interrupted apple task", WEB,
  async ({ t3, app, screen, browser }) => {
    const settingsPath = path.join(T3_HOME, "userdata/settings.json");
    const settings = JSON.parse(await fs.readFile(settingsPath, "utf8"));
    settings.providerInstances.codex = { driver: "codex", enabled: true };
    settings.providerInstances.claudeAgent = { driver: "claudeAgent", enabled: true };
    await fs.writeFile(settingsPath, JSON.stringify(settings));
    const project = await t3.project("Apple poem");
    const { cli } = makeState(T3_HOME);
    const started = await runPromise(cli(["thread", "start", project,
      "Run the shell command `sleep 60 && echo done` and then write a short poem about apples. Do not edit any files.",
      "--title", "Interrupted apple task", "--provider", "codex", "--model", "gpt-6-luna", "--json"]));
    const { threadId } = JSON.parse(started.stdout);
    await t3.open({ threadId });
    await screen.getByRole("button", "Toggle thread details panel").tap();
    await screen.getByRole("button", /^Running (sleep|command|bash|sh)/).waitFor({ state: "visible", timeout: 120_000 });
    await app.screenshot("running-command");
    await screen.getByRole("button", "Stop generation").tap();
    await screen.getByRole("button", "Resume thread").waitFor({ state: "visible", timeout: 120_000 });
    await app.screenshot("stopped");
    await browser.evaluate(() => (document.querySelector('[data-chat-provider-model-picker="true"]') as HTMLButtonElement).click());
    await screen.getByPlaceholder("Search models...").fill("Haiku 5.5");
    await screen.getByRole("option", "Claude Haiku 5.5", { exact: false }).tap();
    await screen.getByText("Context handoff pending", { exact: true }).waitFor({ state: "visible", timeout: 30_000 });
    await app.screenshot("handoff-pending");
    await screen.getByRole("button", "Resume thread").tap();
    await screen.getByRole("button", "Stop generation").waitFor({ state: "visible", timeout: 120_000 });
    await screen.getByRole("button", "Stop generation").waitFor({ state: "hidden", timeout: 180_000 });
    await app.screenshot("resumed-result");
    const shown = JSON.parse((await runPromise(cli(["thread", "show", threadId, "--json"]))).stdout);
    const answer = shown.messages.filter((m: {role: string}) => m.role === "assistant").at(-1)?.text ?? "";
    // The interrupted request asks for an apple poem, so completion must contain verse, not a clarification.
    expect(answer).toMatch(/apples?/i);
    expect(answer).not.toMatch(/should I|would you like|not sure|want me to|paused|single character|empty message/i);
    expect(answer.split("\n").filter((line: string) => line.trim()).length).toBeGreaterThanOrEqual(3);
  });
