import { expect } from "e2e";
import { test, WEB, runPromise } from "./t3.ts";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { createServer } from "node:http";
import { networkInterfaces } from "node:os";
import { spawn, execFileSync } from "node:child_process";
import { mkdirSync, writeFileSync, openSync } from "node:fs";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { Socket } from "effect/socket";
import * as NodeWS from "@effect/platform-node/NodeWS";
import { RpcClient, RpcSerialization } from "effect/rpc";
import { WsRpcGroup, ORCHESTRATION_PROTOCOL_VERSION } from "@t3tools/contracts";

const cli = (home: string, args: string[]) => execFileSync(process.execPath, ["apps/server/src/bin.ts", ...args, "--base-dir", home], {cwd: APP_DIR, encoding:"utf8"}).trim();
async function rpc(origin: string, home: string, patch: unknown) {
 const token = cli(home, ["auth","session","issue","--token-only"]).split("\n").at(-1)!;
 const res = await fetch(`${origin}/api/auth/websocket-ticket`, {method:"POST", headers:{authorization:`Bearer ${token}`, "x-t3-orchestration-protocol":String(ORCHESTRATION_PROTOCOL_VERSION)}});
 const {ticket} = await res.json() as {ticket:string};
 await runPromise(Effect.gen(function*(){
  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));
  yield* client["server.updateSettings"]({patch:patch as never});
 }).pipe(Effect.scoped));
}

test("Anonymous accounts keep distinct hubs and deduplicate shared hubs", WEB, async ({t3,app,screen,browser}) => {
 const scratch = `/tmp/factory-pr-36561-evidence-3/run-${Date.now()}`;
 mkdirSync(scratch,{recursive:true});
 const ip = Object.values(networkInterfaces()).flat().find(a=>a?.family==="IPv4"&&!a.internal)!.address;
 const hubs = [];
 for (const used of [20,70]) {
  const hub = createServer((req,res)=>{
   res.setHeader("Content-Type","application/json");
   if(req.url?.endsWith("auth-files")) res.end(JSON.stringify({files:[{id:"anonymous.json",auth_index:"synthetic",provider:"claude"}]}));
   else res.end(JSON.stringify({status_code:200,body:JSON.stringify({five_hour:{utilization:used,resets_at:new Date(Date.now()+4*3600000).toISOString()}})}));
  });
  await new Promise<void>(r=>hub.listen(0,"0.0.0.0",r)); hubs.push(hub);
 }
 const ports = hubs.map(h=>(h.address() as {port:number}).port);
 const source=(url:string,label:string)=>({kind:"cliproxy",url,label,managementKey:"synthetic-key",enabled:true});
 const secondHome=`${scratch}/second`;
 mkdirSync(`${secondHome}/userdata`,{recursive:true});
 writeFileSync(`${secondHome}/userdata/settings.json`,JSON.stringify({providerInstances:{codex:{driver:"codex",enabled:false},claudeAgent:{driver:"claudeAgent",enabled:false}},usageLimitSources:{collision:source(`http://${ip}:${ports[1]}`,"Hub B")}}));
 const portProbe=createServer(); await new Promise<void>(r=>portProbe.listen(0,"127.0.0.1",r));const secondPort=(portProbe.address() as {port:number}).port;await new Promise<void>(r=>portProbe.close(()=>r()));
 const log=openSync(`${scratch}/second.log`,"w");
 const child=spawn(process.execPath,["apps/server/src/bin.ts","serve","--host","127.0.0.1","--port",String(secondPort),"--base-dir",secondHome,"--no-browser"],{cwd:APP_DIR,env:{...process.env,PATH:`${T3_HOME}/bin:${process.env.PATH}`,T3CODE_DEV_SEED:"0"},stdio:["ignore",log,log]});
 try {
  const origin=`http://127.0.0.1:${secondPort}`;
  await fetch(origin+"/.well-known/t3/environment",{signal:AbortSignal.timeout(1000)}).catch(()=>undefined);
  // Wait for server readiness, independently of the browser's bug assertions.
  for(let i=0;i<120;i++){try{if((await fetch(origin+"/.well-known/t3/environment")).ok)break;}catch{} await new Promise(r=>setTimeout(r,500));}
  await t3.project("Hub identity proof");
  await rpc(app.baseUrl!,T3_HOME,{usageLimitSources:{collision:source(`http://${ip}:${ports[0]}`,"Hub A")}});
  await t3.open("/settings/connections");
  const pairing=cli(secondHome,["pair"]);
  const url=pairing.match(/https?:\/\/\S*\/pair\S*/)?.[0];
  if(!url)throw new Error(`No pairing URL found`);
  await screen.getByRole("button","Add environment",{exact:true}).tap();
  await screen.getByRole("textbox","Host",{exact:true}).fill(url);
  await screen.getByRole("button","Add environment",{exact:true}).last().tap();
  const observed: number[] = [];
  const capture = async (label:string) => {
   await app.open("/usage");
   await screen.getByRole("button","Limits",{exact:true}).tap();
   await screen.getByRole("button",/anonymous: .*% left/).first().waitFor({state:"visible"});
   await screen.getByRole("button","Refresh limits",{exact:true}).tap();
   await browser.locator('button[aria-label="Refresh limits"]:not(:disabled)').first().waitFor({state:"visible"});
   await app.screenshot(label);
   observed.push(await screen.getByRole("button",/anonymous: .*% left/).count());
  };
  await capture("distinct-remote-hubs");
  await rpc(app.baseUrl!,T3_HOME,{usageLimitSources:{collision:source(`http://127.0.0.1:${ports[0]}`,"Local hub A")}});
  await rpc(origin,secondHome,{usageLimitSources:{collision:source(`http://127.0.0.1:${ports[1]}`,"Local hub B")}});
  await capture("distinct-localhost-hubs");
  await rpc(app.baseUrl!,T3_HOME,{usageLimitSources:{collision:source(`http://${ip}:${ports[0]}`,"Shared hub")}});
  await rpc(origin,secondHome,{usageLimitSources:{collision:null,"different-id":source(`http://${ip}:${ports[0]}`,"Shared hub")}});
  await capture("shared-remote-hub");
  await expect(observed).toEqual([2,2,1]);
 } finally {child.kill("SIGTERM");for(const h of hubs)h.close();}
});
