import { CommandId, ThreadId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { copyFileSync, mkdirSync } from "node:fs";
import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Linked PR uses Gitea's subpath URL and is linked only once", WEB, async ({t3, app, browser, screen}) => {
  mkdirSync(`${T3_HOME}/bin`, {recursive:true});
  copyFileSync(`${process.env.GITEA_CLI_CONFIG_DIR}/../gt`, `${T3_HOME}/bin/gt`);
  const project = await t3.project("ACME-REPO");
  await runPromise(run("git", ["remote", "add", "origin", "http://127.0.0.1:13047/gitea/ACME/REPO.git"], {cwd:project}));
  const input = {project,title:"Gitea subpath pull request",messages:["Start"]};
  const thread = await t3.thread({...input,model:"default"}).catch((error:unknown) => {
    if (!String(error).includes("Model default is not advertised")) throw error;
    return t3.thread(input);
  });
  const tid = ThreadId.make(thread.threadId);
  const use = <A,E,R>(f: (c: Effect.Success<ReturnType<typeof rpcClient>>) => Effect.Effect<A,E,R>) => runPromise(Effect.flatMap(rpcClient(T3_HOME, app.baseUrl ?? ""), f).pipe(Effect.scoped));
  const link = (repository:string,url:string) => use(c => c["orchestration.dispatchCommand"]({type:"thread.pull-request.link",commandId:CommandId.make(crypto.randomUUID()),threadId:tid,host:"127.0.0.1:13047",repository,number:1,url,source:"agent"}));
  const read = () => use(c => c["orchestration.getThreadProjection"]({threadId:tid}));
  const correct = "http://127.0.0.1:13047/gitea/ACME/REPO/pulls/1";
  await link("acme/repo", "http://127.0.0.1:13047/ACME/REPO/pulls/1");
  await expect.poll(async () => JSON.stringify(await read()), {timeout:30000}).toContain('Add hello');
  await browser.setViewport({width:1440,height:900});
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel", {exact:true}).tap();
  await screen.getByRole("button", "Linked items L", {exact:true}).tap();
  await screen.getByRole("link", /^#1 Add hello/).waitFor();
  await browser.keyboard.down("Shift");
  await app.screenshot("synced-pr-url");
  await browser.keyboard.up("Shift");
  const first = await read();
  const linkedUrl = await browser.evaluate(() => Array.from(document.querySelectorAll<HTMLAnchorElement>('a[href*="/pulls/1"]')).find(a => a.textContent?.includes('Add hello'))?.href);
  if (!linkedUrl) throw new Error("The synced PR link is missing");
  await app.open(linkedUrl);
  await screen.getByText(linkedUrl.includes("/gitea/") ? "Add hello" : "404", {exact:false}).first().waitFor();
  await app.screenshot("synced-link-destination");
  await t3.open(thread);
  await screen.getByRole("link", /^#1 Add hello/).waitFor();
  await link("gitea/acme/repo",correct);
  await expect.poll(async () => {const x=await read();return JSON.stringify(x).includes('gitea/acme/repo') || JSON.stringify(x).includes(correct)}, {timeout:10000}).toBe(true);
  await browser.keyboard.down("Shift");
  await app.screenshot("after-linking-correct-url");
  await browser.keyboard.up("Shift");
  const last = await read();
  expect(first.thread.pullRequests[0]?.url).toBe(correct);
  expect(last.thread.pullRequests.length).toBe(1);
});
