"""compare.py flags injected diffs, passes allowlisted ones, and the
shipped allowlist covers exactly the informational meta section."""

import json
from pathlib import Path

from compare import DEFAULT_ALLOWLIST, load_allowlist, main, run_compare

FIXTURES = Path(__file__).parent / "fixtures"
OLD = json.loads((FIXTURES / "old.json").read_text(encoding="utf-8"))
NEW = json.loads((FIXTURES / "new.json").read_text(encoding="utf-8"))
SHIPPED = load_allowlist(DEFAULT_ALLOWLIST)

INJECTED = {
    "months/2026-03/11111111-1111-1111-1111-111111111111/billout/CAD",
    "months/2026-03/11111111-1111-1111-1111-111111111111/billout_adjusted/CAD",
    "invoices/aaaaaaaa-0000-0000-0000-000000000001/entry_count",
    "invoices/aaaaaaaa-0000-0000-0000-000000000001/attached_entry_ids",
}


def test_injected_diff_is_red_and_meta_is_not():
    report = run_compare(OLD, NEW, SHIPPED)
    assert not report.ok
    assert {d.path for d in report.failures} == INJECTED
    # the shipped allowlist absorbs the meta-only differences, nothing else
    allowed = {d.path for d in report.diffs if d.allowed}
    assert allowed and all(p.startswith("meta/") for p in allowed)

    # the id-set diff reads as removed/added, not an index cascade
    ids_diff = next(d for d in report.failures if d.path.endswith("attached_entry_ids"))
    assert ids_diff.kind == "changed"
    assert "cccccccc-0000-0000-0000-000000000002" in ids_diff.old
    assert "cccccccc-0000-0000-0000-000000000002" not in ids_diff.new


def test_allowlisted_diff_passes_and_stale_entries_are_reported(tmp_path, capsys):
    allowlist = SHIPPED + [
        {"path": p, "reason": "test: injected, accepted"} for p in INJECTED
    ] + [{"path": "invoices/never-matches/*", "reason": "test: stale"}]
    report = run_compare(OLD, NEW, allowlist)
    assert report.ok
    assert "invoices/never-matches/*" in report.stale_patterns
    # any other stale patterns must be the SHIPPED straggler pins
    # (judgment #22 — pinned to the real Legacy-transfers invoice id, so
    # they never match these fixture docs)
    assert set(report.stale_patterns) - {"invoices/never-matches/*"} == {
        e["path"] for e in SHIPPED if e["path"].startswith("invoices/")
    }

    # end to end through the CLI: exit 0 green with the allowlist, 1 without
    allowlist_file = tmp_path / "allowlist.json"
    allowlist_file.write_text(json.dumps({"entries": allowlist}), encoding="utf-8")
    argv = [str(FIXTURES / "old.json"), str(FIXTURES / "new.json")]
    assert main(argv + ["--allowlist", str(allowlist_file)]) == 0
    assert "GREEN" in capsys.readouterr().out
    assert main(argv) == 1
    assert "RED" in capsys.readouterr().out
