"""Tests for scripts/build_working_leo_authorized_apply_session_plan.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_session_plan as session_plan  # noqa: E402
import working_leo_integrated_packet as integrated_packet  # noqa: E402


def test_session_plan_preserves_packet_order_and_not_executed_boundary():
    plan = session_plan.build_plan()
    apply_ids = [step["packet_id"] for step in plan["apply_steps"]]
    rollback_ids = [step["packet_id"] for step in plan["rollback_steps"]]

    assert plan["mode"] == "authorized_apply_session_plan_not_executed"
    assert plan["production_apply_executed"] is False
    assert apply_ids == [packet["id"] for packet in integrated_packet.PACKETS]
    assert rollback_ids == list(reversed(apply_ids))
    assert "does not execute SQL" in plan["claim_ceiling"]
    assert "does not authorize production apply" in plan["claim_ceiling"]


def test_session_plan_marks_only_apply_and_rollback_as_mutating_and_authorized():
    plan = session_plan.build_plan()

    assert plan["all_apply_steps_require_authorization"] is True
    assert plan["all_rollback_steps_require_authorization"] is True
    assert plan["non_apply_steps_do_not_mutate_db"] is True
    assert all(step["mutates_production_db"] is True for step in plan["apply_steps"])
    assert all(step["requires_authorization"] is True for step in plan["apply_steps"])
    assert all(step["mutates_production_db"] is True for step in plan["rollback_steps"])
    assert all(step["requires_authorization"] is True for step in plan["rollback_steps"])
    for group_name in (
        "pre_apply_validation_steps",
        "preflight_steps",
        "postflight_steps",
        "post_apply_regression_steps",
    ):
        assert all(step["mutates_production_db"] is False for step in plan[group_name])
        assert all(step["requires_authorization"] is False for step in plan[group_name])


def test_session_plan_outputs_every_receipt_path_source():
    plan = session_plan.build_plan()
    sources = plan["receipt_field_sources_after_execution"]

    assert len(sources["preflight_output_paths"]) == 5
    assert len(sources["apply_output_paths"]) == 5
    assert len(sources["postflight_output_paths"]) == 5
    assert len(sources["telegram_or_handler_regression_paths"]) == 5
    assert sources["service_readback"].endswith("post-apply-service-readback.log")
    assert sources["cleanup_readback"].endswith("post-apply-cleanup-readback.log")
    assert len(sources["rollback_packet_paths"]) == 5


def test_session_plan_commands_capture_outputs():
    plan = session_plan.build_plan(output_dir=Path("/tmp/leo-session"))

    all_steps = (
        plan["pre_apply_validation_steps"]
        + plan["preflight_steps"]
        + plan["apply_steps"]
        + plan["postflight_steps"]
        + plan["post_apply_regression_steps"]
        + plan["rollback_steps"]
        + [plan["service_readback_step"], plan["cleanup_readback_step"], plan["receipt_validation_step"]]
    )
    assert all("tee " in step["command"] for step in all_steps)
    assert all(step["output_path"].startswith("/tmp/leo-session") for step in all_steps)


def test_markdown_preserves_authorization_boundary(tmp_path: Path):
    plan = session_plan.build_plan()
    out = tmp_path / "session-plan.md"

    session_plan.write_markdown(out, plan)

    text = out.read_text()
    assert "Production apply executed: `False`" in text
    assert "All apply steps require authorization: `True`" in text
    assert "All rollback steps require authorization: `True`" in text
    assert "Do not run apply commands unless" in text
