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

test("CLI opt-in generates a title while explicit titles remain", WEB, async ({ t3, app, screen }) => {
  const project = await t3.project("bicycle-demo");
  const cli = (args: string[], allow = [0]) => runPromise(makeState(T3_HOME).cli(args, allow));
  await runPromise(Effect.scoped(Effect.gen(function* () {
    const rpc = yield* rpcClient(T3_HOME, app.baseUrl!);
    yield* rpc["server.updateSettings"]({ patch: {
      textGenerators: { titleApi: { kind: "openaiCompatible", label: "Title provider", baseUrl: process.env.TITLE_API_URL!, apiKey: process.env.TITLE_API_KEY!, enabled: true } },
      textGenerationModelSelection: { instanceId: "titleApi", model: "gpt-6-luna" },
    } });
  })));
  const fixed = await cli(["thread", "start", project, "Describe a bicycle repair log", "--title", "explicit title remains", "--provider", "devReplay", "--model", "multi-turn", "--wait", "--json"], [0,2]);
  await t3.open(JSON.parse(fixed.stdout));
  await expect(screen.getByRole("button", "explicit title remains, bicycle-demo", {exact:true})).toBeVisible();
  const result = await cli(["thread", "start", project, "Describe a bicycle repair log", "--title", "cli title seed", "--generate-title", "--provider", "devReplay", "--model", "multi-turn", "--json"], [0,1,2]);
  const seedRows = JSON.parse((await cli(["thread", "list", "--project", project, "--json"])).stdout);
  await app.screenshot("initial-title");
  const listedBeforeMcp = JSON.parse((await cli(["thread", "list", "--project", project, "--json"])).stdout);
  const projectId = listedBeforeMcp[0].projectId;
  const token = (await cli(["auth", "session", "issue", "--subject", "mcp-client", "--token-only"])).stdout.trim();
  let session = "";
  let requestId = 0;
  const mcp = async (method: string, params: unknown) => {
    const response = await fetch(`${app.baseUrl}/mcp`, {method:"POST", headers:{authorization:`Bearer ${token}`, "content-type":"application/json", accept:"application/json, text/event-stream", ...(session ? {"mcp-session-id":session,"mcp-protocol-version":"2025-06-18"}: {})}, body:JSON.stringify({jsonrpc:"2.0",id:++requestId,method,params})});
    session = response.headers.get("mcp-session-id") ?? session;
    const text = await response.text();
    const data = text.startsWith("data:") || text.includes("\ndata:") ? text.split("\n").filter(x=>x.startsWith("data:")).map(x=>JSON.parse(x.slice(5))).find(x=>x.id===requestId) : JSON.parse(text);
    if (response.status !== 200) throw new Error(`MCP HTTP ${response.status}: ${JSON.stringify(data)}`);
    return data;
  };
  await mcp("initialize", {protocolVersion:"2025-06-18",capabilities:{},clientInfo:{name:"title-proof",version:"1.0.0"}});
  const launchMcp = (args: unknown) => mcp("tools/call", {name:"t3_thread_launch",arguments:args});
  const mcpLaunch = await launchMcp({projectId,title:"mcp title seed",generateTitle:true,message:"Describe a bicycle repair log",modelSelection:{instanceId:"devReplay",model:"multi-turn"}});
  const invalidMcp = [];
  for (const message of [undefined,""," \n "]) {
    invalidMcp.push(await launchMcp({projectId,title:"empty request must not launch",generateTitle:true,...(message===undefined?{}:{message})}));
  }
  const mcpTranscript = JSON.stringify({initialCliThreads:seedRows,launch:mcpLaunch,emptyRequests:invalidMcp},null,2);
  await writeFile(`${T3_HOME}/mcp-transcript.json`, mcpTranscript);

  await expect(screen.getByRole("button", "explicit title remains, bicycle-demo", {exact:true})).toBeVisible({timeout:120000});
  await writeFile(`${T3_HOME}/cli-transcript.txt`, `t3 thread start . "Describe a bicycle repair log" --title "cli title seed" --generate-title\nexit=${result.exitCode}\n${result.stderr.replaceAll(T3_HOME,"<isolated-home>")}\n${result.stdout}\n`);
  const side = result.exitCode === 0 ? "head" : "base";
  const clean = (value: string) => value.replaceAll(project,"<project>").replaceAll(T3_HOME,"<isolated-home>").replaceAll(app.baseUrl!,"<app-origin>");
  await writeFile(`${process.env.PROOF_OUTPUT_DIR}/${side}-mcp.json`, clean(mcpTranscript));
  await writeFile(`${process.env.PROOF_OUTPUT_DIR}/${side}-cli.txt`, clean(`generate-title exit=${result.exitCode}\n${result.stderr}\n${result.stdout}\n`));
  await expect(result.exitCode).toBe(0);
  await expect.poll(async () => {
    const rows = JSON.parse((await cli(["thread", "list", "--project", project, "--json"])).stdout);
    return rows.find((t:any) => t.threadId === JSON.parse(result.stdout).threadId)?.title ?? "cli title seed";
  }, {timeout:120000}).not.toBe("cli title seed");
  const listed = await cli(["thread", "list", "--project", project, "--json"]);
  const threads = JSON.parse(listed.stdout);
  const launched = JSON.parse(result.stdout);
  const generated = threads.find((t:any) => t.threadId === launched.threadId)?.title;
  await expect(screen.getByText(generated, {exact:true}).first()).toBeVisible();
  await expect.poll(async () => {
    const rows = JSON.parse((await cli(["thread", "list", "--project", project, "--json"])).stdout);
    return rows.find((t:any) => t.threadId === mcpLaunch.result?.structuredContent?.threadId)?.title ?? "mcp title seed";
  }, {timeout:120000}).not.toBe("mcp title seed");
  for (const response of invalidMcp) await expect(JSON.parse(response.result.content[0].text).code).toBe("invalid_request");
  const finalList = (await cli(["thread", "list", "--project", project, "--json"])).stdout;
  await expect(JSON.parse(finalList).filter((t:any) => t.title === "empty request must not launch").length).toBe(0);
  await writeFile(`${process.env.PROOF_OUTPUT_DIR}/${side}-list.json`, clean(finalList));
  await app.screenshot("mcp-and-cli-titles");
  await expect(threads.find((t:any) => t.title === "explicit title remains")?.title).toBe("explicit title remains");
});
