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

test("Scheduled task titles use only the first prompt line", WEB, async ({ t3, app, screen }) => {
  await t3.project("Schedule title proof");
  const origin = app.baseUrl!;
  const post = async (path: string, body: unknown, headers: Record<string,string> = {}) => {
    const response = await fetch(origin + path, { method: "POST", headers: { "content-type": "application/json", ...headers }, body: JSON.stringify(body) });
    if (!response.ok) throw new Error(`${path}: ${response.status} ${await response.text()}`);
    return response;
  };
  const credential = await readFile(`${T3_HOME}/browser-dev-token`, "utf8");
  const signedIn = await post("/api/auth/browser-session", { credential });
  const cookie = signedIn.headers.getSetCookie().map(value => value.split(";")[0]).join("; ");
  const registered = await (await post("/oauth/mcp/register", { client_name: "Schedule title proof", redirect_uris: ["http://localhost:51234/callback"], token_endpoint_auth_method: "none" })).json();
  const authorization = { response_type: "code", client_id: registered.client_id, redirect_uri: "http://localhost:51234/callback", code_challenge: "DeB41nTVkPwpbbYecrnqtVq7VXLezustdHAK4SWt13c", code_challenge_method: "S256", state: "proof", resource: `${origin}/mcp` };
  const approval = await (await post("/oauth/mcp/approval", authorization, { cookie, origin })).json();
  const decision = await (await post("/oauth/mcp/decision", { authorization, decision: { _tag: "browser-session", access: "full-access", csrfToken: approval.csrfToken } }, { cookie, origin })).json();
  const exchange = await fetch(`${origin}/oauth/mcp/token`, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ grant_type: "authorization_code", client_id: registered.client_id, redirect_uri: authorization.redirect_uri, code: new URL(decision.redirectTo).searchParams.get("code")!, code_verifier: "a".repeat(43) + "-verifier-for-tests", resource: authorization.resource }) });
  const token = await exchange.json();
  if (!token.access_token) throw new Error("OAuth exchange failed");
  let session = "";
  let id = 0;
  const send = async (method: string, params: unknown) => {
    const response = await post("/mcp", { jsonrpc: "2.0", id: ++id, method, params }, { authorization: `Bearer ${token.access_token}`, accept: "application/json, text/event-stream", ...(session ? { "mcp-session-id": session, "mcp-protocol-version": "2025-06-18" } : {}) });
    session = response.headers.get("mcp-session-id") ?? session;
    const body = await response.text();
    const data = body.startsWith("{") ? body : body.split("\n").filter(line => line.startsWith("data: ")).map(line => line.slice(6)).at(-1)!;
    const result = JSON.parse(data);
    if (result.error || result.result?.isError) throw new Error(`MCP ${method}: ${data}`);
    return result.result;
  };
  await send("initialize", { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "schedule-title-proof", version: "1" } });
  const tool = async (name: string, args: object) => {
    const result = await send("tools/call", { name, arguments: args });
    return result.structuredContent ?? JSON.parse(result.content.find((item: { type: string }) => item.type === "text").text);
  };
  const project = await tool("t3_project_create", { title: "Line separator tasks" });
  await tool("t3_project_update", { projectId: project.id, defaultModelSelection: { instanceId: "devReplay", model: "showcase" } });
  const separators = ["\n", "\r", "\u2028", "\u2029"];
  for (const separator of separators) {
    await tool("schedule_task", { projectId: project.id, prompt: `Review merge${separator}Check changelog`, schedule: { type: "interval", everyMs: 86400000 }, enabled: false });
  }
  const listed = await tool("list_scheduled_tasks", { projectId: project.id });
  await t3.open("/settings/scheduled-tasks");
  await screen.getByRole("button", "New task").waitFor();
  await screen.getByRole("heading", "Review merge", { exact: true }).first().waitFor();
  await app.screenshot("scheduled-task-titles");
  expect(listed.tasks.map((task: { prompt: string }) => task.prompt).sort()).toEqual(separators.map(separator => `Review merge${separator}Check changelog`).sort());
  expect(listed.tasks.map((task: { title: string }) => task.title)).toEqual(separators.map(() => "Review merge"));
});
