"""Instrument-validation gate re-confirmation — offline items (2-6).

Item 1 (live 3-hop e2e) needs a docker daemon + sor-hop image, so it is exercised
separately by the forwarder e2e test; here we drive the gate with ``allow_live=
False`` and assert every *offline* item is green and the report is write-once.
"""

import json

from cmd_chat.sor import gate


def test_offline_gate_items_all_green(tmp_path):
    report = gate.run_gate(tmp_path, allow_live=False)
    assert report["offline_items_green"] is True
    by_n = {it["n"]: it for it in report["items"]}
    for n in (2, 3, 4, 5, 6):
        assert by_n[n]["status"] == "green", (n, by_n[n])
    # With live disabled, item 1 is 'unavailable' (not a red failure).
    assert by_n[1]["status"] == "unavailable"
    assert report["all_green"] is False  # item 1 not confirmed in this offline run


def test_gate_report_is_write_once(tmp_path):
    gate.run_gate(tmp_path, allow_live=False)
    path = tmp_path / "gate-report.json"
    first = path.read_text()
    gate.run_gate(tmp_path, allow_live=False)  # second call must not overwrite
    assert path.read_text() == first
    doc = json.loads(first)
    assert doc["schema"] == "sor-gate-report/1"


def test_item5_isolation_refuses_local_accepts_docker(tmp_path):
    report = gate.run_gate(tmp_path, allow_live=False)
    ev = next(it["evidence"] for it in report["items"] if it["n"] == 5)
    assert ev["refused_local"] and ev["refused_unknown"] and ev["accepts_docker"]


def test_item4_entropy_is_exact_log2n(tmp_path):
    report = gate.run_gate(tmp_path, allow_live=False)
    ev = next(it["evidence"] for it in report["items"] if it["n"] == 4)
    assert all(c["exact"] for c in ev["checks"])
