import json
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]


def test_controller_provenance_is_current_and_gate_b_legacy_is_explicit():
    config = json.loads((ROOT / "config/gal_fingerprint_i_registered_specification.json").read_text())
    provenance = config["controller_provenance"]
    assert config["version"] == "0.2.2"
    assert provenance["controller_version"] == "0.2.2"
    assert provenance["runtime_package_version"] == "0.2.2"
    assert provenance["measurement_kernel_version"] == "1.0.4"
    assert provenance["gate_b_successful_runtime"] == "0.1.3"
    assert provenance["gate_b_legacy_exported_controller_label"] == "0.1.0"
    exports = (ROOT / "gal_fingerprint_i/exports.py").read_text(encoding="utf-8")
    assert '"controller_version": execution_controller_version' in exports
    assert '"runtime_package_version": execution_controller_version' in exports
    assert '"finalizer_version": CHAMBER_VERSION' in exports


def test_gate_b_provenance_has_embedded_fallback(monkeypatch, tmp_path):
    from gal_fingerprint_i import evidence

    monkeypatch.setattr(evidence, "BUNDLED_DATA", tmp_path / "missing_registered_data")
    text = evidence.gate_b_provenance_amendment()
    assert "Successful runtime package" in text
    assert "GAL-FINGERPRINT-I Chamber v0.1.3" in text
    assert "Rerun required" in text


def test_gate_b_provenance_fallback_is_written(monkeypatch, tmp_path):
    from gal_fingerprint_i import evidence

    monkeypatch.setattr(evidence, "BUNDLED_DATA", tmp_path / "missing_registered_data")
    monkeypatch.setattr(evidence, "active_roots", lambda: {"analysis_root": tmp_path / "analysis"})
    path = evidence.write_gate_b_provenance_amendment()
    assert path.is_file()
    assert path.read_text(encoding="utf-8") == evidence.gate_b_provenance_amendment()
