/**
 * Cross-language conformance: the TS emitter reproduces the canonical golden
 * (Wave 1.5 / OB-10). Loads the SAME fixture + manifest the Python authority
 * test pins (`src/mgf/common/observability/schema/`) and asserts the TS port
 * emits byte-identical lines and agrees on the key order.
 *
 * Run (Node >= 22):
 *   node --experimental-strip-types --test clients/typescript/conformance.test.ts
 */

import { test } from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { join } from "node:path";

import {
  CORE_KEYS,
  EMIT_ORDER,
  LOG_SCHEMA_VERSION,
  fromJsonlLine,
  toJsonlLine,
  toWire,
} from "./logRecord.ts";

const SCHEMA_DIR = join(
  import.meta.dirname,
  "..", "..", "src", "mgf", "common", "observability", "schema",
);
const fixtureLines = readFileSync(join(SCHEMA_DIR, "log_record_fixture.jsonl"), "utf-8")
  .split("\n")
  .filter((l) => l.length > 0);
const manifest = JSON.parse(
  readFileSync(join(SCHEMA_DIR, "log_record_schema.json"), "utf-8"),
);

test("fixture is non-empty", () => {
  assert.ok(fixtureLines.length >= 6);
});

test("every golden line round-trips byte-identically", () => {
  for (const line of fixtureLines) {
    const rec = fromJsonlLine(line);
    assert.equal(toJsonlLine(rec), line + "\n", `drift on: ${line}`);
  }
});

test("core keys always present on the wire", () => {
  for (const line of fixtureLines) {
    const wire = toWire(fromJsonlLine(line));
    for (const key of CORE_KEYS) {
      assert.ok(key in wire, `core key ${key} missing`);
    }
  }
});

test("emit order + core + version agree with the manifest", () => {
  assert.deepEqual([...EMIT_ORDER], manifest.emit_order);
  assert.deepEqual([...CORE_KEYS], manifest.core);
  assert.equal(LOG_SCHEMA_VERSION, manifest.schema_version);
});

test("forward-compat: unknown key preserved through a round-trip", () => {
  const rec = fromJsonlLine(fixtureLines[fixtureLines.length - 1]);
  assert.equal(rec.extra?.severity_text, "notice");
  assert.ok(toJsonlLine(rec).includes('"severity_text":"notice"'));
});
