import assert from "node:assert/strict";
import { test } from "bun:test";

import type { WorkbenchRawHwlabEventWindowCapability } from "@/config/runtime";
import { appendRawHwlabIngressFrame, createRawHwlabIngressState } from "./workbench-raw-hwlab-ingress";

const capability: WorkbenchRawHwlabEventWindowCapability = {
  enabled: true,
  maxEntries: 2,
  maxRetainedBytes: 32
};

test("raw HWLAB ingress retains complete frames in arrival order and exposes decode rejection", () => {
  let state = createRawHwlabIngressState("ses_raw");
  const roomyCapability = { ...capability, maxRetainedBytes: 128 };
  state = appendRawHwlabIngressFrame(state, frame('{"schema":"hwlab.event.v1"}', "accepted"), roomyCapability, () => 1);
  state = appendRawHwlabIngressFrame(state, frame("not-json", "invalid-json"), roomyCapability, () => 2);

  assert.equal(state.receivedCount, 2);
  assert.equal(state.decodedCount, 1);
  assert.equal(state.rejectedCount, 1);
  assert.deepEqual(state.rows.map((row) => [row.arrivalSeq, row.rawText, row.decodeStatus]), [
    [1, '{"schema":"hwlab.event.v1"}', "accepted"],
    [2, "not-json", "invalid-json"]
  ]);
});

test("raw HWLAB ingress evicts whole envelopes by YAML-owned entry and byte capacities", () => {
  let state = createRawHwlabIngressState("ses_raw");
  state = appendRawHwlabIngressFrame(state, frame("1234567890", "accepted"), capability, () => 1);
  state = appendRawHwlabIngressFrame(state, frame("abcdefghij", "accepted"), capability, () => 2);
  state = appendRawHwlabIngressFrame(state, frame("ABCDEFGHIJ", "accepted"), capability, () => 3);

  assert.equal(state.receivedCount, 3);
  assert.equal(state.evictedCount, 1);
  assert.equal(state.retainedBytes, 20);
  assert.deepEqual(state.rows.map((row) => row.rawText), ["abcdefghij", "ABCDEFGHIJ"]);

  const oversized = appendRawHwlabIngressFrame(state, frame("x".repeat(40), "accepted"), capability, () => 4);
  assert.equal(oversized.receivedCount, 4);
  assert.equal(oversized.evictedCount, 4);
  assert.equal(oversized.retainedBytes, 0);
  assert.deepEqual(oversized.rows, []);
});

test("raw HWLAB ingress ignores non-product events and disabled capability", () => {
  const state = createRawHwlabIngressState("ses_raw");
  const connected = appendRawHwlabIngressFrame(state, { eventName: "workbench.connected", rawText: "{}", decodeStatus: "accepted" }, capability);
  const disabled = appendRawHwlabIngressFrame(state, frame("{}", "accepted"), { ...capability, enabled: false });
  assert.equal(connected, state);
  assert.equal(disabled, state);
});

function frame(rawText: string, decodeStatus: "accepted" | "invalid-json" | "not-object") {
  return { eventName: "hwlab.event.v1", rawText, decodeStatus } as const;
}
