import assert from "node:assert/strict";
import test from "node:test";

import { buildRelationWindow, mergeMonotonicBoolean, normalizeRunStatus, type AgentObserverRun } from "../src/stores/agent-observer.ts";

test("Agent observer keeps generic event status outside Run authority", () => {
  assert.equal(normalizeRunStatus(null, null), "unknown");
  assert.equal(normalizeRunStatus(null, null, "running"), "running");
  assert.equal(normalizeRunStatus("queued", null, "unknown"), "queued");
  assert.equal(normalizeRunStatus(null, "cancelled", "running"), "canceled");
});

test("Agent observer final authority is monotonic once true", () => {
  assert.equal(mergeMonotonicBoolean(null, false), false);
  assert.equal(mergeMonotonicBoolean(false, null), false);
  assert.equal(mergeMonotonicBoolean(false, true), true);
  assert.equal(mergeMonotonicBoolean(true, false), true);
  assert.equal(mergeMonotonicBoolean(true, null), true);
});

test("Agent observer relation tree consumes the YAML node limit", () => {
  const runs = [observerRun("run_1"), observerRun("run_2"), observerRun("run_3")];
  const window = buildRelationWindow(runs, null, new Set(), new Set(), 3);
  assert.equal(window.limited, true);
  assert.equal(window.nodeCount, 3);
  assert.equal(window.omittedRunCount, 1);
  assert.equal(window.rows.length, 3);
});

test("Agent observer relation tree keeps a stable order across live activity reordering", () => {
  const first = buildRelationWindow([observerRun("run_2"), observerRun("run_1")], null, new Set(), new Set(), 10);
  const second = buildRelationWindow([observerRun("run_1"), observerRun("run_2")], null, new Set(), new Set(), 10);
  assert.deepEqual(first.rows.map((row) => row.id), second.rows.map((row) => row.id));
});

function observerRun(id: string): AgentObserverRun {
  return {
    id,
    title: null,
    taskId: null,
    taskStatus: null,
    commandId: null,
    attemptId: null,
    attemptStatus: null,
    runnerId: null,
    runnerCapacityUsed: null,
    runnerCapacityTotal: null,
    nodeId: null,
    lane: null,
    sessionId: null,
    traceId: null,
    projectId: null,
    workspace: null,
    backend: null,
    providerId: null,
    runStatus: "unknown",
    commandState: null,
    commandType: null,
    phase: "event",
    result: null,
    replyAuthority: null,
    final: null,
    errorCode: null,
    lastMessage: null,
    startedAt: null,
    finishedAt: null,
    updatedAt: null,
    lastSourceSeq: null,
    eventIds: [],
    changedAtMs: 0
  };
}
