import * as NodeWS from "@effect/platform-node/NodeWS";
import {
  ORCHESTRATION_PROTOCOL_VERSION,
  WsRpcGroup,
} from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
import { RpcClient, RpcSerialization } from "effect/rpc";
import { Socket } from "effect/socket";

import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { SECOND_HOME, startSecondServer } from "./second-server.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";


/** The typed RPC client of the server on `home` at `origin`, signed in through its own CLI. */
const rpcClient = Effect.fn("scenario.rpcClient")(function* (home: string, origin: string) {
  const issued = yield* makeState(home).cli(["auth", "session", "issue", "--token-only"]);
  const { ticket } = yield* HttpClient.execute(
    HttpClientRequest.post(`${origin}/api/auth/websocket-ticket`).pipe(
      HttpClientRequest.bearerToken(issued.stdout.trim()),
    ),
  ).pipe(
    Effect.flatMap(HttpClientResponse.filterStatusOk),
    Effect.flatMap(HttpClientResponse.schemaBodyJson(Schema.Struct({ ticket: Schema.String }))),
    Effect.provide(FetchHttpClient.layer),
  );
  // Built into the caller's scope: `Effect.provide` would close the socket once `make` returns.
  const protocol = yield* Layer.build(
    RpcClient.layerProtocolSocket().pipe(
      Layer.provide(
        Socket.layerWebSocket(
          `${origin.replace(/^http/, "ws")}/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}&wsTicket=${encodeURIComponent(ticket)}`,
        ),
      ),
      Layer.provide(RpcSerialization.layerJson),
      Layer.provide(NodeWS.layerWebSocketConstructor),
    ),
  );
  return yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol));
});

const decodePairing = Schema.decodeEffect(
  Schema.fromJsonString(Schema.Struct({ credential: Schema.String })),
);

/** Turns the Linked environments beta on for both servers and links the first to the second. */
const linkEnvironments = Effect.fn("scenario.linkEnvironments")(function* (
  primaryOrigin: string,
  secondOrigin: string,
  secondRpcOrigin: string = secondOrigin,
) {
  const primary = yield* rpcClient(T3_HOME, primaryOrigin);
  const second = yield* rpcClient(SECOND_HOME, secondRpcOrigin);
  for (const client of [primary, second]) {
    yield* client["server.updateSettings"]({ patch: { linkedEnvironmentsEnabled: true } });
  }
  const pairing = yield* makeState(SECOND_HOME).cli(["auth", "pairing", "create", "--json"]);
  const { credential } = yield* decodePairing(pairing.stdout);
  yield* primary["peerLinks.link"]({
    url: secondOrigin,
    pairingCode: credential,
    access: "full-access",
  });
}, Effect.scoped);

import { readFile, writeFile } from "node:fs/promises";
import { spawn } from "node:child_process";
import { createServer } from "node:net";
import * as http from "node:http";
import { run } from "./shell.ts";

const freePort = () => new Promise<number>((resolve) => {
  const server = createServer();
  server.listen(0, "127.0.0.1", () => {
    const address = server.address();
    if (!address || typeof address === "string") throw new Error("No port");
    server.close(() => resolve(address.port));
  });
});

const configureParent = Effect.fn("scenario.configureParent")(function* (origin: string, agent: string) {
  const client = yield* rpcClient(T3_HOME, origin);
  yield* client["server.updateSettings"]({patch: {providerInstances: {
    devReplay: {driver: "acpRegistry", displayName: "Replay (dev)", enabled: true,
      config: {source: "local", commandPath: process.execPath, commandArgs: [agent]}}
  }}});
}, Effect.scoped);

// The ordinary replay agent, with one scripted MCP delegation before its recorded turn.
const installDelegatingReplay = async (environmentId: string) => {
  const original = `${APP_DIR}/apps/server/scripts/dev-replay-agent.ts`;
  let source = await readFile(original, "utf8");
  source = source.replace('new URL(scenario.file, import.meta.url)',
    `new URL(scenario.file, ${JSON.stringify('file://' + original)})`);
  source = source.replace('const turns = loadTurns(session.model);', `
        const promptText = JSON.stringify(params.prompt);
        const match = promptText.includes("Delegate a tiny task to the linked worker.");
        if (match) {
          const input = {environmentId: ${JSON.stringify(environmentId)}};
          const endpoint = process.env.T3_ACP_MCP_ENDPOINT;
          const authorization = process.env.T3_ACP_MCP_AUTHORIZATION;
          if (!endpoint || !authorization) throw new Error("MCP not injected");
          let sessionHeader;
          let nextId = 0;
          const rpc = async (method, args) => {
            const response = await fetch(endpoint, {method: "POST", headers: {
              "Content-Type": "application/json", Accept: "application/json, text/event-stream",
              Authorization: authorization, "MCP-Protocol-Version": "2025-06-18",
              ...(sessionHeader ? {"Mcp-Session-Id": sessionHeader} : {})
            }, body: JSON.stringify({jsonrpc: "2.0", id: ++nextId, method, params: args})});
            sessionHeader = response.headers.get("mcp-session-id") ?? sessionHeader;
            const text = await response.text();
            const payload = text.startsWith("{") ? JSON.parse(text) : text.split("\\n")
              .filter(line => line.startsWith("data: ")).map(line => JSON.parse(line.slice(6)))
              .find(value => value.id === nextId);
            if (!response.ok || payload?.error || payload?.result?.isError)
              throw new Error("MCP call failed: " + text);
            return payload?.result;
          };
          await rpc("initialize", {protocolVersion:"2025-06-18", capabilities:{},
            clientInfo:{name:"remote-settle-replay",version:"1"}});
          await rpc("tools/call", {name:"orchestrator_capabilities",arguments:{}});
          const projectResult = await rpc("tools/call", {name:"t3_project_list",arguments:{environmentId:input.environmentId}});
          const listed = projectResult.structuredContent ?? JSON.parse(projectResult.content.find(c=>c.type === "text").text);
          input.projectId = listed.projects[0].id;
          send({method:"session/update", params:{sessionId, update:{sessionUpdate:"tool_call",
            toolCallId:"remote-task", title:"delegate_task: Tiny test task on worker", kind:"other", status:"in_progress"}}});
          const result = await rpc("tools/call", {name:"delegate_task",arguments:{
            task:"Reply with a brief completion message.", title:"Tiny test task", mode:"wait", timeoutMs:45000,
            target:{...input, providerInstanceId:"devReplay",model:"multi-turn"}}});
          send({method:"session/update", params:{sessionId, update:{sessionUpdate:"tool_call_update",
            toolCallId:"remote-task", status:"completed", content:[{type:"content",content:{type:"text",text:"Tiny test task completed on worker."}}]}}});
          send({method:"session/update", params:{sessionId, update:{sessionUpdate:"agent_message_chunk",
            content:{type:"text",text:"The tiny task on the worker is complete."}}}});
          return {stopReason:"end_turn"};
        }
        const turns = loadTurns(session.model);`);
  const file = `${T3_HOME}/delegating-replay.ts`;
  await writeFile(file, source);
  return file;
};

// A transparent peer route that refuses only the first settlement, after all work is done.
const settlementProxy = async (host: string) => {
  let armed = false;
  const events: Array<{action:string; httpStatus:number}> = [];
  const proxy = http.createServer(async (request, response) => {
    const chunks: Buffer[] = [];
    for await (const chunk of request) chunks.push(Buffer.from(chunk));
    const body = Buffer.concat(chunks);
    let settlement = false;
    try {
      const call = JSON.parse(body.toString());
      settlement = call.method === "tools/call" && call.params?.name === "t3_thread_organize"
        && call.params?.arguments?.action === "settle";
    } catch {}
    if (settlement && armed) {
      armed = false;
      events.push({action:"settle",httpStatus:503});
      response.writeHead(503, {"Content-Type":"text/plain"});
      response.end("Synthetic temporary peer failure");
      return;
    }
    const upstream = http.request(new URL(request.url ?? "/", host), {
      method:request.method, headers:request.headers,
    }, result => {
      if (settlement) events.push({action:"settle",httpStatus:result.statusCode ?? 0});
      response.writeHead(result.statusCode ?? 502, result.headers);
      result.pipe(response);
    });
    upstream.on("error",()=>{response.writeHead(502);response.end("Peer unavailable");});
    upstream.end(body);
  });
  await new Promise<void>(resolve=>proxy.listen(0,"127.0.0.1",resolve));
  const address=proxy.address();
  if (!address || typeof address === "string") throw new Error("No peer proxy port");
  return {origin:`http://127.0.0.1:${address.port}`,events,arm:()=>{armed=true;},
    stop:()=>new Promise<void>(resolve=>{proxy.closeAllConnections();proxy.close(()=>resolve());})};
};

test("Completed remote tasks settle with their parent in a worker-only client", WEB,
  async ({ t3, app, screen, browser }) => {
    const origin = app.baseUrl ?? "";
    const primary = await t3.project("parent-proj");
    const second = startSecondServer(origin);
    let web: ReturnType<typeof spawn> | undefined;
    let proxy: Awaited<ReturnType<typeof settlementProxy>> | undefined;
    try {
      const {host, token} = await second.ready;
      if (process.env.PROOF_CASE === "retry") proxy = await settlementProxy(host);
      await runPromise(linkEnvironments(origin, proxy?.origin ?? host, host));
      const worker = makeState(SECOND_HOME);
      const project = await worker.state.project("worker-proj");
      const environment = await fetch(`${host}/.well-known/t3/environment`).then(r=>r.json());
      const agent = await installDelegatingReplay(environment.environmentId);
      await runPromise(configureParent(origin, agent));
      const parent = await t3.thread({project:primary,title:"Parent: delegate to worker",
        messages:["Delegate a tiny task to the linked worker."]});
      const port = await freePort();
      const workerWeb = `http://127.0.0.1:${port}`;
      web = spawn(process.execPath, ["scripts/dev-runner.ts","dev:web","--home-dir",SECOND_HOME,
        "--no-seed","--port",new URL(host).port,"--dev-url",workerWeb,"--","--host","127.0.0.1"],
        {cwd:APP_DIR,env:{PATH:process.env.PATH,HOME:process.env.HOME,T3CODE_DEV_SEED:"0",
          T3CODE_PORT_OFFSET:String(port-5733)},stdio:"ignore",detached:false});
      for (let attempt=0; ; attempt++) {
        if (await fetch(`${workerWeb}/.well-known/t3/environment`).then(r=>r.ok).catch(()=>false)) break;
        if (attempt===180) throw new Error("Worker web did not start");
        await new Promise(resolve=>setTimeout(resolve,500));
      }
      await app.open(`${workerWeb}/pair#token=${encodeURIComponent(token)}`);
      await screen.getByRole("button", "Tiny test task, Done, worker-proj", {exact:true})
        .waitFor({state:"visible",timeout:60000});
      await browser.mouse.move(900,650);
      await new Promise(resolve=>setTimeout(resolve,600));
      await app.screenshot("worker-before-parent-settles");

      if (process.env.PROOF_CASE === "disabled") {
        await t3.open("/settings/labs");
        await screen.getByRole("switch", "Linked environments", {exact:true}).uncheck();
        await browser.mouse.move(900,650);
        await new Promise(resolve=>setTimeout(resolve,600));
        await app.screenshot("new-linked-work-disabled");
      }
      await t3.open(parent);
      await screen.getByRole("button", "Parent: delegate to worker, parent-proj", {exact:true}).hover();
      proxy?.arm();
      await screen.getByRole("button", "Settle thread", {exact:true}).first().press("Enter");

      await t3.open(parent);
      await screen.getByRole("button", "Un-settle", {exact:true}).waitFor({state:"visible"});
      await screen.getByText("Syncing messages", {exact:false}).waitFor({state:"hidden"});
      await browser.mouse.move(900,650);
      await new Promise(resolve=>setTimeout(resolve,600));
      await app.screenshot("parent-settled");
      await app.open(`${workerWeb}/`);
      await screen.getByRole("button", /^Settled/).waitFor({state:"visible",timeout:60000});
      try {
        await expect(screen.getByRole("button", /^Settled/)).toContainText("1", {timeout:30000});
      } finally {
        await screen.getByRole("button", /^Settled/).tap();
        await screen.getByRole("button", /^Tiny test task,/).waitFor({state:"visible"});
        await browser.mouse.move(900,650);
        await new Promise(resolve=>setTimeout(resolve,600));
        await app.screenshot("worker-only-after-parent-settles");
        await new Promise(resolve=>setTimeout(resolve,1000));
      }
    } finally {
      if (proxy && process.env.PROOF_OUTPUT_DIR) {
        const {stdout} = await runPromise(run("git",["rev-parse","HEAD"],{cwd:APP_DIR}));
        await writeFile(`${process.env.PROOF_OUTPUT_DIR}/retry-${stdout.trim()}.json`,
          JSON.stringify({commit:stdout.trim(),events:proxy.events},null,2));
      }
      web?.kill("SIGTERM");
      await proxy?.stop();
      await second.stop();
    }
  });
