// @effect-diagnostics nodeBuiltinImport:off -- Synthetic GitHub transport for a real-app watch reproduction.
import { createServer, type ServerResponse } from "node:http";
import { execFileSync } from "node:child_process";
import { mkdirSync, writeFileSync } from "node:fs";
import { randomUUID } from "node:crypto";
import { CommandId, ThreadId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { test, WEB, rpcClient, runPromise } from "./t3.ts";

const socket = process.env.PROOF_SOCKET!;
const page = { nodes: [], pageInfo: { hasNextPage: false, endCursor: null }, totalCount: 0 };
const url = "https://github.com/example/watch-proof/pull/7";
const ack = `<!-- This is an auto-generated reply by CodeRabbit -->\n<details>\n<summary>✅ Actions performed</summary>\n\nReview triggered.\n\n</details>`;
const pause = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));

test("CodeRabbit acknowledgement stays idle; finished and rate-limited edits wake once", WEB, async ({t3, app, browser, screen}) => {
  const sha = execFileSync("git", ["rev-parse", "--short=10", "HEAD"], { cwd: APP_DIR, encoding: "utf8" }).trim();
  const output = `${process.env.PROOF_OUTPUT}/run-${Date.now()}`;
  mkdirSync(output);
  let phase = "baseline";
  let stamp = new Date().toISOString();
  let reads = 0;
  let fingerprints = 0;
  let createdAt = stamp;
  const streams = new Set<ServerResponse>();
  const requests: unknown[] = [];
  const server = createServer(async (req, res) => {
    let raw = "";
    for await (const chunk of req) raw += chunk;
    if (req.url?.includes("/events")) {
      res.writeHead(200, {"content-type":"text/event-stream"});
      res.write(": ready\n\n"); streams.add(res); res.on("close", () => streams.delete(res)); return;
    }
    res.setHeader("content-type", "application/json");
    if (req.url?.includes("event-subscriptions")) { res.end(JSON.stringify({id:"proof",events_url:"https://api.github.com/events"})); return; }
    if (!raw) { res.end(JSON.stringify({login:"proof-viewer",id:123})); return; }
    const { query = "" } = JSON.parse(raw);
    requests.push({phase, query});
    writeFileSync(`${output}/${sha}-requests.json`, JSON.stringify(requests,null,2));
    const comment = {id:"ACK_1",body: phase === "ack" ? ack : phase === "finished" ? ack.replace("Review triggered.", "Review finished.") : ack.replace("✅ Actions performed", "❌ Action not completed").replace("Review triggered.", "Rate limit exceeded. Please try again later."), createdAt,lastEditedAt:phase === "ack" ? null : stamp,url:url+"#issuecomment-1",isMinimized:false,author:{__typename:"Bot",login:"coderabbitai",avatarUrl:"https://example.invalid/avatar.png"},reactionGroups:[]};
    const comments = phase === "baseline" ? page : {...page,nodes:[comment],totalCount:1};
    const pr = {
      id:"PR_7",number:7,title:"CodeRabbit review watch proof",url,body:"Synthetic review acknowledgement",state:"OPEN",isDraft:false,mergeable:"MERGEABLE",mergeStateStatus:"CLEAN",reviewDecision:null,
      additions:0,deletions:0,changedFiles:0,createdAt:"2026-11-01T00:00:00Z",updatedAt:stamp,mergedAt:null,mergeCommit:null,mergedBy:null,closedAt:null,
      headRefName:"feature",baseRefName:"main",headRefOid:"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",isCrossRepository:false,maintainerCanModify:true,headRepositoryOwner:null,headRepository:null,headRef:null,author:null,autoMergeRequest:null,
      viewerCanUpdate:true,viewerDidAuthor:false,viewerCanUpdateBranch:true,baseRef:{compare:{behindBy:0}},reviewRequests:page,labels:page,commits:page,latestReviews:page,reviews:page,comments,reviewThreads:page,reviewDismissals:page,mergeQueueRemovals:{...page,filteredCount:0},reactionGroups:[],stack:null,stackEntry:null
    };
    const repo = {mergeCommitAllowed:true,squashMergeAllowed:true,rebaseMergeAllowed:true,autoMergeAllowed:true,viewerPermission:"WRITE",pullRequests:page,pullRequest:pr};
    const data: Record<string,unknown> = {viewer:{login:"proof-viewer",databaseId:123},repository:repo};
    for (const alias of query.matchAll(/([_\w]+)\s*:\s*repository\s*\(/g)) data[alias[1]!] = repo;
    if (query.includes("PullRequestActivity")) reads++;
    if (query.includes("PullRequestWatchFingerprint")) fingerprints++;
    res.end(JSON.stringify({data}));
  });
  await new Promise<void>(resolve => server.listen(socket, resolve));
  try {
    const project = await t3.project(`Watch proof ${sha}`, {"README.md":"Synthetic CodeRabbit watch proof"});
    execFileSync("git", ["remote", "add", "origin", "https://github.com/example/watch-proof.git"], {cwd:project});
    const thread = await t3.thread({project,title:`CodeRabbit watch · ${sha}`,messages:["Watch the pull request and wait for actionable review feedback."],model:"multi-turn"});
    await browser.setViewport({width:1280,height:900});
    await t3.open(thread);
    await runPromise(Effect.gen(function*(){
      const client = yield* rpcClient(T3_HOME, app.baseUrl!);
      yield* client["orchestration.dispatchCommand"]({type:"thread.pull-request.watch",commandId:CommandId.make(randomUUID()),threadId:ThreadId.make(thread.threadId),host:"github.com",repository:"example/watch-proof",number:7,watching:true,link:{url,source:"agent"}});
    }).pipe(Effect.scoped));
    const snapshot = () => runPromise(Effect.gen(function*(){ const c=yield* rpcClient(T3_HOME,app.baseUrl!); return yield* c["orchestration.getThreadProjection"]({threadId:ThreadId.make(thread.threadId)}); }).pipe(Effect.scoped));
    const wait = async (predicate:()=>Promise<boolean>|boolean, what:string) => { for(let i=0;i<1700;i++){if(await predicate())return;await pause(100);} throw new Error(`Timed out: ${what}; requests ${JSON.stringify(requests).slice(-4000)}`); };
    await wait(async()=> (await snapshot()).thread.pullRequests?.[0]?.watch?.headSha != null,"baseline");

    const totals: number[] = [];
    const capture = async (label:string) => {
      await wait(async()=> (await snapshot()).runs.every(run => ["completed","failed","interrupted","cancelled"].includes(run.status)), "agent finished");
      await pause(1200);
      await app.screenshot(label);
      const s=await snapshot();
      totals.push(s.thread.pullRequests?.[0]?.watch?.wakes ?? -1);
      console.log(`${sha} ${label}: wakes=${totals.at(-1)}`);
      writeFileSync(`${output}/${sha}-${label}.json`, JSON.stringify({sha,phase,wakes:totals.at(-1),messages:s.messages,watch:s.thread.pullRequests?.[0]?.watch},null,2));
    };
    const emit = async (next:string) => {
      phase=next; stamp=new Date().toISOString(); if(next === "ack") createdAt=stamp;

      await wait(async()=> (await snapshot()).thread.pullRequests?.[0]?.watch?.remarksThrough === stamp,`processed ${next}`);
    };
    await emit("ack"); await capture("acknowledgement");
    await emit("finished"); await capture("finished-outcome");
    let seen = fingerprints;

    await wait(()=>fingerprints > seen,"unchanged finished sweep");
    await pause(1500); await capture("finished-unchanged");
    await emit("rate-limited"); await capture("rate-limited-outcome");
    seen = fingerprints;

    await wait(()=>fingerprints > seen,"unchanged rate-limited sweep");
    await pause(1500); await capture("rate-limited-unchanged");
    writeFileSync(`${output}/${sha}-requests.json`,JSON.stringify(requests,null,2));
    expect(totals,"Acknowledgement consumes zero wakes; each changed outcome consumes one, unchanged versions consume none").toEqual([0,1,1,2,2]);
  } finally { for(const stream of streams) stream.destroy(); server.close(); }
});
