"""Tests for scripts/build_working_leo_production_apply_authorization_packet.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_production_apply_authorization_packet as packet  # noqa: E402


def _force_direct_claim_score_pass(monkeypatch):
    real_load = packet._load_json

    def fake_load(path: Path):
        data = real_load(path)
        if path == packet.DEFAULT_DIRECT_CLAIM_SCORE:
            data = dict(data)
            data["score"] = dict(data["score"])
            data["score"].update({"pass": True, "passes": 6, "failures": []})
        return data

    monkeypatch.setattr(packet, "_load_json", fake_load)


def test_authorization_packet_is_ready_but_not_executed(monkeypatch):
    _force_direct_claim_score_pass(monkeypatch)
    report = packet.build_packet(git_sha="45bec0e")

    assert report["mode"] == "production_apply_authorization_packet_not_executed"
    assert report["production_apply_executed"] is False
    assert report["production_apply_authorization_present"] is False
    assert report["ready_to_request_authorization"] is True
    assert report["authorization_gate_status"] == "ready_to_request_explicit_authorization"
    assert all(report["checks"].values())
    assert report["packet_generation_git_sha"] == "45bec0e"
    assert report["authorization_commit_sha_rule"] == "Use the fresh deployed SHA read back immediately before apply."
    assert report["authorization_scope"]["telegram_visible_post_authorized"] is False
    assert report["authorization_scope"]["gcp_parity_in_scope"] is False
    assert report["authorization_scope"]["apply_order"] == [
        "mapped-rich-base",
        "cross-surface-anchor",
        "rio-strategy-context",
        "governance-concept-schema",
        "helmer-7powers",
    ]
    assert "I authorize production DB apply" in report["explicit_operator_authorization_text_template"]
    assert "<DEPLOYED_SHA_READBACK>" in report["explicit_operator_authorization_text_template"]
    assert "do not post Telegram-visible messages unless separately authorized" in report[
        "explicit_operator_authorization_text_template"
    ]
    assert "re-read the deployed SHA" in report["clear_CTA"]
    assert "does not run SQL" in report["claim_ceiling"]
    assert "does not mutate production" in report["claim_ceiling"]


def test_authorization_packet_markdown_preserves_clear_cta(tmp_path: Path, monkeypatch):
    _force_direct_claim_score_pass(monkeypatch)
    report = packet.build_packet(git_sha="45bec0e")
    out = tmp_path / "authorization.md"

    packet.write_markdown(out, report)

    text = out.read_text(encoding="utf-8")
    assert "Working Leo Production Apply Authorization Packet" in text
    assert "Ready to request authorization: `True`" in text
    assert "Production apply executed: `False`" in text
    assert "Packet generation git SHA: `45bec0e`" in text
    assert "Explicit Operator Authorization Text" in text
    assert "Clear CTA" in text
    assert "Do Not Run Without" in text
    assert "I authorize production DB apply" in text


def test_authorization_packet_not_ready_when_direct_claim_score_fails(monkeypatch):
    real_load = packet._load_json

    def fake_load(path: Path):
        data = real_load(path)
        if path == packet.DEFAULT_DIRECT_CLAIM_SCORE:
            data = dict(data)
            data["score"] = dict(data["score"])
            data["score"]["pass"] = False
            data["score"]["passes"] = 5
            data["score"]["failures"] = [{"prompt_id": "DC-06"}]
        return data

    monkeypatch.setattr(packet, "_load_json", fake_load)

    report = packet.build_packet(git_sha="45bec0e")

    assert report["ready_to_request_authorization"] is False
    assert report["authorization_gate_status"] == "not_ready"
    assert report["checks"]["direct_claim_score_passed"] is False
