import { expect } from "e2e";
import { spawn, execFileSync } from "node:child_process";
import { createCipheriv } from "node:crypto";
import { mkdtemp, mkdir, writeFile, readdir, stat } from "node:fs/promises";
import { createServer, connect } from "node:net";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { test, WEB } from "./t3.ts";

const scratch = process.env.PROOF_SCRATCH ?? join(tmpdir(), "interrupted-fetch-proof");
const pause = (ms: number) => new Promise(r => setTimeout(r, ms));
const git = (cwd: string, ...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
const listen = (server: ReturnType<typeof createServer>) => new Promise<number>(r => server.listen(0, "127.0.0.1", () => r((server.address() as {port:number}).port)));

test("Failed background status fetches leave no abandoned packs", WEB, async ({t3, app, browser, screen}) => {
  await mkdir(scratch, {recursive:true});
  const run = await mkdtemp(join(scratch, "run-"));
  const project = await t3.project("Interrupted-fetch", { "README.md": "Synthetic interrupted-fetch reproduction\n" });
  const remote = join(run, "remote.git");
  git(run, "clone", "--bare", project, remote);
  git(project, "remote", "add", "origin", remote);
  git(project, "fetch", "origin");
  git(project, "branch", "--set-upstream-to=origin/main", "main");
  const updater = join(run, "updater");
  git(run, "clone", remote, updater);
  const backlog = createCipheriv("aes-256-ctr", Buffer.alloc(32,7), Buffer.alloc(16)).update(Buffer.alloc(300*24000));
  for (let i=0;i<300;i++) await writeFile(join(updater, `random-${i}.bin`), backlog.subarray(i*24000,(i+1)*24000));
  git(updater, "add", ".");
  git(updater, "-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-m", "Large upstream backlog");
  git(updater, "push", "origin", "main");
  const reservation = createServer();
  const daemonPort = await listen(reservation);
  await new Promise<void>(r => reservation.close(() => r()));
  const serving = spawn("git", ["daemon", "--reuseaddr", "--export-all", "--listen=127.0.0.1", `--port=${daemonPort}`, `--base-path=${run}`, run], {stdio:"ignore"});
  let cuts = 0;
  const sockets = new Set<ReturnType<typeof connect>>();
  const proxy = createServer(client => {
    const upstream = connect(daemonPort,"127.0.0.1");
    sockets.add(client); sockets.add(upstream);
    let bytes = 0;
    client.on("data", chunk => upstream.write(chunk));
    upstream.on("data", chunk => {
      const available = Math.min(chunk.length, 1_500_000 - bytes);
      if (available > 0) client.write(chunk.subarray(0,available));
      bytes += available;
      if (bytes >= 1_500_000) { cuts++; client.end(); upstream.destroy(); }
    });
    client.on("error",()=>{}); upstream.on("error",()=>client.destroy());
    client.on("close",()=>{sockets.delete(client); upstream.destroy();});
    upstream.on("close",()=>{sockets.delete(upstream); client.end();});
  });
  const port = await listen(proxy);
  git(project,"remote","set-url","origin",`git://127.0.0.1:${port}/remote.git`);
  const packs = async () => {
    const directory = join(project,".git/objects/pack");
    return Promise.all((await readdir(directory)).filter(n=>n.startsWith("tmp_pack_")).map(async name=>({name,bytes:(await stat(join(directory,name))).size})));
  };
  const attempts: {attempt:number; bytes:number; packs:number}[] = [];
  try {
    const thread = await t3.thread({project,title:"Interrupted background fetch",messages:["Ready for Git status inspection"]});
    await t3.open(thread);
    const deadline = Date.now()+200_000;
    let seen = 0;
    while (attempts.length<3 && Date.now()<deadline) {
      if (cuts>seen) {
        seen = cuts;
        await pause(1500);
        const files = await packs();
        attempts.push({attempt:seen,bytes:files.reduce((a,f)=>a+f.bytes,0),packs:files.length});
        await writeFile(join(run,"observations.json"),JSON.stringify(attempts,null,2));
      }
      await pause(250);
    }
    if (attempts.length<3) throw new Error(`Only ${cuts} interrupted background transfers observed before deadline`);
    const files = await packs();
    const report = ["INTERRUPTED BACKGROUND STATUS FETCH", "Linux | web | Chromium | 1280 x 800", "Remote: 300 random files; each transfer cut at 1,500,000 bytes", "", "Attempt   Abandoned packs   Total bytes", ...attempts.map(a=>`${String(a.attempt).padEnd(10)}${String(a.packs).padEnd(18)}${a.bytes}`), "", `Final abandoned packs: ${files.length}`, ...files.map(f=>`${f.name}  ${f.bytes} bytes`), "", "Repository object accounting:", git(project,"count-objects","-vH")].join("\n");
    await writeFile(join(project,".git/evidence.txt"),report);
    await writeFile(join(run,"evidence.txt"),report);
    await screen.getByRole("button", "Toggle terminal drawer").tap();
    const box = await browser.evaluate(() => {
      const b = document.querySelector("[data-thread-terminal-drawer]")!.getBoundingClientRect();
      return {x:b.x+b.width/2,y:b.y+2};
    });
    await browser.mouse.move(box.x,box.y);
    await browser.mouse.down();
    await browser.mouse.move(box.x,200);
    await browser.mouse.up();
    const input = screen.getByRole("textbox", "Terminal input");
    await input.waitFor({timeout:30_000});
    await input.focus();
    await browser.keyboard.type("export PS1='$ '; printf '\\033[2J\\033[H'; cat .git/evidence.txt; touch .git/evidence-shown\n");
    const renderDeadline = Date.now()+20_000;
    while (Date.now()<renderDeadline) { try {await stat(join(project,".git/evidence-shown"));break;}catch{await pause(200);} }
    await pause(1000);
    await app.screenshot("after-three-interrupted-fetches");
    await expect(files.length).toBe(0);
  } finally {
    for (const socket of sockets) socket.destroy();
    await new Promise<void>(r=>proxy.close(()=>r()));
    serving.kill();
  }
});
