import json

from scripts.ops import check_production_version_truth as guard


def _report(production_version="V10.725", local_version="V10.725", head_version="V10.725"):
    return {
        "policy": "production_health_is_latest_version_truth",
        "health_url": "https://mo.wooo.work/health",
        "production": {
            "status": "healthy",
            "database": "postgresql",
            "version": production_version,
        },
        "local": {
            "branch": "main",
            "head": "f3e412cd211f5e4601204b256aeb95eae073b441",
            "config_version": local_version,
            "head_config_version": head_version,
        },
        "origin_main": {
            "head": "f3e412cd211f5e4601204b256aeb95eae073b441",
            "matches_local_head": True,
        },
    }


def test_parse_config_version():
    assert guard.parse_config_version('SYSTEM_VERSION = "V10.725"\n') == "V10.725"


def test_production_version_truth_passes_when_everything_matches():
    ok, errors = guard.evaluate(_report(), allow_local_version_drift=False)

    assert ok is True
    assert errors == []


def test_working_tree_version_drift_blocks_by_default():
    ok, errors = guard.evaluate(_report(local_version="V10.726"), allow_local_version_drift=False)

    assert ok is False
    assert any("working-tree config.py version differs from production" in error for error in errors)


def test_explicit_release_prep_can_allow_working_tree_version_drift():
    ok, errors = guard.evaluate(_report(local_version="V10.726"), allow_local_version_drift=True)

    assert ok is True
    assert errors == []


def test_head_version_must_still_match_production():
    ok, errors = guard.evaluate(_report(head_version="V10.724"), allow_local_version_drift=True)

    assert ok is False
    assert any("HEAD config.py version differs from production" in error for error in errors)


def test_json_output_contains_production_truth_policy(monkeypatch, capsys):
    monkeypatch.setattr(guard, "build_report", lambda health_url, timeout: _report())

    exit_code = guard.main(["--json"])
    payload = json.loads(capsys.readouterr().out)

    assert exit_code == 0
    assert payload["policy"] == "production_health_is_latest_version_truth"
    assert payload["production"]["version"] == "V10.725"
