/// <reference lib="dom" />
import * as fs from "node:fs/promises";
import * as path from "node:path";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as NodeWS from "@effect/platform-node/NodeWS";
import {
  CommandId,
  ORCHESTRATION_PROTOCOL_VERSION,
  ThreadId,
  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";

// A shell keeps an environment's 25 newest settled threads; older ones come from search.
const NEWER_SETTLED = 25;

/** 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 command = (origin: string, threadId: string) => runPromise(Effect.scoped(Effect.gen(function* () {
  const client = yield* rpcClient(T3_HOME, origin);
  yield* client["orchestration.dispatchCommand"]({type:"thread.settle", commandId: CommandId.make(crypto.randomUUID()), threadId: ThreadId.make(threadId)});
})));

test("Settling closes a waiting environment link request", WEB, async ({t3, app, screen, browser}) => {
  // Mask only the authentication credential before any frame can display it.
  await browser.addInitScript(() => {
    const install = () => {
      if (!document.documentElement || document.getElementById("capture-redaction")) return;
      const style = document.createElement("style");
      style.id = "capture-redaction";
      style.textContent = "#pairing-token { color: transparent !important; text-shadow: none !important; caret-color: transparent !important; }";
      document.documentElement.appendChild(style);
    };
    new MutationObserver(install).observe(document, {childList:true, subtree:true});
    install();
  });
  const peer = startSecondServer(app.baseUrl ?? "");
  try {
    const {host} = await peer.ready;
    await runPromise(Effect.scoped(Effect.gen(function* () {
      const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
      yield* client["server.updateSettings"]({patch:{linkedEnvironmentsEnabled:true}});
    })));
    // Extend only the replay fixture: it calls the same MCP tool a real agent calls.
    const original = path.join(APP_DIR,"apps/server/scripts/dev-replay-agent.ts");
    let replay = await fs.readFile(original,"utf8");
    replay = replay.replace('const FIXTURES = "../src/orchestration-v2/testkit/fixtures";', `const FIXTURES = ${JSON.stringify(path.join(APP_DIR,"apps/server/src/orchestration-v2/testkit/fixtures"))};`);
    replay = replay.replaceAll('"./dev-replay/', JSON.stringify(path.join(APP_DIR,"apps/server/scripts/dev-replay/")).slice(0,-1));
    replay = replay.replace('const handleRequest =', 'let mcpEnv = {};\n  const handleRequest =');
    replay = replay.replace('const cwd = typeof params.cwd', `mcpEnv = Object.fromEntries((params.mcpServers ?? []).flatMap(s => s.env ?? []).map(v => [v.name,v.value]));\n        const cwd = typeof params.cwd`);
    replay = replay.replace('const turns = loadTurns(session.model);', `const {execFileSync} = await import("node:child_process");
        execFileSync(process.execPath, [${JSON.stringify(path.join(APP_DIR,"apps/server/src/bin.ts"))},"acp-mcp-call","t3_environment_link",${JSON.stringify(JSON.stringify({url:host, reason:"Link the test environment to continue.",clientRequestId:"settle-link-proof"}))}], {env:{...process.env,...mcpEnv},stdio:["ignore","pipe","pipe"]});
        const turns = loadTurns(session.model);`);
    const fixture = path.join(T3_HOME,"link-replay.ts");
    await fs.writeFile(fixture,replay);
    const settingsFile = path.join(T3_HOME,"userdata/settings.json");
    const settings = JSON.parse(await fs.readFile(settingsFile,"utf8"));
    settings.providerInstances.devReplay.config.commandArgs = [fixture];
    await fs.writeFile(settingsFile,JSON.stringify(settings));
    const project = await makeState(T3_HOME).state.project("Link request proof");
    const thread = await t3.thread({project,title:"Settle waiting link",messages:["Please link the test environment."],model:"multi-turn"});
    await t3.open(thread);
    await screen.getByText("first fixture turn complete", {exact:true}).waitFor();
    await screen.getByRole("button", "Review link…", {exact:true}).waitFor();
    await command(app.baseUrl ?? "", thread.threadId);

    await screen.getByText("first fixture turn complete", {exact:true}).waitFor();
    await screen.getByRole("button", "Un-settle", {exact:true}).waitFor();
    await new Promise(resolve => setTimeout(resolve, 1500));
    await browser.reload();
    await screen.getByText("first fixture turn complete", {exact:true}).waitFor();
    await screen.getByRole("button", "Un-settle", {exact:true}).waitFor();
    await new Promise(resolve => setTimeout(resolve, 1500));
    await app.screenshot("after-reload");
    await browser.keyboard.press("ControlOrMeta+k");
    await screen.getByRole("dialog", "Command palette").waitFor();
    await screen.getByRole("dialog", "Command palette").getByRole("combobox").fill("Settle waiting link");
    await new Promise(resolve => setTimeout(resolve, 1500));
    await app.screenshot("settled-thread-status");
    await browser.keyboard.press("Escape");
    await screen.getByRole("dialog", "Command palette").waitFor({state:"hidden"});
    await new Promise(resolve => setTimeout(resolve, 3000));
    await expect(screen.getByText("Request ended", {exact:true})).toBeVisible({timeout:5000});
  } finally { await peer.stop(); }
});
