/**
 * Git Smart HTTP Protocol implementation.
 *
 * Handles the server side of:
 *   - GET  /:owner/:repo.git/info/refs?service=git-upload-pack
 *   - GET  /:owner/:repo.git/info/refs?service=git-receive-pack
 *   - POST /:owner/:repo.git/git-upload-pack
 *   - POST /:owner/:repo.git/git-receive-pack
 *
 * Reference: https://git-scm.com/docs/http-protocol
 */

import { getRepoPath } from "./repository";

function pktLine(data: string): string {
  const len = (data.length + 4).toString(16).padStart(4, "0");
  return `${len}${data}`;
}

function pktFlush(): string {
  return "0000";
}

export function infoRefsResponse(
  service: string,
  advertise: string
): Response {
  const body = pktLine(`# service=${service}\n`) + pktFlush() + advertise;

  return new Response(body, {
    headers: {
      "Content-Type": `application/x-${service}-advertisement`,
      "Cache-Control": "no-cache",
    },
  });
}

export async function getInfoRefs(
  owner: string,
  repo: string,
  service: string
): Promise<Response> {
  const repoDir = getRepoPath(owner, repo);
  const proc = Bun.spawn([service, "--stateless-rpc", "--advertise-refs", repoDir], {
    stdout: "pipe",
    stderr: "pipe",
  });
  const stdout = await new Response(proc.stdout).text();
  await proc.exited;
  return infoRefsResponse(service, stdout);
}

export async function serviceRpc(
  owner: string,
  repo: string,
  service: string,
  body: ReadableStream<Uint8Array> | ArrayBuffer | null,
  extraEnv?: Record<string, string>
): Promise<Response> {
  const repoDir = getRepoPath(owner, repo);
  const inputBytes = body
    ? body instanceof ArrayBuffer
      ? new Uint8Array(body)
      : new Uint8Array(await new Response(body).arrayBuffer())
    : new Uint8Array();

  const proc = Bun.spawn([service, "--stateless-rpc", repoDir], {
    stdin: "pipe",
    stdout: "pipe",
    stderr: "pipe",
    env: extraEnv ? { ...process.env, ...extraEnv } : process.env,
  });

  proc.stdin.write(inputBytes);
  proc.stdin.end();

  // git-receive-pack (push) callers install a temp pre-receive hook and
  // delete it the instant this call resolves, so pushes must keep waiting
  // for the subprocess to fully exit before we hand back a Response.
  // git-upload-pack (clone/fetch) has no such coupling, and buffering its
  // stdout via `.arrayBuffer()` was the bug: for a repo with any real
  // history the pack can be many MB, the child starts writing it to a
  // pipe with a small OS buffer well before we ever start reading, and
  // nothing drains stdout until the process exits -- on large enough
  // packs this deadlocks and the client sees the connection die mid-clone
  // (reproduced directly against this repo: shallow clone fine, full
  // clone/fetch "remote end hung up unexpectedly"). Stream it straight
  // through instead so the OS pipe stays drained the whole time.
  if (service === "git-upload-pack") {
    proc.exited.then((code) => {
      if (code !== 0) {
        new Response(proc.stderr)
          .text()
          .then((stderr) =>
            console.error(
              `[git] ${service} exited ${code} for ${owner}/${repo}: ${stderr}`
            )
          )
          .catch(() => {});
      }
    });

    return new Response(proc.stdout, {
      headers: {
        "Content-Type": `application/x-${service}-result`,
        "Cache-Control": "no-cache",
      },
    });
  }

  const stdout = await new Response(proc.stdout).arrayBuffer();
  await proc.exited;

  return new Response(stdout, {
    headers: {
      "Content-Type": `application/x-${service}-result`,
      "Cache-Control": "no-cache",
    },
  });
}
