"use strict";

const test = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");

const repositoryRoot = path.resolve(__dirname, "..", "..");
const bridge = fs.readFileSync(
  path.join(repositoryRoot, "MainWindow.OperatorCatalogs.cs"),
  "utf8");

test("theme, expert, schema and next-code reads use entity-operation lanes", () => {
  assert.match(bridge,
    /Dictionary<string, OperatorCatalogReadRequest> _operatorCatalogReadLanes/);
  assert.match(bridge,
    /new OperatorCatalogReadRequest\(\s*\$"\{entity\}:\{operation\}"/s);
  assert.match(bridge, /_operatorCatalogReadLanes\[request\.Lane\] = request/);
  assert.match(bridge, /_operatorCatalogReadLanes\.TryGetValue\(request\.Lane/);
  assert.doesNotMatch(bridge, /_operatorCatalogReadCancellation/);
  assert.match(bridge, /await _databaseActivityGate\.WaitAsync\(requestToken\)/);
  assert.match(bridge, /OperatorCatalogBridgeReply/);
});

test("each catalog request publishes at most one terminal result or error", () => {
  assert.match(bridge, /CancelRequest\(superseded\.Cancellation\)/);
  assert.match(bridge, /superseded\?\.TryComplete\(\)/);
  assert.match(bridge, /"CANCELLED"/);
  assert.match(bridge, /newer request replaced it/);
  assert.match(bridge,
    /Interlocked\.CompareExchange\(ref _terminalState, 1, 0\) == 0/);
  assert.match(bridge,
    /TryCompleteOperatorCatalogReadIfCurrent\(request\)[\s\S]*PostMessage\(reply\.MessageType/s);
  assert.match(bridge,
    /ReferenceEquals\(current, request\) &&[\s\S]*request\.TryComplete\(\)/s);
  assert.match(bridge,
    /PostOperatorCatalogReadErrorIfCurrent\([\s\S]*!TryCompleteOperatorCatalogReadIfCurrent\(request\)/s);
});

test("browser invalidation, playout priority and shutdown cover every active lane", () => {
  assert.match(bridge, /private OperatorCatalogReadRequest\[\] SnapshotOperatorCatalogReads/);
  assert.ok((bridge.match(/SnapshotOperatorCatalogReads\(clear: true\)/g) || []).length >= 2);
  assert.match(bridge,
    /CancelOperatorCatalogReadsForPlayout\(\)[\s\S]*SnapshotOperatorCatalogReads\(clear: false\)/s);
});

test("write safety gate and process quarantine remain intact", () => {
  assert.match(bridge,
    /CanStartOperatorMutation\(IsOperatorCatalogWriteQuarantined\(\)\)/);
  assert.match(bridge, /LatchOperatorCatalogWriteQuarantine/);
  assert.match(bridge, /Interlocked\.Exchange\(ref _operatorCatalogWriteCancellation, null\)/);
  assert.doesNotMatch(bridge, /operationBody\(requestToken\)\.ConfigureAwait\(false\)/);
});
