"""Tests for scripts/build_working_leo_authorized_apply_runbook.py."""

from __future__ import annotations

import sys
from pathlib import Path

REPO_ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(REPO_ROOT / "scripts"))

import build_working_leo_authorized_apply_runbook as runbook  # noqa: E402
import working_leo_integrated_packet as integrated_packet  # noqa: E402


def test_build_runbook_is_ready_not_executed():
    report = runbook.build_runbook()
    apply_ids = [entry["packet_id"] for entry in report["phases"]["apply_order"]]
    rollback_ids = [entry["packet_id"] for entry in report["phases"]["rollback_order"]]

    assert report["status"] == "ready_not_executed"
    assert report["ready_for_authorized_operator"] is True
    assert report["production_apply_executed"] is False
    assert report["production_apply_authorization_present"] is False
    assert all(report["checks"].values())
    assert apply_ids == [packet["id"] for packet in integrated_packet.PACKETS]
    assert rollback_ids == list(reversed(apply_ids))
    assert len(report["phases"]["preflight_order"]) == 5
    assert len(report["phases"]["apply_order"]) == 5
    assert len(report["phases"]["postflight_order"]) == 5
    assert len(report["phases"]["rollback_order"]) == 5
    assert report["operator_environment"]["runbook_generation_runs_sql"] is False
    assert report["operator_environment"]["operator_commands_run_sql_if_executed"] is True
    assert "does not execute SQL" in report["claim_ceiling"]
    assert report["checks"]["post_apply_regression_commands_present"] is True
    assert report["checks"]["pre_apply_validation_commands_present"] is True
    assert report["checks"]["production_apply_receipt_schema_present"] is True
    assert {item["id"] for item in report["pre_apply_validation_commands"]} == {
        "readonly_production_preflight_collector",
    }
    assert all(item["mutates_production_db"] is False for item in report["pre_apply_validation_commands"])
    assert all(item["applies_production_packet"] is False for item in report["pre_apply_validation_commands"])
    assert {item["id"] for item in report["post_apply_regression_commands"]} == {
        "direct_claim_handler_suite",
        "direct_claim_strict_score",
        "focused_local_regression_tests",
        "gateway_service_readback",
        "production_receipt_validator",
    }
    assert all(item["mutates_production_db"] is False for item in report["post_apply_regression_commands"])
    assert all(item["posts_to_telegram"] is False for item in report["post_apply_regression_commands"])
    assert "explicit_authorization_record" in report["production_apply_receipt_required_fields"]
    assert "actual_after_apply_counts" in report["production_apply_receipt_required_fields"]
    assert "direct_claim_score_path" in report["production_apply_receipt_required_fields"]
    assert "rollback_packet_paths" in report["production_apply_receipt_required_fields"]

    for phase in report["phases"].values():
        for entry in phase:
            assert entry["ok"] is True
            assert 'psql "$TELEO_DATABASE_URL"' in entry["command_template"]


def test_write_markdown_includes_authorization_boundary(tmp_path: Path):
    report = runbook.build_runbook()
    out = tmp_path / "runbook.md"

    runbook.write_markdown(out, report)

    text = out.read_text()
    assert "Working Leo Authorized Apply Runbook" in text
    assert "Production apply executed: `False`" in text
    assert "Production apply authorization present: `False`" in text
    assert "Do not run apply commands unless" in text
    assert 'psql "$TELEO_DATABASE_URL"' in text
    assert "Pre-Apply Validation Commands" in text
    assert "collect_working_leo_production_preflight.py --execute" in text
    assert "Post-Apply Regression Commands" in text
    assert "scripts/run_leo_direct_claim_handler_suite.py" in text
    assert "direct_claim_score_path" in text
    assert "mutates production DB: `False`" in text


def test_runbook_not_ready_when_readiness_is_not_ready(monkeypatch):
    real_readiness = runbook.readiness.build_readiness()
    failed_readiness = dict(real_readiness)
    failed_readiness["ready_for_authorized_production_apply_packet"] = False

    monkeypatch.setattr(runbook.readiness, "build_readiness", lambda report_dir: failed_readiness)

    report = runbook.build_runbook()

    assert report["status"] == "not_ready"
    assert report["ready_for_authorized_operator"] is False
    assert report["checks"]["readiness_passes"] is False


def test_runbook_not_ready_when_readiness_says_production_executed(monkeypatch):
    real_readiness = runbook.readiness.build_readiness()
    executed_readiness = dict(real_readiness)
    executed_readiness["production_apply_executed"] = True
    executed_readiness["production_apply_authorization_present"] = True

    monkeypatch.setattr(runbook.readiness, "build_readiness", lambda report_dir: executed_readiness)

    report = runbook.build_runbook()

    assert report["status"] == "not_ready"
    assert report["production_apply_executed"] is True
    assert report["production_apply_authorization_present"] is True
    assert report["checks"]["readiness_says_not_executed"] is False
    assert report["checks"]["readiness_says_not_authorized"] is False
