import * as Http from "node:http";
import { mkdir, writeFile } from "node:fs/promises";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
test("A completed workflow agent advances while Linear's issue read is held open", WEB, async ({t3, app}) => {
  const key = process.env.LINEAR_API_KEY;
  if (!key) throw new Error("Real Linear test key is required");
  const graphql = async (query: string, variables = {}) => {
    const response = await fetch("https://api.linear.app/graphql", {method:"POST", headers:{Authorization:key,"Content-Type":"application/json"}, body:JSON.stringify({query,variables})});
    const result = await response.json();
    if (result.errors) throw new Error(JSON.stringify(result.errors));
    return result.data;
  };
  let stall = false;
  let held = 0;
  const proxy = Http.createServer(async (req,res) => {
    let body = "";
    for await (const chunk of req) body += chunk;
    if (stall && /query\s+T3Issue\s*\(/.test(JSON.parse(body).query)) {
      held++;
      console.log("STALL T3Issue: request held open without a response");
      return;
    }
    try {
      const upstream = await fetch("https://api.linear.app/graphql", {method:"POST",headers:{Authorization:key,"Content-Type":"application/json"},body});
      res.writeHead(upstream.status,{"Content-Type":"application/json"});
      res.end(await upstream.text());
    } catch { res.destroy(); }
  });
  await new Promise<void>(resolve => proxy.listen(13997,"127.0.0.1",resolve));
  let issueId: string | undefined;
  const cli = async (args: string[]) => JSON.parse((await runPromise(makeState(T3_HOME).cli([...args,"--json"]))).stdout);
  const rpc = <A>(f: (client: any) => Effect.Effect<A, any, any>) => runPromise(Effect.gen(function*(){const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");return yield* f(client);}).pipe(Effect.scoped) as any);
  try {
    const created = await graphql('mutation($input:IssueCreateInput!){issueCreate(input:$input){issue{id url identifier}}}',{input:{teamId:process.env.LINEAR_TEST_TEAM_ID,title:"factory-pr-49582 tracker stall proof " + Date.now()}});
    issueId = created.issueCreate.issue.id;
    const issueUrl = created.issueCreate.issue.url;
    const project = await t3.project("app");
    const seeded = await t3.thread({project,title:"Ready",messages:["Ready"],model:"multi-turn"});
    const projectId = (await cli(["thread","show",seeded.threadId])).thread.projectId;
    await rpc(client => client["issueTrackers.connect"]({tracker:"linear",token:key}));
    await rpc(client => client["issueTrackers.bindProject"]({projectId,binding:{tracker:"linear",scope:process.env.LINEAR_TEST_TEAM_KEY}}));
    await mkdir(`${T3_HOME}/workflows`,{recursive:true});
    await writeFile(`${T3_HOME}/workflows/tracker-stall.ts`, `export default T3.workflow("tracker-stall", {version:1,payload:Schema.Struct({})}, Effect.fn(function*(){
      yield* T3.agent("fix", {project:${JSON.stringify(project)}, brief:"Reply done.", model:{instanceId:"devReplay",model:"multi-turn"}, issue:{project:${JSON.stringify(project)},url:${JSON.stringify(issueUrl)}},timeout:"1 minute"});
      yield* T3.step("after",{returns:Schema.String},Effect.succeed("Agent finished; subsequent step ran"));
    }));`);
    await rpc(client => client["server.updateSettings"]({patch:{workflowsEnabled:true}}));
    await delay(3000);
    const control = await cli(["workflow","start","tracker-stall","--key","control"]);
    const controlId = control.run.runId;
    let controlDetail;
    for(let i=0;i<30;i++) {controlDetail = await cli(["workflow","show",controlId]); if(controlDetail.run.status === "completed") break; await delay(1000);}
    if(controlDetail.run.status !== "completed") throw new Error("Passing control did not complete: " + JSON.stringify(controlDetail));
    console.log("CONTROL completed with real Linear requests passing through");
    stall = true;
    const started = await cli(["workflow","start","tracker-stall","--key","stalled-1"]);
    const runId = started.run.runId;
    await t3.open(`/workflows?run=${runId}`);
    await delay(90000);
    if(held === 0) throw new Error("Proxy did not hold a T3Issue request");
    const detail = await cli(["workflow","show",runId]);
    const threads = await cli(["thread","list","--project",project]);
    console.log("STALLED RUN after 90 seconds",JSON.stringify(detail));
    console.log("AGENT THREADS",JSON.stringify(threads));
    await app.screenshot("workflow-with-tracker-held-open");
    await expect(detail.run.status).toBe("completed");
  } finally {
    proxy.closeAllConnections();
    await new Promise(resolve => proxy.close(resolve));
    if(issueId) await graphql('mutation($id:String!){issueArchive(id:$id){success}}',{id:issueId});
  }
});
