import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";

import { T3_HOME } from "../e2e.config.ts";
import { ScenarioError } from "./shell.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

const replayOverMcp = Effect.fn("scenario.replayOverMcp")(function* (
  baseUrl: string,

) {
  const { cli } = makeState(T3_HOME);
  const { stdout } = yield* cli([
    "auth",
    "session",
    "issue",
    "--subject",
    "mcp-client",
    "--scope",
    "orchestration:read",
    "--scope",
    "orchestration:operate",
    "--token-only",
  ]);
  const client = yield* HttpClient.HttpClient;
  let sessionId: string | null = null;
  const send = Effect.fnUntraced(function* (message: object) {
    const response = yield* client.execute(
      HttpClientRequest.post(`${baseUrl}/mcp`).pipe(
        HttpClientRequest.setHeaders({
          accept: "application/json, text/event-stream",
          authorization: `Bearer ${stdout.trim()}`,
          ...(sessionId === null ? {} : { "mcp-session-id": sessionId }),
        }),
        HttpClientRequest.bodyJsonUnsafe({ jsonrpc: "2.0", ...message }),
      ),
    );
    sessionId = response.headers["mcp-session-id"] ?? sessionId;
    const body = yield* response.text;
    if (response.status >= 300) {
      return yield* new ScenarioError({ message: `MCP ${response.status}: ${body}` });
    }
    return body;
  });
  yield* send({
    id: 1,
    method: "initialize",
    params: {
      protocolVersion: "2025-06-18",
      capabilities: {},
      clientInfo: { name: "scenario", version: "1" },
    },
  });
  yield* send({ method: "notifications/initialized" });
  const call = (id: number, name: string, args: object) => send({id, method: "tools/call", params: {name, arguments: args}});
  const decode = (body: string) => {
    const line = body.split("\n").find(line => line.startsWith("data: "));
    const envelope = JSON.parse(line ? line.slice(6) : body);
    const result = envelope.result;
    if (result?.isError) throw new Error(JSON.stringify(result));
    return result.structuredContent ?? JSON.parse(result.content.find((c: {type: string}) => c.type === "text").text);
  };
  const projectId = decode(yield* call(10, "t3_project_list", {})).projects.find((p: {title: string}) => p.title === "demo").id;
  const original = {instanceId: "devReplay", model: "showcase"};
  const initial = decode(yield* call(2, "t3_thread_launch", {projectId, title: "Replay check", clientRequestId: "verify-replay-2", modelSelection: original}));
  const retry = decode(yield* call(3, "t3_thread_launch", {projectId, title: "Replay check", clientRequestId: "verify-replay-2", modelSelection: {instanceId: "devReplay", model: "unadvertised-retry-model"}, message: "Say hi."}));
  const read = decode(yield* call(4, "t3_thread_read", {threadId: initial.threadId}));
  console.log(JSON.stringify({initial,retry,read}));
  return {initial,retry,read,original};
}, Effect.provide(FetchHttpClient.layer));

test("launch replay keeps original model when retry adds a message", WEB, async ({t3,app,screen}) => {
  await t3.project("demo");
  const result = await runPromise(replayOverMcp(app.baseUrl ?? ""));
  await t3.open({threadId: result.initial.threadId});
  await screen.getByRole("textbox", "Message Replay check").waitFor({timeout: 120_000});
  await app.screenshot("replay-model-after-retry");
  expect(result.retry.modelSelection).toEqual(result.original);
  expect({instanceId: result.read.thread.providerInstanceId, model: result.read.thread.model}).toEqual(result.original);
});
