import { describe, expect, test } from "bun:test";
import { spawnSync } from "node:child_process";
import { resolve } from "node:path";

const evaluator = resolve(import.meta.dir, "platform_infra_gitea_status_evaluator.py");

describe("Gitea source authority status evaluator", () => {
  test("fails closed for GitHub hooks error objects and malformed lists", () => {
    expect(evaluate({
      action: "parse-github-hooks-response",
      ok: false,
      status: 403,
      body: JSON.stringify({ message: "forbidden" }),
    })).toEqual({ ok: false, status: 403, hooks: [], error: "github-hooks-http-403" });
    expect(evaluate({
      action: "parse-github-hooks-response",
      ok: true,
      status: 200,
      body: JSON.stringify({ message: "not a list" }),
    }).error).toBe("github-hooks-response-not-list");
    expect(evaluate({
      action: "parse-github-hooks-response",
      ok: true,
      status: 200,
      body: JSON.stringify([{ id: 1 }, "malformed"]),
    }).error).toBe("github-hooks-item-not-object");
  });

  test("reads GitHub hook URLs from object and string config shapes", () => {
    expect(evaluate({ action: "github-hook-url", hook: { config: { url: "https://hooks.example/object" } } })).toBe("https://hooks.example/object");
    expect(evaluate({ action: "github-hook-url", hook: { config: "https://hooks.example/string" } })).toBe("https://hooks.example/string");
    expect(evaluate({ action: "github-hook-url", hook: "malformed" })).toBe("");
  });

  test("parses branch and exact snapshot from ls-remote output larger than the display tail budget", () => {
    const head = "2".repeat(40);
    const prefix = "refs/unidesk/snapshots/gitea-actions/unidesk-master-nc01";
    const historical = Array.from({ length: 420 }, (_, index) => {
      const sha = index.toString(16).padStart(40, "0");
      return `${sha}\t${prefix}/${sha}`;
    });
    const output = [
      `${head}\trefs/heads/master`,
      `${head}\t${prefix}/${head}`,
      ...historical,
    ].join("\n");
    expect(Buffer.byteLength(output)).toBeGreaterThan(20_000);
    const refs = evaluate({ action: "parse-ls-remote", output });
    expect(refs["refs/heads/master"]).toBe(head);
    expect(refs[`${prefix}/${head}`]).toBe(head);
  });

  test("anchors the current committed head beyond more than fifty unrelated feature pushes", () => {
    const head = "7".repeat(40);
    const committed = committedInbox("master-durable-guid", head);
    const headRecord = evaluate({
      action: "select-committed-head-record",
      repoKey: "fixture",
      githubHead: head,
      records: [committedInbox("old-guid", "6".repeat(40)), committed],
    });
    expect(headRecord.deliveryId).toBe("master-durable-guid");
    expect(evaluate({
      action: "select-committed-head-record",
      repoKey: "fixture",
      githubHead: "8".repeat(40),
      records: [committed],
    })).toBeNull();
    const featureDeliveries = Array.from({ length: 75 }, (_, index) => ({
      id: String(10_000 - index),
      deliveryId: `feature-${index}`,
      deliveredAt: `2026-07-11T23:${String(index % 60).padStart(2, "0")}:00Z`,
      repository: "pikasTech/fixture",
      ref: `refs/heads/feature-${index}`,
      requestedCommit: index.toString(16).padStart(40, "0"),
    }));
    const masterDelivery = {
      id: "42",
      deliveryId: "master-durable-guid",
      deliveredAt: "2026-07-11T22:00:00Z",
      repository: "pikasTech/fixture",
      ref: "refs/heads/main",
      requestedCommit: head,
    };
    const failedRedelivery = {
      id: "43",
      deliveryId: "failed-redelivery-same-head",
      deliveredAt: "2026-07-11T23:59:59Z",
      statusCode: 502,
      repository: "pikasTech/fixture",
      ref: "refs/heads/main",
      requestedCommit: head,
    };
    const selected = evaluate({
      action: "select-target-delivery",
      deliveries: [...featureDeliveries, failedRedelivery, masterDelivery],
      repository: "pikasTech/fixture",
      ref: "refs/heads/main",
      requestedCommit: head,
      deliveryId: headRecord.deliveryId,
    });
    expect(selected).toEqual(masterDelivery);
  });

  test("selects only the exact branch-derived immutable snapshot", () => {
    const head = "b".repeat(40);
    const result = evaluate({
      action: "select-snapshot",
      branchCommit: head,
      snapshotPrefix: "refs/snapshots/source",
      refs: {
        "refs/snapshots/source/zzzz": "f".repeat(40),
        [`refs/snapshots/source/${head}`]: head,
      },
    });
    expect(result).toEqual({
      expectedSnapshotRef: `refs/snapshots/source/${head}`,
      snapshotRef: `refs/snapshots/source/${head}`,
      snapshotCommit: head,
      sourceBundleReady: true,
    });

    const missing = evaluate({
      action: "select-snapshot",
      branchCommit: head,
      snapshotPrefix: "refs/snapshots/source",
      refs: { "refs/snapshots/source/zzzz": "f".repeat(40) },
    });
    expect(missing.snapshotRef).toBeNull();
    expect(missing.sourceBundleReady).toBe(false);
  });

  test("latest failed delivery cannot be hidden by an older successful bridge event", () => {
    const head = "b".repeat(40);
    const row = evaluateRow({
      head,
      branchCommit: head,
      snapshotCommit: head,
      deliveryId: "new-delivery",
      statusCode: 502,
      bridgeEvents: [terminalEvent("old-delivery", head)],
      inboxRecords: [committedInbox("old-delivery", head)],
    });
    expect(row.authorityMatches).toBe(true);
    expect(row.deliveryAccepted).toBe(false);
    expect(row.correlatedBridgeEvent).toBeNull();
    expect(row.bridgeEventStale).toBe(true);
    expect(row.staleReason).toBe("target-branch-delivery-failed");
  });

  test("missing selected delivery never inherits latest push status", () => {
    const head = "7".repeat(40);
    const row = evaluate({
      action: "evaluate-repository",
      repo: { key: "fixture", upstream: { repository: "pikasTech/fixture", branch: "main" }, snapshot: { prefix: "refs/snapshots/source" } },
      hook: {
        hookId: 1,
        hookReady: true,
        latestPush: { deliveryId: "unrelated-latest", event: "push", statusCode: 202, repository: "pikasTech/fixture", ref: "refs/heads/main", requestedCommit: head },
        selectedPush: null,
      },
      head: { ok: true, sha: head },
      mirror: { branchCommit: head, snapshotCommit: head, snapshotRef: `refs/snapshots/source/${head}` },
      bridgeEvents: [],
      inboxRecords: [],
    });
    expect(row.latestPushDelivery.deliveryId).toBe("unrelated-latest");
    expect(row.selectedPushDelivery).toBeNull();
    expect(row.deliveryId).toBe("");
    expect(row.deliveryAccepted).toBe(false);
  });

  test("selects the exact durable proof across duplicate exact-url hooks without hiding topology drift", () => {
    const head = "8".repeat(40);
    const row = evaluate({
      action: "evaluate-repository",
      repo: {
        key: "fixture",
        upstream: { repository: "pikasTech/fixture", branch: "main" },
        snapshot: { prefix: "refs/snapshots/source" },
      },
      hook: {
        hookId: 22,
        hookReady: false,
        active: true,
        status: 200,
        latest: { hookId: 11, deliveryId: "duplicate-unpersisted", event: "push", statusCode: 202 },
        latestPush: { hookId: 11, deliveryId: "duplicate-unpersisted", event: "push", statusCode: 202 },
        selectedPush: { hookId: 22, deliveryId: "durable-exact", event: "push", statusCode: 202, repository: "pikasTech/fixture", ref: "refs/heads/main", requestedCommit: head },
        deliverySelectionReason: "committed-durable-proof-for-github-head",
        matchingHookCount: 2,
        matchingHookIds: [11, 22],
        hookTopologyReason: "github-hook-duplicate-exact-url",
      },
      head: { ok: true, sha: head },
      mirror: {
        branchCommit: head,
        snapshotCommit: head,
        snapshotRef: `refs/snapshots/source/${head}`,
      },
      bridgeEvents: [terminalEvent("durable-exact", head)],
      inboxRecords: [committedInbox("durable-exact", head)],
    });
    expect(row.latestPushDelivery.deliveryId).toBe("duplicate-unpersisted");
    expect(row.selectedPushDelivery.deliveryId).toBe("durable-exact");
    expect(row.deliveryId).toBe("durable-exact");
    expect(row.deliverySelectionReason).toBe("committed-durable-proof-for-github-head");
    expect(row.durableInboxCommitted).toBe(true);
    expect(row.bridgeEventStale).toBe(false);
    expect(row.hookReady).toBe(false);
    expect(row.hookTopologyReason).toBe("github-hook-duplicate-exact-url");
  });

  test("MATCH=false is always STALE=true and exact delivery correlation is repo isolated", () => {
    const head = "c".repeat(40);
    const old = "b".repeat(40);
    const row = evaluateRow({
      head,
      branchCommit: old,
      snapshotCommit: old,
      deliveryId: "3830578865896423400",
      statusCode: 202,
      bridgeEvents: [
        { ...terminalEvent("3830578865896423400", head), repo: "other" },
        terminalEvent("3830578865896423400", head),
      ],
    });
    expect(row.deliveryId).toBe("3830578865896423400");
    expect(row.correlatedBridgeEvent.repo).toBe("fixture");
    expect(row.authorityMatches).toBe(false);
    expect(row.bridgeEventStale).toBe(true);
    expect(row.staleReason).toBe("gitea-branch-behind-github");
  });

  test("a correlated terminal event and exact refs prove current authority", () => {
    const head = "d".repeat(40);
    const row = evaluateRow({
      head,
      branchCommit: head,
      snapshotCommit: head,
      deliveryId: "delivery-ok",
      statusCode: 202,
      bridgeEvents: [terminalEvent("delivery-ok", head)],
    });
    expect(row.authorityMatches).toBe(true);
    expect(row.bridgeEventStale).toBe(false);
    expect(row.staleReason).toBeNull();
  });

  test("an out-of-order delivery may prove a newer authority without rolling it back", () => {
    const head = "e".repeat(40);
    const older = "d".repeat(40);
    const event = terminalEvent("delivery-old", older);
    event.authorityCommit = head;
    event.disposition = "superseded-with-immutable-snapshot";
    const row = evaluateRow({
      head,
      branchCommit: head,
      snapshotCommit: head,
      deliveryId: "delivery-old",
      requestedCommit: older,
      statusCode: 202,
      bridgeEvents: [event],
      inboxRecords: [committedInbox("delivery-old", older, head, "superseded-with-immutable-snapshot")],
    });
    expect(row.authorityMatches).toBe(true);
    expect(row.bridgeEventStale).toBe(false);
  });

  test("accepted, processing and failed inbox states never masquerade as committed refs", () => {
    const head = "f".repeat(40);
    for (const state of ["accepted", "processing", "failed"]) {
      const row = evaluateRow({
        head,
        branchCommit: head,
        snapshotCommit: head,
        deliveryId: `delivery-${state}`,
        statusCode: 202,
        bridgeEvents: [],
        inboxRecords: [{ ...committedInbox(`delivery-${state}`, head), state, result: null }],
      });
      expect(row.authorityMatches).toBe(true);
      expect(row.durableInboxState).toBe(state);
      expect(row.bridgeEventStale).toBe(true);
      expect(row.staleReason).toBe(`durable-inbox-${state}-not-committed`);
    }
  });

  test("missing committed watermark or mismatched proof remains stale", () => {
    const head = "a".repeat(40);
    const missing = evaluateRow({
      head,
      branchCommit: head,
      snapshotCommit: head,
      deliveryId: "delivery-missing",
      statusCode: 202,
      bridgeEvents: [],
      inboxRecords: [],
    });
    expect(missing.staleReason).toBe("no-correlated-durable-inbox-record");

    const wrong = evaluateRow({
      head,
      branchCommit: head,
      snapshotCommit: head,
      deliveryId: "delivery-wrong",
      statusCode: 202,
      bridgeEvents: [],
      inboxRecords: [committedInbox("delivery-wrong", "b".repeat(40))],
    });
    expect(wrong.staleReason).toBe("correlated-inbox-proof-head-mismatch");
  });

  test("a delivery older than the persistent journal is marked pre-durable-bootstrap without faking committed", () => {
    const head = "9".repeat(40);
    const row = evaluateRow({
      head,
      branchCommit: head,
      snapshotCommit: head,
      deliveryId: "bootstrap-delivery",
      statusCode: 202,
      deliveredAt: "2026-07-11T06:00:00.000Z",
      journalCreatedAt: "2026-07-11T07:00:00.000Z",
      bridgeEvents: [],
      inboxRecords: [],
    });
    expect(row.authorityMatches).toBe(true);
    expect(row.durableInboxState).toBe("pre-durable-bootstrap");
    expect(row.preDurableBootstrap).toBe(true);
    expect(row.durableInboxCommitted).toBe(false);
    expect(row.bridgeEventStale).toBe(false);
    expect(row.staleReason).toBeNull();
  });
});

function evaluateRow(input: {
  head: string;
  branchCommit: string;
  snapshotCommit: string;
  deliveryId: string;
  statusCode: number;
  bridgeEvents: Array<Record<string, unknown>>;
  inboxRecords?: Array<Record<string, unknown>>;
  deliveredAt?: string;
  journalCreatedAt?: string;
  requestedCommit?: string;
}): Record<string, any> {
  return evaluate({
    action: "evaluate-repository",
    repo: {
      key: "fixture",
      upstream: { repository: "pikasTech/fixture", branch: "main" },
      snapshot: { prefix: "refs/snapshots/source" },
    },
    hook: {
      hookId: 1,
      hookReady: true,
      active: true,
      status: 200,
      latest: { deliveryId: input.deliveryId, event: "push", statusCode: input.statusCode, deliveredAt: input.deliveredAt },
      latestPush: { deliveryId: input.deliveryId, event: "push", statusCode: input.statusCode, deliveredAt: input.deliveredAt, repository: "pikasTech/fixture", ref: "refs/heads/main", requestedCommit: input.requestedCommit ?? input.head },
      selectedPush: { deliveryId: input.deliveryId, event: "push", statusCode: input.statusCode, deliveredAt: input.deliveredAt, repository: "pikasTech/fixture", ref: "refs/heads/main", requestedCommit: input.requestedCommit ?? input.head },
    },
    head: { ok: true, sha: input.head },
    mirror: {
      branchCommit: input.branchCommit,
      snapshotCommit: input.snapshotCommit,
      snapshotRef: `refs/snapshots/source/${input.snapshotCommit}`,
    },
    bridgeEvents: input.bridgeEvents,
    inboxRecords: input.inboxRecords ?? [committedInbox(input.deliveryId, input.head)],
    journal: input.journalCreatedAt === undefined ? undefined : { version: 1, kind: "GiteaGithubSyncDurableInbox", createdAt: input.journalCreatedAt },
  });
}

function committedInbox(deliveryId: string, sourceCommit: string, authorityCommit = sourceCommit, disposition = "atomic-source-authority-committed"): Record<string, unknown> {
  return {
    deliveryId,
    repo: "fixture",
    requestedCommit: sourceCommit,
    state: "committed",
    result: {
      sourceCommit,
      authorityCommit,
      snapshotRef: `refs/snapshots/source/${sourceCommit}`,
      disposition,
    },
  };
}

function terminalEvent(deliveryId: string, sourceCommit: string): Record<string, unknown> {
  return {
    event: "github-to-gitea-sync",
    repo: "fixture",
    deliveryId,
    ok: true,
    terminal: true,
    sourceCommit,
    authorityCommit: sourceCommit,
    disposition: "atomic-source-authority-committed",
  };
}

function evaluate(payload: Record<string, unknown>): Record<string, any> {
  const result = spawnSync("python3", [evaluator], {
    input: JSON.stringify(payload),
    encoding: "utf8",
    env: { ...process.env, PYTHONDONTWRITEBYTECODE: "1" },
  });
  expect(result.status).toBe(0);
  return JSON.parse(result.stdout);
}
