import { execFileSync } from "node:child_process";
import { randomUUID } from "node:crypto";
import { writeFileSync, mkdirSync } from "node:fs";
import { CommandId, ThreadId, EnvironmentId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { SECOND_HOME, startSecondServer } from "./second-server.ts";
import { environmentId, makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

const org = process.env.AZURE_DEVOPS_TEST_ORG!;
const projectName = process.env.AZURE_DEVOPS_TEST_PROJECT!;
const az = (...args: string[]) => JSON.parse(execFileSync("az", [...args, "--organization", org, "--output", "json"], {encoding:"utf8"}));
const git = (cwd: string, ...args: string[]) => execFileSync("git", ["-c", 'credential.helper=!f() { echo username=pat; echo "password=$AZURE_DEVOPS_EXT_PAT"; }; f', ...args], {cwd, encoding:"utf8", stdio:["ignore","pipe","pipe"]});
const rpc = <A>(origin: string, f: (client: any) => Effect.Effect<A, any, any>) => runPromise(Effect.gen(function*(){ const client = yield* rpcClient(T3_HOME, origin); return yield* f(client); }).pipe(Effect.scoped) as any) as Promise<A>;

test("Moving a watched thread keeps its source idle after the PR closes", WEB, async ({t3, app, screen, browser}) => {
  const tag = `proof-46571-${Date.now()}`;
  const repo = az("repos", "show", "--repository", "t3-factory-test", "--project", projectName);
  const remote = new URL(repo.remoteUrl); remote.username=""; remote.password="";
  const url = remote.toString();
  const workspace = await t3.project("Watch move proof");
  git(workspace,"remote","add","origin",url);
  git(workspace,"fetch","origin","main");
  git(workspace,"reset","--hard","FETCH_HEAD");
  git(workspace,"checkout","-b",tag);
  writeFileSync(`${workspace}/proof-46571.txt`,tag);
  git(workspace,"add","proof-46571.txt");
  git(workspace,"-c","user.name=Scenario","-c","user.email=scenario@example.invalid","commit","-m","Watch move proof");
  git(workspace,"push","origin",tag);
  const pr = az("repos","pr","create","--repository",repo.id,"--project",projectName,"--source-branch",tag,"--target-branch","main","--title",tag);
  const prUrl = `${url}/pullrequest/${pr.pullRequestId}`;
  const server = startSecondServer(app.baseUrl!);
  try {
    const observer = await t3.thread({project:workspace,title:"Source watch evidence",messages:["Inspect the source thread records after its move."]});
    const thread = await t3.thread({project:workspace,title:"Watched PR source",messages:["Keep this thread idle while its pull request is watched."]});
    const origin=app.baseUrl!;
    const read = () => rpc<any>(origin, c=>c["orchestration.getThreadProjection"]({threadId:ThreadId.make(thread.threadId)}));
    const host=remote.hostname;
    const repository=decodeURIComponent(remote.pathname.slice(1)).toLowerCase();
    await rpc(origin,c=>c["orchestration.dispatchCommand"]({type:"thread.pull-request.watch",commandId:CommandId.make(randomUUID()),threadId:ThreadId.make(thread.threadId),host,repository,number:pr.pullRequestId,watching:true,until:"merged",link:{url:prUrl,source:"agent",repositoryWebUrl:url}}));
    // Wait for the real host read to establish the baseline before moving.
    let before:any;
    for(let i=0;i<90;i++){ before=await read(); if(before.thread.pullRequests?.[0]?.watch?.headSha) break; await new Promise(r=>setTimeout(r,1000)); }
    if(!before.thread.pullRequests?.[0]?.watch?.headSha) throw new Error("Real Azure PR watch never established a baseline");
    const {host:secondOrigin,token}=await server.ready;
    const second=makeState(SECOND_HOME);
    const clone=await second.state.project("Watch move destination");
    git(clone,"remote","add","origin",url); git(clone,"fetch","origin","main"); git(clone,"reset","--hard","FETCH_HEAD"); git(clone,"fetch","origin",tag);
    await rpc(origin,c=>c["server.updateSettings"]({patch:{linkedEnvironmentsEnabled:true}}));
    await runPromise(Effect.gen(function*(){const c=yield* rpcClient(SECOND_HOME,secondOrigin); yield* c["server.updateSettings"]({patch:{linkedEnvironmentsEnabled:true}});}).pipe(Effect.scoped));
    const pairing=JSON.parse((await runPromise(second.cli(["auth","pairing","create","--json"]))).stdout);
    await rpc(origin,c=>c["peerLinks.link"]({url:secondOrigin,pairingCode:pairing.credential,access:"full-access"}));
    await t3.open("/settings/connections");
    await screen.getByRole("button","Add environment").tap();
    const dialog=screen.getByRole("dialog");
    await dialog.getByPlaceholder("backend.example.com").fill(secondOrigin);
    await dialog.getByPlaceholder("PAIRCODE").fill(token);
    await dialog.getByRole("button","Add environment").tap();
    await t3.open(thread);
    await screen.getByText("Keep this thread idle while its pull request is watched.", {exact:true}).waitFor();
    await app.screenshot("watch-before-move");
    const destination=await runPromise(environmentId(secondOrigin));
    await rpc(origin,c=>c["threadHandoff.start"]({threadId:ThreadId.make(thread.threadId),environmentId:EnvironmentId.make(destination)}));
    let moved:any;
    for(let i=0;i<90;i++){moved=await read();if(moved.thread.handoff?.state==="departed")break;await new Promise(r=>setTimeout(r,1000));}
    if(moved.thread.handoff?.state!=="departed") throw new Error("Thread did not complete its real move");
    az("repos","pr","update","--id",String(pr.pullRequestId),"--status","completed","--squash","true");
    // A quiet PR is reread on the reactor's real polling interval.
    await new Promise(r=>setTimeout(r,140000));
    const after=await read();
    const report={initialRuns:before.runs.length,afterRuns:after.runs.length,handoff:after.thread.handoff?.state,watchPresentImmediatelyAfterMove:!!moved.thread.pullRequests?.[0]?.watch,watchPresent:!!after.thread.pullRequests?.[0]?.watch,messages:after.messages.map((m:any)=>({role:m.role,text:m.text}))};
    mkdirSync(process.env.PROOF_OUTPUT_DIR!,{recursive:true});
    writeFileSync(`${process.env.PROOF_OUTPUT_DIR}/${tag}.json`,JSON.stringify(report,null,2));
    console.log("SOURCE THREAD OBSERVATION",JSON.stringify(report));
    await screen.getByText("Keep this thread idle while its pull request is watched.", {exact:true}).waitFor();
    await app.screenshot("after-move-and-pr-close");
    const observation = ["Source thread records after external PR merge", `Move state: ${report.handoff}`, `Runs before move: ${report.initialRuns}`, `Runs after merge: ${report.afterRuns}`, `Source watch immediately after move: ${report.watchPresentImmediatelyAfterMove}`, `Source watch after merge: ${report.watchPresent}`, ""].join("\n");
    writeFileSync(`${workspace}/source-observation.txt`, observation);
    await t3.open(observer);
    await screen.getByText("Inspect the source thread records after its move.", {exact:true}).waitFor();
    await screen.getByRole("button", "Toggle terminal drawer").tap();
    const terminal = browser.locator('[aria-label="Terminal input"][data-workspace-focus-default]');
    await terminal.waitFor();
    await terminal.focus();
    await browser.keyboard.type("PS1='$ '; clear; cat source-observation.txt; echo done > observation-rendered\n");
    // The marker is written by the real terminal command after it prints the observations.
    for(let i=0;i<50;i++){try{execFileSync("test",["-f",`${workspace}/observation-rendered`]);break;}catch{await new Promise(r=>setTimeout(r,100));}}
    await new Promise(r=>setTimeout(r,500));
    await app.screenshot("source-records-after-merge");
    expect(after.runs.length,"The departed source must not receive another agent run").toBe(before.runs.length);
    expect(!!after.thread.pullRequests?.[0]?.watch,"A successful move removes the source watch").toBe(false);
    
  } finally {
    await server.stop();
    try{if(az("repos","pr","show","--id",String(pr.pullRequestId)).status==="active") az("repos","pr","update","--id",String(pr.pullRequestId),"--status","abandoned");}catch{}
    git(workspace,"push","origin","--delete",tag);
  }
});
