import { chmodSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { ThreadId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import { expect } from "e2e";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { test, WEB, rpcClient, runPromise } from "./t3.ts";

// Instrument only the model stand-in: the app and ACP adapter stay at the tested commit.
function installNotesReplay() {
  const file = join(APP_DIR, "apps/server/scripts/dev-replay-agent.ts");
  const original = readFileSync(file, "utf8");
  const marker = '      case "session/prompt": {';
  const branch = `
        const sessionId = String(params.sessionId);
        const session = sessions.get(sessionId)!;
        const emit = (update: unknown) => send({ method: "session/update", params: { sessionId, update } });
        const promptText = JSON.stringify(params.prompt);
        if (promptText.includes("Keep working until I send an update")) {
          emit({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "Working; waiting for your steering update. " } });
          await new Promise<void>(resolve => { (session as any).finishWork = resolve; });
          return { stopReason: "end_turn" };
        }
        if (promptText.includes("What updated secret did the notes app report")) {
          const match = promptText.match(/NOTE-B: the secret launch word is ([A-Z0-9-]+)/);
          emit({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: match ? "ACP steer received app note: " + match[1] : "ACP steer received no app note." } });
          (session as any).finishWork?.();
          return { stopReason: "end_turn" };
        }
        if (session.promptCount++ === 0) {
          emit({ sessionUpdate: "tool_call", toolCallId: "notes-panel", kind: "execute", title: "mcp.notes.open_notes_panel", status: "completed", rawInput: { server: "notes", tool: "open_notes_panel", arguments: {} }, _meta: { is_mcp_tool_call: true }, rawOutput: { t3McpApp: { attachmentId: "notes-00000000-0000-0000-0000-000000000000-html", server: "notes", tool: "open_notes_panel", resourceUri: "ui://notes/panel" } } });
          emit({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "Notes app opened. The app will publish a private note outside chat." } });
        } else {
          const blocks = (params.prompt as Array<{type: string; text?: string}>).filter(b => b.type === "text");
          const notes = blocks.flatMap(b => [...(b.text ?? "").matchAll(/NOTE-A: the secret launch word is ([A-Z0-9-]+)/g)]).map(m => m[1]);
          emit({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: (promptText.includes("unchanged app note") ? "Unchanged-note check: " : "") + (notes.length ? "ACP received app note: " + notes.join(", ") : "ACP received no app note in this prompt.") } });
        }
        return { stopReason: "end_turn" };
      }
      case "unused-original-prompt": {`;
  const nativeSteer = `
      case "_x.ai/interject": {
        const sessionId = String(params.sessionId);
        const session = sessions.get(sessionId)!;
        const text = String(params.text);
        const match = text.match(/NOTE-B: the secret launch word is ([A-Z0-9-]+)/);
        send({ method: "session/update", params: { sessionId, update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: match ? "ACP steer received app note: " + match[1] : "ACP steer received no app note." } } } });
        (session as any).finishWork?.();
        return { result: { status: "queued" } };
      }
`;
  writeFileSync(file, original.replace(marker, marker + branch).replace('      case "authenticate":', nativeSteer + '      case "authenticate":').replace('authMethods: [],', 'authMethods: [{ id: "grok.com", name: "Local replay" }, { id: "xai.api_key", name: "Local replay" }],'));
  return () => writeFileSync(file, original);
}

test("ACP receives an MCP app note on the next normal message, then avoids resending it", WEB, async ({ t3, app, screen }) => {
  const restore = installNotesReplay();
  try {
    mkdirSync(join(T3_HOME, "userdata/attachments"), { recursive: true });
    writeFileSync(join(T3_HOME, "userdata/attachments/notes-00000000-0000-0000-0000-000000000000-html.html"), `<!doctype html><html><body style="font:14px system-ui;color:#202028;background:#f3f0ff;padding:16px;margin:0"><b>Notes app</b><p>NOTE-A: the secret launch word is <b>PURPLE-OTTER-42</b></p><small id="status">Published outside chat through MCP app model context</small><script>
      const send = message => parent.postMessage({jsonrpc:"2.0", ...message}, "*");
      addEventListener("message", event => { if(event.data.id === 1 && event.data.result) { send({method:"ui/notifications/initialized"}); send({method:"ui/notifications/size-changed",params:{height:130}}); } });
      send({id:1,method:"ui/initialize",params:{protocolVersion:"2026-01-26",appCapabilities:{}}});
    </script></body></html>`);
    const binary = join(T3_HOME, "bin/notes-acp-replay");
    writeFileSync(binary, '#!/bin/sh\nif [ "$1" = "--version" ]; then echo "grok 1.0.77"; exit 0; fi\nif [ "$1" = "inspect" ]; then echo \'{"skills":[]}\'; exit 0; fi\nif [ "$1" = "models" ]; then printf \'You are logged in\\n- multi-turn (default)\\n\'; exit 0; fi\nexec ' + JSON.stringify(process.execPath) + ' ' + JSON.stringify(join(APP_DIR, "apps/server/scripts/dev-replay-agent.ts")) + '\n');
    chmodSync(binary, 0o755);
    await runPromise(Effect.gen(function* () {
      const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
      yield* client["server.updateSettings"]({ patch: {}, providerInstanceMutation: { operation: "upsert", instanceId: "devReplay", instance: { driver: "grok", enabled: true, displayName: "ACP notes replay", config: { binaryPath: binary } } } });
    }).pipe(Effect.scoped));
    const project = await t3.project("notes-demo");
    const thread = await t3.thread({ project, title: "ACP app notes", messages: ["Open the notes app"], model: "multi-turn" });
    const itemId = await runPromise(Effect.gen(function* () {
      const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
      const threadId = ThreadId.make(thread.threadId);
      const projection = yield* client["orchestration.getThreadProjection"]({ threadId });
      const item = projection.turnItems.find(item => item.type === "dynamic_tool" && item.toolName === "notes.open_notes_panel");
      if (!item) throw new Error("Notes app tool item missing");
      yield* client["mcpApps.updateModelContext"]({ threadId, itemId: item.id, conversationThreadId: threadId, content: [{ type: "text", text: "NOTE-A: the secret launch word is PURPLE-OTTER-42" }] });
      return item.id;
    }).pipe(Effect.scoped));
    await t3.open(thread);
    await screen.getByRole("textbox").fill("Without using any tools: what secret launch word did the notes app report to you?");
    await screen.getByRole("textbox").press("Enter");
    await screen.getByText(/^ACP received/).first().waitFor();
    await screen.getByRole("button", "Stop generation").waitFor({ state: "hidden" });
    await app.screenshot("app-note-delivery");
    await screen.getByRole("textbox").fill("Check whether the unchanged app note is repeated in this prompt.");
    await screen.getByRole("textbox").press("Enter");
    await screen.getByText(/^Unchanged-note check:/).waitFor();
    await screen.getByRole("button", "Stop generation").waitFor({ state: "hidden" });
    await app.screenshot("unchanged-note-not-repeated");
    await screen.getByRole("textbox").fill("Keep working until I send an update.");
    await screen.getByRole("textbox").press("Enter");
    await screen.getByText("Working; waiting for your steering update.", { exact: true }).waitFor();
    await runPromise(Effect.gen(function* () {
      const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
      const threadId = ThreadId.make(thread.threadId);
      yield* client["mcpApps.updateModelContext"]({ threadId, itemId, conversationThreadId: threadId, content: [{ type: "text", text: "NOTE-B: the secret launch word is SILVER-BADGER-73" }] });
    }).pipe(Effect.scoped));
    await screen.getByRole("textbox").fill("What updated secret did the notes app report to you? Answer without tools.");
    await screen.getByRole("textbox").press("Enter");
    await screen.getByText(/ACP steer received/).waitFor();
    await app.screenshot("updated-note-on-steer");
    await expect(screen.getByText(/ACP steer received app note: SILVER-BADGER-73/)).toBeVisible();
    await expect(screen.getByText("ACP received app note: PURPLE-OTTER-42", { exact: true })).toBeVisible();
    await expect(screen.getByText("Unchanged-note check: ACP received no app note in this prompt.", { exact: true })).toBeVisible();
  } finally { restore(); }
});
