"""Authority/pin tests for the cross-language ``LogRecord`` contract (OB-10).

mgf-common is the source of truth for the wire shape; the Zig/TS reference
emitters under ``clients/`` pin against the golden artifacts these tests
guard. The guarantees here:

* the checked-in goldens (fixture + manifest) are exactly what the canonical
  source produces — regenerate with ``tools/gen_log_record_schema.py`` if these
  fail (no silent drift);
* every fixture line round-trips byte-for-byte through the Python reader/writer
  (so the fixture is a faithful Python-emit golden the other languages match);
* the manifest cannot drift from the live dataclass / parser (adding a typed
  field forces a manifest + ``LOG_SCHEMA_VERSION`` update — OB-09 rule 2);
* forward-compat: an unknown future key survives a round-trip (OB-09 rule 3).
"""

from __future__ import annotations

from dataclasses import fields as dataclass_fields

from mgf.common.observability import LogRecord, log_schema_manifest
from mgf.common.observability._conformance import (
    CORE_KEYS,
    EMIT_ORDER,
    fixture_path,
    render_fixture,
    render_schema_json,
    schema_path,
)
from mgf.common.observability.log_record import (
    _KNOWN_TOP_LEVEL_KEYS,
    LOG_SCHEMA_VERSION,
)


class TestGoldensInSync:
    """The checked-in/packaged goldens match the canonical source exactly."""

    def test_fixture_file_matches_source(self) -> None:
        on_disk = fixture_path().read_text(encoding="utf-8")
        assert on_disk == render_fixture(), (
            "log_record_fixture.jsonl is stale — run `uv run python tools/gen_log_record_schema.py`"
        )

    def test_schema_file_matches_source(self) -> None:
        on_disk = schema_path().read_text(encoding="utf-8")
        assert on_disk == render_schema_json(), (
            "log_record_schema.json is stale — run `uv run python tools/gen_log_record_schema.py`"
        )


class TestFixtureRoundTrips:
    """Every golden line parses + re-emits byte-identically (the cross-lang pin)."""

    def test_every_line_round_trips(self) -> None:
        lines = fixture_path().read_text(encoding="utf-8").splitlines()
        assert lines, "fixture is empty"
        for line in lines:
            rec = LogRecord.from_jsonl_line(line)
            assert rec.to_jsonl_line().rstrip("\n") == line

    def test_core_keys_always_present(self) -> None:
        for line in fixture_path().read_text(encoding="utf-8").splitlines():
            wire = LogRecord.from_jsonl_line(line).to_dict()
            for key in CORE_KEYS:
                assert key in wire, f"core key {key!r} missing from {line}"

    def test_forward_compat_unknown_key_preserved(self) -> None:
        # The last fixture record carries `severity_text`, a key this schema
        # version does not define; it must survive the round-trip (OB-09 rule 3).
        lines = fixture_path().read_text(encoding="utf-8").splitlines()
        rec = LogRecord.from_jsonl_line(lines[-1])
        assert rec.extra.get("severity_text") == "notice"
        assert '"severity_text":"notice"' in rec.to_jsonl_line()


class TestManifestPinnedToSchema:
    """The language-neutral manifest cannot drift from the live Python schema."""

    def test_schema_version_pinned(self) -> None:
        manifest = log_schema_manifest()
        assert manifest["schema_version"] == LOG_SCHEMA_VERSION == "1.0.0"

    def test_manifest_fields_match_parser_known_keys(self) -> None:
        # Every key the manifest describes is a key the parser recognises, and
        # vice-versa — so a new typed field can't be added on one side only.
        assert set(EMIT_ORDER) == set(_KNOWN_TOP_LEVEL_KEYS)
        assert set(log_schema_manifest()["fields"]) == set(_KNOWN_TOP_LEVEL_KEYS)

    def test_manifest_fields_match_dataclass(self) -> None:
        # The dataclass's typed fields (minus the `extra` pass-through bucket,
        # which is not a wire key of its own) must equal the manifest field set.
        # Adding a field to LogRecord without updating _conformance fails here.
        live = {f.name for f in dataclass_fields(LogRecord)} - {"extra"}
        assert live == set(EMIT_ORDER)

    def test_core_is_prefix_of_emit_order(self) -> None:
        assert EMIT_ORDER[: len(CORE_KEYS)] == CORE_KEYS

    def test_manifest_emit_order_is_complete(self) -> None:
        manifest = log_schema_manifest()
        assert manifest["emit_order"] == list(EMIT_ORDER)
        assert manifest["core"] == list(CORE_KEYS)
