import { CommandId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";

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

const readOverMcp = Effect.fn("scenario.readOverMcp")(function* (
  baseUrl: string,
  threadId: string,
) {
  const { cli } = makeState(T3_HOME);
  const { stdout } = yield* cli([
    "auth",
    "session",
    "issue",
    "--subject",
    "mcp-client",
    "--scope",
    "orchestration:read",
    "--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" });
  return yield* send({
    id: 2,
    method: "tools/call",
    params: { name: "t3_thread_read", arguments: { threadId } },
  });
}, Effect.provide(FetchHttpClient.layer));

test("MCP reads a delegated thread copied with raw colons", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("delegated-read");
  const parent = await t3.thread({ project, title: "Delegated thread read proof", messages: ["Start"], model: "question" });
  const commandId = "command:mcp:scenario:delegate-task:1";
  const encoded = `thread:delegated-task:${encodeURIComponent(commandId)}`;
  const raw = encoded.replaceAll("%3A", ":");
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    const projection = yield* client["orchestration.getThreadProjection"]({ threadId: ThreadId.make(parent.threadId) });
    const run = projection.runs.at(-1)!;
    yield* client["orchestration.dispatchCommand"]({
      type: "delegated_task.request", commandId: CommandId.make(commandId),
      createdBy: "agent", creationSource: "mcp",
      parentThreadId: ThreadId.make(parent.threadId), parentRunId: run.id, parentNodeId: run.rootNodeId!,
      task: "Reply with a short greeting.", title: "Delegated read target",
      modelSelection: { instanceId: ProviderInstanceId.make("devReplay"), model: "showcase" },
      runtimeMode: "approval-required", interactionMode: "default",
    });
  }).pipe(Effect.scoped));
  const result = await runPromise(readOverMcp(app.baseUrl ?? "", raw));
  const lines = result.split("\n").filter(line => line.startsWith("data: "));
  const body = JSON.parse(lines.length ? lines.at(-1)!.slice(6) : result);
  const payload = body.result;
  const data = payload.structuredContent;
  const output = data ? [
    `isError: ${payload.isError ?? false}`,
    `Resolved: ${data.thread.threadId}`,
    `Title: ${data.thread.title}`,
    `Recent runs: ${data.recentRuns.length}`,
    `Timeline items: ${data.items.length}`,
    ...data.items.map((item: { type: string; text: string }) => `${item.type}: ${item.text}`),
  ].join("\n") : payload.content.map((entry: {text: string}) => entry.text).join("\n");
  const transcript = ["REAL SERVER MCP RESPONSE (selected fields)", `t3_thread_read(${raw})`, output, "END OF RESPONSE"].join("\n\n");
  await runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    yield* fs.writeFileString(`${project}/mcp-response.txt`, transcript);
  }));
  await browser.setViewport({ width: 1600, height: 1000 });
  await t3.open(parent);
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const terminal = screen.getByLabel("Terminal input");
  await expect.poll(async () => {
    await terminal.focus();
    await browser.keyboard.type(`echo ready > '${project}/ready'`);
    await browser.keyboard.press("Enter");
    return runPromise(Effect.flatMap(FileSystem.FileSystem, fs => fs.readFileString(`${project}/ready`)).pipe(Effect.orElseSucceed(() => "")));
  }, {timeout: 30000}).toBe("ready\n");
  const handle = await browser.evaluate(() => {
    const rect = document.querySelector('[data-thread-terminal-drawer]')!.getBoundingClientRect();
    return {x: rect.x + rect.width / 2, y: rect.y + 2};
  });
  await browser.mouse.move(handle.x, handle.y);
  await browser.mouse.down();
  await browser.mouse.move(handle.x, 420);
  await browser.mouse.up();
  await terminal.focus();
  await browser.keyboard.type("PS1=; clear; cat mcp-response.txt; echo done > shown; read -r");
  await browser.keyboard.press("Enter");
  await expect.poll(() => runPromise(Effect.flatMap(FileSystem.FileSystem, fs => fs.readFileString(`${project}/shown`)).pipe(Effect.orElseSucceed(() => "")))).toBe("done\n");
  await browser.evaluate(async () => {
    const canvas = document.querySelector('[aria-label="Terminal input"]')!.parentElement!.querySelector("canvas")!;
    let previous = "";
    for (let attempt = 0; attempt < 10; attempt++) {
      const current = canvas.toDataURL();
      if (current === previous) return;
      previous = current;
      await new Promise(resolve => setTimeout(resolve, 500));
    }
  });
  await app.screenshot("raw-colon-mcp-read");
  expect(payload.isError ?? false).toBe(false);
  expect(result).toContain("Delegated read target");
  expect(data.items.length).toBeGreaterThan(0);
});
