import * as NodeWS from "@effect/platform-node/NodeWS";
import { CommandId, ThreadId, ORCHESTRATION_PROTOCOL_VERSION, WsRpcGroup } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { RpcClient, RpcSerialization } from "effect/rpc";
import { Socket } from "effect/socket";
import { readFileSync } from "node:fs";
import { randomUUID } from "node:crypto";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

const scratch = process.env.PROOF_FIXTURE_DIR!;
const pause = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
const rpc = (origin: string, work: (client: any) => Effect.Effect<any, any, any>) => runPromise(Effect.gen(function* () {
 const issued = yield* makeState(T3_HOME).cli(["auth", "session", "issue", "--token-only"]);
 const response = yield* Effect.promise(() => fetch(`${origin}/api/auth/websocket-ticket`, {method:"POST",headers:{authorization:`Bearer ${issued.stdout.trim()}`}}));
 const {ticket} = yield* Effect.promise(() => response.json());
 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)));
 const client = yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol));
 return yield* work(client);
}).pipe(Effect.scoped));

async function resetForges() {
 for (const [side,port] of [["default",""],["ported",":8443"]]) {
  const headers={authorization:`token ${readFileSync(`${scratch}/${side}/token`,"utf8")}`};
  const origin=`https://gitea.test${port}`;
  const comments=await (await fetch(`${origin}/api/v1/repos/acme/web/issues/3/comments`,{headers})).json();
  for(const c of comments) await fetch(`${origin}/api/v1/repos/acme/web/issues/comments/${c.id}`,{method:"DELETE",headers});
 }
}

test("An unconfigured issue port cannot read or comment on the default server, or open its in-app issue", WEB, async ({t3,app,screen,browser}) => {
 await resetForges();
 const project=await t3.project("web",{".git/config":"[core]\n repositoryformatversion = 0\n bare = false\n[remote \"origin\"]\n url = https://gitea.test/acme/web.git\n fetch = +refs/heads/*:refs/remotes/origin/*\n"});
 await rpc(app.baseUrl!, client=>client["server.updateSettings"]({patch:{},providerInstanceMutation:{operation:"upsert",instanceId:"devReplay",instance:{driver:"acpRegistry",displayName:"Replay (dev)",enabled:true,config:{source:"local",commandPath:process.execPath,commandArgs:[`${scratch}/agent.mjs`]}}}}));
 const thread=await t3.thread({project,title:"Issue URL port isolation proof",messages:["Show the link https://gitea.test:8443/acme/web/issues/3 so I can click it before asking you to read and comment."]});
 await rpc(app.baseUrl!, client=>client["orchestration.dispatchCommand"]({type:"thread.runtime-mode.set",commandId:CommandId.make(randomUUID()),threadId:ThreadId.make(thread.threadId),runtimeMode:"full-access"}));
 await t3.open(thread);
 await screen.getByRole("link","Port 8443 issue").tap();
 await pause(2500);
 const openedWrongIssue=await browser.evaluate(()=>document.body.innerText.includes("DEFAULT PORT — must not be accessed"));
 await app.screenshot("clicked-ported-issue-link");
 await screen.getByTestId("composer-editor").fill("Read https://gitea.test:8443/acme/web/issues/3, then comment on that URL: PORT ISOLATION PROOF: comment requested for port 8443 only.");
 await screen.getByTestId("composer-editor").press("Enter");
 // Wait for the real deterministic agent's second MCP operation to render, on either outcome.
 await expect.poll(()=>browser.evaluate(()=>document.body.innerText.includes("comment_on_issue:")),{timeout:60000}).toBe(true);
 await pause(3500);
 const output=await browser.evaluate(()=>document.body.innerText);
 await app.screenshot("read-and-comment-results");
 let defaultComments=0,portedComments=0;
 for(const [side,port] of [["default",""],["ported",":8443"]]) {
  const comments=await(await fetch(`https://gitea.test${port}/api/v1/repos/acme/web/issues/3/comments`,{headers:{authorization:`token ${readFileSync(`${scratch}/${side}/token`,"utf8")}`}})).json();
  if(side==="default")defaultComments=comments.length;else portedComments=comments.length;
  await app.open(`https://gitea.test${port}/acme/web/issues/3`);
  await pause(1800);
  await app.screenshot(`${side}-forge-after-comment`);
 }
 await expect({openedWrongIssue,readRejected:output.includes("read_issue: REJECTED"),commentRejected:output.includes("comment_on_issue: REJECTED"),defaultComments,portedComments}).toEqual({openedWrongIssue:false,readRejected:true,commentRejected:true,defaultComments:0,portedComments:0});
});
