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

test("Project MCP responses include the action saved in Settings", WEB, async ({t3, app, screen}) => {
  await t3.project("demo-repo");
  await t3.open("/settings/projects");
  await screen.getByText("demo-repo", {exact: true}).tap();
  await screen.getByRole("button", "Add action", {exact: true}).tap();
  await screen.getByRole("textbox", "Name", {exact: true}).fill("Test");
  await screen.getByRole("textbox", "Command", {exact: true}).fill("pnpm test");
  await screen.getByRole("button", "Save action", {exact: true}).tap();
  await screen.getByRole("dialog", "Add Action").waitFor({state:"hidden"});
  await screen.getByText("pnpm test", {exact:true}).scrollIntoView();
  await app.screenshot("saved-action");
  const token = (await runPromise(makeState(T3_HOME).cli(["auth","session","issue","--subject","mcp-client","--scope","orchestration:read","--token-only"]))).stdout.trim();
  let session = "";
  let id = 0;
  async function send(method: string, params?: object) {
    const res = await fetch(`${app.baseUrl}/mcp`, {method:"POST", headers:{"content-type":"application/json",accept:"application/json, text/event-stream",authorization:`Bearer ${token}`,...(session ? {"mcp-session-id":session}: {})},body:JSON.stringify({jsonrpc:"2.0", ...(method.startsWith("notifications/")?{}:{id:++id}),method,params})});
    session = res.headers.get("mcp-session-id") ?? session;
    const text = await res.text();
    if (!res.ok) throw new Error(`MCP ${res.status}: ${text}`);
    if (!text) return null;
    const json = text.startsWith("{") ? text : text.split("\n").find(l=>l.startsWith("data: "))!.slice(6);
    return JSON.parse(json);
  }
  await send("initialize",{protocolVersion:"2025-06-18",capabilities:{},clientInfo:{name:"scenario",version:"1"}});
  await send("notifications/initialized");
  const list = await send("tools/call",{name:"t3_project_list",arguments:{}});
  function unpack(r:any):any { return r.result.structuredContent ?? JSON.parse(r.result.content.find((c:any)=>c.type==="text").text); }
  const projects = unpack(list).projects;
  const project = projects.find((p:any)=>p.title==="demo-repo");
  const read = await send("tools/call",{name:"t3_project_read",arguments:{projectId:project.id}});
  const result = {savedAction:{name:"Test",command:"pnpm test"},readScripts:unpack(read).scripts,listScripts:project.scripts};
  console.log(JSON.stringify(result));
  await writeFile(`/tmp/factory-pr-39676-evidence-1/${APP_DIR.endsWith("2c33cbdf02") ? "base" : "head"}-mcp-result.json`,JSON.stringify(result,null,2));
  expect(result.readScripts.map((s:any)=>({name:s.name,command:s.command}))).toEqual([{name:"Test",command:"pnpm test"}]);
  expect(result.listScripts.map((s:any)=>({name:s.name,command:s.command}))).toEqual([{name:"Test",command:"pnpm test"}]);
});
