"use strict";
const test = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const { receiveBundle, resolveRepository } = require("./repo-push-broker");

test("repository resolution is exact and returns an explicit unregistered receipt", () => {
  const registry = {
    "bingshuo/hololake-platform": {
      branches: ["main", "feat/hldp-runtime-browser"],
      remote: "file:///srv/forgejo/hololake-platform.git",
      source_urls: [
        "https://guanghulab.com/fifth-domain/bingshuo/hololake-platform.git",
      ],
    },
  };
  assert.deepEqual(
    resolveRepository(
      "https://guanghulab.com/fifth-domain/bingshuo/hololake-platform.git",
      registry,
    ),
    {
      ok: true,
      diagnostic_code: "repository_registered",
      repo: "bingshuo/hololake-platform",
      branches: ["main", "feat/hldp-runtime-browser"],
    },
  );
  assert.deepEqual(resolveRepository("", registry), {
    ok: false,
    diagnostic_code: "local_repository_remote_missing",
  });
  assert.deepEqual(
    resolveRepository("https://example.invalid/unknown.git", registry),
    {
      ok: false,
      diagnostic_code: "repository_not_registered",
    },
  );
});

test("Guanghu Ice Heart resolves only through its public code-channel URL", () => {
  const registry = {
    "bingshuo/guanghu-ice-heart": {
      branches: ["main"],
      remote: "file:///var/lib/guanghu/personas/guanghu/hlcc-v16.0.1/data/repositories/bingshuo/guanghu-ice-heart.git",
      source_urls: [
        "https://guanghulab.com/code/bingshuo/guanghu-ice-heart.git",
      ],
    },
  };
  assert.deepEqual(
    resolveRepository(
      "https://guanghulab.com/code/bingshuo/guanghu-ice-heart.git",
      registry,
    ),
    {
      ok: true,
      diagnostic_code: "repository_registered",
      repo: "bingshuo/guanghu-ice-heart",
      branches: ["main"],
    },
  );
  assert.equal(
    resolveRepository(
      "https://guanghulab.com/fifth-domain/bingshuo/guanghu-ice-heart.git",
      registry,
    ).diagnostic_code,
    "repository_not_registered",
  );
});

test("receiver permits only an allowlisted fast-forward bundle with an exact base", async () => {
  const uploadDir = fs.mkdtempSync(path.join(os.tmpdir(), "lake-lamp-upload-"));
  const bundle = path.join(uploadDir, "one.bundle"); fs.writeFileSync(bundle, "bundle");
  const calls = [];
  const base = "a".repeat(40), incoming = "b".repeat(40);
  const run = async args => { calls.push(args); if (args.includes("rev-parse")) return { ok: true, stdout: `${incoming}\n` }; if (args[0] === "ls-remote") return { ok: true, stdout: `${base}\trefs/heads/main\n` }; return { ok: true, stdout: "" }; };
  try {
    const result = await receiveBundle({ repo: "bingshuo/guanghu-ice-heart", branch: "main", expected_head: base, bundle_path: bundle }, { uploadDir, registry: { "bingshuo/guanghu-ice-heart": { branch: "main", remote: "/srv/local/code.git", verification_url: "https://example.invalid/commits/main" } }, run });
    assert.equal(result.ok, true); assert.equal(result.commit_sha, incoming);
    assert.ok(calls.some(args => args.includes("update-ref")));
  } finally { fs.rmSync(uploadDir, { recursive: true, force: true }); }
});

test("receiver refuses a changed remote base before it can push", async () => {
  const uploadDir = fs.mkdtempSync(path.join(os.tmpdir(), "lake-lamp-upload-"));
  const bundle = path.join(uploadDir, "one.bundle"); fs.writeFileSync(bundle, "bundle");
  const base = "a".repeat(40), changed = "c".repeat(40);
  const run = async args => { if (args.includes("rev-parse")) return { ok: true, stdout: `${"b".repeat(40)}\n` }; if (args[0] === "ls-remote") return { ok: true, stdout: `${changed}\trefs/heads/main\n` }; if (args.includes("update-ref")) throw new Error("must not update"); return { ok: true, stdout: "" }; };
  try {
    const result = await receiveBundle({ repo: "bingshuo/guanghu-ice-heart", branch: "main", expected_head: base, bundle_path: bundle }, { uploadDir, registry: { "bingshuo/guanghu-ice-heart": { branch: "main", remote: "/srv/local/code.git" } }, run });
    assert.equal(result.diagnostic_code, "expected_head_mismatch");
  } finally { fs.rmSync(uploadDir, { recursive: true, force: true }); }
});

test("receiver can create only an explicitly allowlisted branch from an exact missing base", async () => {
  const uploadDir = fs.mkdtempSync(path.join(os.tmpdir(), "lake-lamp-upload-"));
  const bundle = path.join(uploadDir, "one.bundle"); fs.writeFileSync(bundle, "bundle");
  const incoming = "b".repeat(40);
  const calls = [];
  const run = async (args, options = {}) => {
    calls.push(args);
    if (args.includes("rev-parse")) return { ok: true, stdout: `${incoming}\n` };
    if (args[0] === "ls-remote") return { ok: options.allowFailure === true, stdout: "" };
    return { ok: true, stdout: "" };
  };
  try {
    const result = await receiveBundle({
      repo: "bingshuo/hololake-platform",
      branch: "feat/hldp-runtime-browser",
      expected_head: "0".repeat(40),
      bundle_path: bundle,
    }, {
      uploadDir,
      registry: {
        "bingshuo/hololake-platform": {
          branches: ["main", "feat/hldp-runtime-browser"],
          remote: "/srv/local/code.git",
        },
      },
      run,
    });
    assert.equal(result.ok, true);
    assert.equal(result.commit_sha, incoming);
    assert.ok(calls.some(args => args.includes("update-ref")));
  } finally {
    fs.rmSync(uploadDir, { recursive: true, force: true });
  }
});
