/// <reference lib="dom" />
import * as http from "node:http";
import * as fs from "node:fs/promises";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { SCENARIO_LINEAR_PORT } from "./start-app.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Uppercase and mixed-case Linear hosts open beside the thread", WEB, async ({t3, app, browser, screen}) => {
  // Transparent transport proxy: every response comes from the real test team's Linear API.
  const proxy = http.createServer(async (req,res) => {
    try {
      const chunks = [];
      for await (const chunk of req) chunks.push(chunk);
      const upstream = await fetch("https://api.linear.app/graphql", {
        method:"POST", headers:{"content-type":"application/json", authorization:req.headers.authorization ?? ""},
        body:Buffer.concat(chunks),
      });
      res.writeHead(upstream.status, {"content-type":"application/json"});
      res.end(await upstream.text());
    } catch { res.writeHead(502); res.end(); }
  });
  await new Promise<void>(resolve => proxy.listen(SCENARIO_LINEAR_PORT,"127.0.0.1",resolve));
  const key = process.env.LINEAR_EVIDENCE_KEY!;
  const hosts = ["LINEAR.APP", "Linear.App", "linear.app"];
  const transcript = hosts.flatMap(host => [
    {type:"expect_outbound",frame:{kind:"request",method:"session/prompt",params:{}}},
    {type:"emit_inbound",frame:{kind:"notification",method:"session/update",params:{sessionId:"replay",update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[${key} via ${host}](https://${host}/pinglabs/issue/${key})`}}}}},
    {type:"emit_inbound",frame:{kind:"response",method:"session/prompt",result:{stopReason:"end_turn"}}},
  ]).map(x=>JSON.stringify(x)).join("\n");
  try {
    const project = await t3.project("demo-proj");
    await runPromise(Effect.gen(function*(){
      const rpc = yield* rpcClient(T3_HOME, app.baseUrl!);
      yield* rpc["issueTrackers.connect"]({tracker:"linear", token:process.env.LINEAR_API_KEY!});
    }).pipe(Effect.scoped));
    await t3.open("/settings/source-control");
    await screen.getByRole("button","Toggle Linear details").tap();
    await screen.getByRole("combobox","Linear team for demo-proj").tap();
    await screen.getByRole("option","T3 Code Factory (T3CF)").tap();
    await browser.keyboard.press("Escape");
    const recording = `${project}/linear.ndjson`;
    await fs.writeFile(recording,transcript);
    const agentSource = await fs.readFile(`${APP_DIR}/apps/server/scripts/dev-replay-agent.ts`,"utf8");
    await fs.writeFile(`${project}/linear-replay.ts`,agentSource.replace('file: `${FIXTURES}/multi_turn/registry_transcript.ndjson`', `file: "file://${recording}"`));
    await runPromise(Effect.gen(function*(){
      const rpc = yield* rpcClient(T3_HOME, app.baseUrl!);
      yield* rpc["server.updateSettings"]({patch:{}, providerInstanceMutation:{operation:"upsert", instanceId:"devReplay", instance:{driver:"acpRegistry", displayName:"Replay (dev)", enabled:true, config:{source:"local", commandPath:process.execPath, commandArgs:[`${project}/linear-replay.ts`]}}}});
    }).pipe(Effect.scoped));
    const thread = await t3.thread({project,title:"Linear hostname comparison",messages:["Show uppercase link","Show mixed-case link","Show lowercase link"]});
    await t3.open(thread);
    const panel = () => browser.locator(`[aria-label="Workspace panel: ${key}"]`);
    await screen.getByRole("link",`${key} via linear.app`,{exact:true}).tap();
    await panel().waitFor();
    await screen.getByText("[pr-43211-evidence] uppercase host link",{exact:true}).waitFor();
    await app.screenshot("lowercase-control");
    await screen.getByRole("button",`Close ${key}`,{exact:true}).tap();
    // Observe default prevention without altering navigation or the app's handlers.
    await browser.evaluate(() => {
      (window as any).__linearClicks = [];
      document.addEventListener("click", event => {
        const a = (event.target as Element)?.closest("a");
        if (a?.href.toLowerCase().includes("linear.app/")) (window as any).__linearClicks.push(event);
      }, true);
    });
    const opened = [];
    for (const [host,label] of [["LINEAR.APP","uppercase-click"],["Linear.App","mixed-case-click"]]) {
      await screen.getByRole("link",`${key} via ${host}`,{exact:true}).tap();
      const visible = await browser.evaluate(k => !!document.querySelector(`[aria-label="Workspace panel: ${k}"]`), key);
      opened.push(visible);
      if (visible) await screen.getByText("[pr-43211-evidence] uppercase host link",{exact:true}).waitFor();
      await app.screenshot(label);
      if (visible) await screen.getByRole("button",`Close ${key}`,{exact:true}).tap();
    }
    await screen.getByRole("link",`${key} via linear.app`,{exact:true}).tap();
    await panel().waitFor();
    await screen.getByText("[pr-43211-evidence] uppercase host link",{exact:true}).waitFor();
    await app.screenshot("lowercase-control-again");
    expect(opened).toEqual([true,true]);
    expect(await browser.evaluate(()=>(window as any).__linearClicks.map((c:any)=>c.defaultPrevented))).toEqual([true,true,true]);
  } finally {
    await new Promise(resolve=>proxy.close(resolve));
  }
});
