import { createServer, request } from "node:http";
import { connect } from "node:net";
import { crc32 } from "node:zlib";
import { randomUUID } from "node:crypto";
import { writeFile } from "node:fs/promises";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { MOBILE, MOBILE_T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise } from "./t3.ts";
import { makeState } from "./t3.ts";

const evidenceDir = process.env.T3_PROOF_OUTPUT_DIR;
if (!evidenceDir) throw new Error("Set T3_PROOF_OUTPUT_DIR");
const evidenceHome = process.env.T3_PROOF_HOME;
if (!evidenceHome) throw new Error("Set T3_PROOF_HOME");
const state = makeState(evidenceHome, {T3CODE_PORT:String(MOBILE.serverPort)});
const t3 = state.state;
  const origin = `http://127.0.0.1:${MOBILE.serverPort}`;
  let held;
  let stallBytes = 2900;
  const downloads = [];
  const proxy = createServer((req, res) => {
    if(req.url?.startsWith("/__stall/")) { stallBytes = Number(req.url.split("/").at(-1)); res.end("ok"); return; }
    if(req.url === "/__release") { held?.(); held = undefined; res.end("ok"); return; }
    if(req.url === "/__state") { res.setHeader("Content-Type","application/json"); res.end(JSON.stringify(downloads)); return; }

    const upstream = request(origin + req.url, { method: req.method, headers: req.headers }, response => {
      res.writeHead(response.statusCode ?? 500, response.headers);
      if (!req.url?.startsWith("/api/assets/")) { response.pipe(res); return; }
      const chunks = [];
      response.on("data", chunk => chunks.push(chunk));
      response.on("end", () => {
        const bytes = Buffer.concat(chunks);
        res.write(bytes.subarray(0, stallBytes));
        downloads.push({ received: stallBytes, total: bytes.length });
        held = () => res.end(bytes.subarray(stallBytes));
      });
    });
    upstream.on("error", () => res.destroy());
    req.pipe(upstream);
  });
  proxy.on("upgrade", (req, socket, head) => {
    const upstream = connect(MOBILE.serverPort, "127.0.0.1", () => {
      upstream.write(`${req.method} ${req.url} HTTP/${req.httpVersion}\r\n` + Object.entries(req.headers).map(([k,v]) => `${k}: ${v}`).join("\r\n") + "\r\n\r\n");
      if (head.length) upstream.write(head);
      socket.pipe(upstream).pipe(socket);
    });
    upstream.on("error", () => socket.destroy());
    socket.on("error", () => upstream.destroy());
  });
  await new Promise(resolve => proxy.listen(MOBILE.serverPort + 2, "0.0.0.0", resolve));

    const project = await t3.project("Download proof");
    const { threadId } = await t3.thread({ project, title: "ZIP download proof", messages: ["hello"] });
    const zip = (size) => {
      const name = Buffer.from("contents.txt");
      const data = Buffer.alloc(size - 30 - 46 - 22 - 2 * name.length, 65);
      const crc = crc32(data);
      const local = Buffer.alloc(30);
      local.writeUInt32LE(0x04034b50,0); local.writeUInt16LE(20,4);
      local.writeUInt32LE(crc,14); local.writeUInt32LE(data.length,18); local.writeUInt32LE(data.length,22); local.writeUInt16LE(name.length,26);
      const central = Buffer.alloc(46);
      central.writeUInt32LE(0x02014b50,0); central.writeUInt16LE(20,4); central.writeUInt16LE(20,6);
      central.writeUInt32LE(crc,16); central.writeUInt32LE(data.length,20); central.writeUInt32LE(data.length,24); central.writeUInt16LE(name.length,28);
      const end = Buffer.alloc(22);
      end.writeUInt32LE(0x06054b50,0); end.writeUInt16LE(1,8); end.writeUInt16LE(1,10);
      end.writeUInt32LE(central.length + name.length,12); end.writeUInt32LE(local.length + name.length + data.length,16);
      return Buffer.concat([local,name,data,central,name,end]);
    };
    await runPromise(Effect.gen(function* () {
      const client = yield* rpcClient(evidenceHome, origin);
      const attachments = [];
      for (const [name,size] of [["sample.zip",10000],["big.zip",1000000]]) {
        const bytes = zip(size);
        const upload = yield* client["attachments.createUploadUrl"]({ type: "file", name, mimeType: "application/zip", sizeBytes: bytes.length });
        yield* Effect.promise(async () => {
          const response = await fetch(origin + upload.relativeUrl, { method: "POST", headers: {"Content-Type":"application/zip"}, body: bytes });
          if (!response.ok) throw new Error(`upload: ${response.status} ${await response.text()}`);
        });
        attachments.push({type:"file",id:upload.attachmentId,name,mimeType:"application/zip",sizeBytes:bytes.length});
      }
      yield* client["orchestration.dispatchCommand"]({ type: "message.dispatch", createdBy: "user", creationSource: "mobile", commandId: randomUUID(), threadId, messageId: randomUUID(), text: "Open these ZIPs", attachments, dispatchMode: {type:"start_immediately"} });
    }).pipe(Effect.scoped));

const paired = await runPromise(state.cli(["auth","pairing","create","--ttl","30m","--label","download proof","--base-url",`http://${MOBILE.host}:${MOBILE.serverPort+2}`]));
const pairingUrl = /Pair URL:\s*(\S+)/.exec(paired.stdout + "\n" + paired.stderr)?.[1];
await writeFile(evidenceDir+"/pairing-url",pairingUrl ?? "");
await writeFile(evidenceDir+"/thread.json",JSON.stringify({}));
console.log("Seed and proxy ready");
await new Promise(() => {});
