import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { execFileSync } from "node:child_process";
import { readFileSync } from "node:fs";
import https from "node:https";
import { test, WEB, rpcClient, runPromise, makeState } from "./t3.ts";
import { T3_HOME } from "../e2e.config.ts";
const root = process.env.ISSUE_PROOF_DIR!;
async function api(path: string, method="GET") {
 return await new Promise<any>((resolve,reject)=>{
  const req=https.request(`https://gitea.127.0.0.1.nip.io/api/v1/${path}`,{method,ca:readFileSync(`${root}/setup/cert.pem`),headers:{Authorization:`token ${readFileSync(`${root}/setup/default-token`,"utf8")}`}},res=>{let text="";res.on("data",x=>text+=x);res.on("end",()=>resolve(text?JSON.parse(text):null));});req.on("error",reject);req.end();
 });
}
test("Issue URLs naming an unconfigured port refuse reads and comments",WEB,async({t3,app,screen})=>{
 for(const comment of await api("repos/acme/web/issues/3/comments")) await api(`repos/acme/web/issues/comments/${comment.id}`,"DELETE");
 const project=await t3.project("web");
 execFileSync("git",["remote","add","origin","https://gitea.127.0.0.1.nip.io/acme/web.git"],{cwd:project});
 await runPromise(Effect.scoped(Effect.gen(function*(){
  const rpc=yield* rpcClient(T3_HOME, app.baseUrl!);
  yield* rpc["server.updateSettings"]({patch:{},providerInstanceMutation:{operation:"upsert",instanceId:"issueProof" as never,instance:{driver:"acpRegistry" as never,displayName:"Issue proof driver",enabled:true,config:{source:"local",commandPath:process.execPath,commandArgs:[`${root}/agent.mjs`]}}}});
 })));
 const launched=await runPromise(makeState(T3_HOME).cli(["thread","start",project,"Ready","--title","Read and comment on port 8443 issue","--provider","issueProof","--model","default","--wait","--json"]));
 const thread=JSON.parse(launched.stdout);
 await t3.open(thread);
 await screen.getByText("Issue tools ready.",{exact:false}).waitFor({state:"visible"});
 await screen.getByTestId("composer-editor").fill("Read https://gitea.127.0.0.1.nip.io:8443/acme/web/issues/3 and comment: Port isolation proof comment");
 await screen.getByRole("button","Submit message").tap();
 await screen.getByText("ISSUE PROBE COMPLETE",{exact:false}).waitFor({state:"visible"});
 await screen.getByRole("button","Submit message").waitFor({state:"visible"});
 await screen.getByText("Working for",{exact:false}).waitFor({state:"hidden"});
 await screen.getByText("Syncing messages",{exact:false}).waitFor({state:"hidden"});
 await app.screenshot("issue-port-resolution");
 const comments=await api("repos/acme/web/issues/3/comments");
 await expect(comments.length).toBe(0);
 await expect(screen.getByText("Issues cannot be browsed for this project yet.",{exact:false}).first()).toBeVisible();
});
