// @effect-diagnostics nodeBuiltinImport:off -- A synthetic ACP peer supplies the reported late session/load frames.
import * as FS from "node:fs/promises";
import { randomUUID } from "node:crypto";
import * as Path from "node:path";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { CommandId, ThreadId, ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

const ACP = `#!${process.execPath}
import { createInterface } from "node:readline";
import { existsSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { randomUUID } from "node:crypto";
if (process.argv.includes("--version")) { console.log("grok 1.0.13"); process.exit(0); }
if (process.argv.includes("models")) { console.log("grok-build"); process.exit(0); }
if (process.argv.includes("inspect")) { console.log(JSON.stringify({skills:[]})); process.exit(0); }
const root = dirname(new URL(import.meta.url).pathname);
const gate = join(root, ".git", "replay-emitted");
const send = (m) => process.stdout.write(JSON.stringify({jsonrpc:"2.0",...m})+"\\n");
const models = {currentModelId:"grok-build",availableModels:[{modelId:"grok-build",name:"Grok replay fixture",_meta:{totalContextTokens:128000}}]};
let sessionId;
let loaded = false;
let freshSession = false;
const update = (update, replay = false) => send({method:"session/update",params:{sessionId,update,...(replay?{_meta:{isReplay:true}}:{})}});
for await (const line of createInterface({input:process.stdin})) {
 const {id,method,params} = JSON.parse(line);
 if(id===undefined) continue;
 let result = {};
 if(method==="initialize") result={protocolVersion:1,agentInfo:{name:"grok-replay-fixture",version:"1.0.13"},agentCapabilities:{loadSession:true},authMethods:[],_meta:{models}};
 else if(method==="session/new" || method==="session/load") {
  loaded = method === "session/load";
  freshSession = method === "session/new" && existsSync(gate);
  sessionId = method==="session/load" ? params.sessionId : randomUUID();
  result={...(method==="session/new"?{sessionId}:{}),models};
 } else if(method==="session/prompt") {
  const fresh = freshSession;
  update({sessionUpdate:"agent_message_chunk",content:{type:"text",text:fresh?"Recovered in a fresh Grok native session. Ready to continue.":"Initial Grok turn complete. No background tasks were started."}});
  update({sessionUpdate:"usage_update",used:fresh?100:127900,size:128000});
  result={stopReason:"end_turn"};
 } else if(method==="session/set_model") {
  if(loaded) {
   update({sessionUpdate:"agent_message_chunk",content:{type:"text",text:"old reply from history"}},true);
   update({sessionUpdate:"tool_call",toolCallId:"replayed-tool",title:"Historical completed read",kind:"read",status:"completed"},true);
   writeFileSync(gate,"late session/load tail emitted after activation");
   loaded = false;
  }
  result={};
 } else if(method==="session/set_mode") result={};
 else if(method==="session/list") result={sessions:[]};
 else { send({id,error:{code:-32601,message:"Method not found"}}); continue; }
 send({id,result});
}
`;

test(
  "Grok session/load replay does not block fresh-session handoff recovery",
  WEB,
  async ({ t3, app, screen }) => {
    const project = await t3.project("replay-demo", { "grok-fixture.mjs": ACP });
    const executable = Path.join(project, "grok-fixture.mjs");
    await FS.chmod(executable, 0o755);
    await runPromise(
      Effect.gen(function* () {
        const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
        yield* client["server.updateSettings"]({
          patch: {},
          providerInstanceMutation: {
            operation: "upsert",
            instanceId: ProviderInstanceId.make("grok"),
            instance: {
              driver: ProviderDriverKind.make("grok"),
              displayName: "Grok",
              enabled: true,
              config: { binaryPath: executable, customModels: ["grok-fixture"] },
            },
          },
        });
      }).pipe(Effect.scoped),
    );
    const select = async (threadId: string, instanceId: string, model: string) =>
      runPromise(
        Effect.gen(function* () {
          const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
          yield* client["orchestration.dispatchCommand"]({
            type: "thread.model-selection.set",
            commandId: CommandId.make(randomUUID()),
            threadId: ThreadId.make(threadId),
            modelSelection: { instanceId: ProviderInstanceId.make(instanceId), model },
          });
        }).pipe(Effect.scoped),
      );
    const { cli } = makeState(T3_HOME);
    const start = await runPromise(
      cli([
        "thread",
        "start",
        project,
        "Complete one turn without starting background work.",
        "--title",
        "Grok replay handoff",
        "--provider",
        "grok",
        "--model",
        "grok-fixture",
        "--wait",
        "--json",
      ]),
    );
    const { threadId } = JSON.parse(start.stdout);
    await t3.open({ threadId });
    await screen
      .getByText("Initial Grok turn complete. No background tasks were started.", { exact: true })
      .waitFor();
    await screen.getByRole("button", "Dismiss Grok provider warning").tap();
    await select(threadId, "devReplay", "multi-turn");
    await runPromise(
      cli([
        "thread",
        "send",
        threadId,
        "Continue briefly with the other provider.",
        "--wait",
        "--json",
      ]),
    );
    await select(threadId, "grok", "grok-fixture");
    await runPromise(
      cli(
        [
          "thread",
          "send",
          threadId,
          "Switch back to Grok and recover the conversation.",
          "--wait",
          "--json",
        ],
        [0, 1, 2],
      ),
    );
    try {
      await expect(
        screen.getByText("Recovered in a fresh Grok native session. Ready to continue.", {
          exact: true,
        }),
      ).toBeVisible({ timeout: 20000 });
    } finally {
      await screen.getByRole("button", "Settle thread", { exact: true }).waitFor();
      await app.screenshot("grok-handoff-recovery");
    }
  },
);
