import { expect } from "e2e";
import { mkdir, writeFile } from "node:fs/promises";
import { test, WEB, runPromise } from "./t3.ts";
import { run } from "./shell.ts";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";

// Uses the running app's owner-auth path, just like `t3 thread`, and calls real MCP tools.
const driver = `
import * as NodeServices from '@effect/platform-node/NodeServices';
import * as NodeCrypto from '@effect/platform-node/NodeCrypto';
import * as NetService from '@t3tools/shared/Net';
import * as Effect from 'effect/Effect';
import * as Layer from 'effect/Layer';
import * as Option from 'effect/Option';
import * as References from 'effect/References';
import * as EnvironmentAuth from './src/auth/EnvironmentAuth.ts';
import * as ServerConfig from './src/config.ts';
import { resolveCliAuthConfig } from './src/cli/config.ts';
import { readLiveServerRuntimeState } from './src/serverRuntimeState.ts';
import { mcpToolSession } from './src/mcp/AcpMcpStdioBridge.ts';
const [home, threadId, phase] = process.argv.slice(2);
const program = Effect.gen(function* () {
 const config = yield* resolveCliAuthConfig({baseDir:Option.some(home)}, Option.none(), {quietLogs:true});
 return yield* Effect.gen(function* () {
  const runtime = yield* readLiveServerRuntimeState(config.serverRuntimeStatePath);
  const auth = yield* EnvironmentAuth.EnvironmentAuth;
  const issued = yield* Effect.acquireRelease(auth.issueMcpClientSession({label:'Review URL evidence',access:'full-access',peerLink:false,client:{deviceType:'bot'}}), s=>auth.revokeSession(s.sessionId));
  const session = yield* mcpToolSession({endpoint:new URL('/mcp',runtime.value.origin).href,authorization:'Bearer '+issued.token,clientName:'review-url-evidence'});
  const target = {threadId,url:'https://vcs.example.com:8080/review/123456?view=files#comments',repository:'Team/Project',number:123456};
  const calls=[];
  const call = function*(name,args) { const result=yield* session.call(name,args);calls.push({name,arguments:args,result});return result; };
  if(phase==='link') {
   yield* call('link_pull_request',target);
   yield* call('link_pull_request',{...target,repository:'team/project'});
   yield* call('list_thread_pull_requests',{threadId});
  } else if(phase==='unlink') {
   yield* call('unlink_pull_request',{threadId,host:'VCS.EXAMPLE.COM:8080',repository:'TEAM/PROJECT',number:123456});
   yield* call('list_thread_pull_requests',{threadId});
  } else {
   yield* call('link_pull_request',{threadId,host:'vcs.example.com:8080',repository:'Team/Project',number:123456});
   yield* call('list_thread_pull_requests',{threadId});
  }
  return calls;
 }).pipe(Effect.scoped,Effect.provide(EnvironmentAuth.layerRuntime.pipe(Layer.provide(ServerConfig.layer(config)),Layer.provide(Layer.succeed(References.MinimumLogLevel,config.logLevel)))));
});
console.log(JSON.stringify(await Effect.runPromise(program.pipe(Effect.provide([NodeServices.layer,NodeCrypto.layer,NetService.layer])))));
`;

test("Custom review URL survives link, dedupe and normalized unlink", WEB, async ({t3,app,browser,screen}) => {
 const project = await t3.project("review-url-demo");
 await runPromise(run("git",["remote","add","origin","https://github.com/Team/Project.git"],{cwd:project}));
 const thread = await t3.thread({project,title:"Custom review URL",messages:["Link the custom review URL with explicit repository and number."]});
 await t3.open(thread);
 await screen.getByRole("textbox").fill("", { timeout: 120_000 });
 const folder = `${process.env.T3_REVIEW_EVIDENCE_DIR}/run-${Date.now()}`;
 await mkdir(folder,{recursive:true});
 const driverPath = `${APP_DIR}/apps/server/.review-driver.mjs`;
 await writeFile(driverPath,driver.replaceAll("'./src/",`'${APP_DIR}/apps/server/src/`));
 const invoke = async (phase:string) => {
  const result=await runPromise(run(process.execPath,[driverPath,T3_HOME,thread.threadId,phase],{cwd:`${APP_DIR}/apps/server`,allowExit:[0,1]}));
  if(result.exitCode!==0) { await writeFile(`${folder}/error.txt`,result.stderr); throw new Error(result.stderr.slice(0,2500)); }
  const calls=JSON.parse(result.stdout.trim());
  await writeFile(`${folder}/${phase}.json`,JSON.stringify(calls,null,2));
  return calls;
 };
 const settle = async (calls:any[]) => {
  const urls = calls.at(-1).result.structuredContent.pullRequests.map((pr:any)=>pr.url).sort();
  await browser.evaluate((expected:string[]) => new Promise<void>((resolve) => {
   const current = () => [...new Set(Array.from(document.querySelectorAll('a')).map(a=>a.href).filter(href=>href.includes('vcs.example.com')))].sort();
   const observer = new MutationObserver(() => {
    if(JSON.stringify(current())===JSON.stringify(expected)) { observer.disconnect();resolve(); }
   });
   if(JSON.stringify(current())===JSON.stringify(expected)) {resolve();return;}
   observer.observe(document.documentElement,{subtree:true,childList:true,attributes:true});
  }), urls);
 };
 const linked=await invoke("link");
 await settle(linked);
 await app.screenshot("custom-url-linked");
 // Inspect the real rendered link as well as the real MCP response.
 const hrefs = await browser.evaluate(()=>Array.from(document.querySelectorAll('a')).map(a=>a.href));
 const unlinked=await invoke("unlink");
 await settle(unlinked);
 await app.screenshot("normalized-unlink");
 const fallback=await invoke("fallback");
 await settle(fallback);
 await app.screenshot("identifiers-only-alternative");
 await writeFile(`${folder}/rendered-hrefs.json`,JSON.stringify(hrefs,null,2));
 const content=(call:any)=>call.result.structuredContent;
 await expect(content(linked[0])?.url).toBe("https://vcs.example.com:8080/review/123456?view=files#comments");
 await expect(content(linked[1])?.alreadyLinked).toBe(true);
 await expect(content(linked[2])?.pullRequests?.[0]?.url).toBe("https://vcs.example.com:8080/review/123456?view=files#comments");
 await expect(hrefs).toContain("https://vcs.example.com:8080/review/123456?view=files#comments");
 await expect(content(unlinked[0])?.wasLinked).toBe(true);
 await expect(content(unlinked[1])?.pullRequests).toEqual([]);
});
