"""Tests for scripts/build_telegram_visible_direct_claim_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_telegram_visible_direct_claim_authorization_packet as packet  # noqa: E402
import working_leo_open_ended_benchmark as benchmark  # noqa: E402


def _force_handler_score_pass(monkeypatch):
    real_load = packet._load_json

    def fake_load(path: Path):
        data = real_load(path)
        if path == packet.DEFAULT_HANDLER_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_packet_ready_but_never_sends_messages(monkeypatch):
    _force_handler_score_pass(monkeypatch)
    report = packet.build_packet(git_sha="262ddb9")

    assert report["mode"] == "telegram_visible_direct_claim_authorization_packet_not_sent"
    assert report["ready_to_request_authorization"] is True
    assert report["authorization_gate_status"] == "ready_to_request_explicit_authorization"
    assert report["telegram_visible_messages_sent"] is False
    assert report["telegram_visible_message_authorization_present"] is False
    assert report["production_apply_executed"] is False
    assert report["production_apply_authorization_present"] is False
    assert report["mutates_db"] is False
    assert report["target"]["chat_id"] == "-5146042086"
    assert report["target"]["chat_label"] == "Leo"
    assert report["target"]["expected_prompt_ids"] == ["DC-01", "DC-02", "DC-03", "DC-04", "DC-05", "DC-06"]
    assert all(report["checks"].values())
    assert "I authorize a Telegram-visible read-only direct-claim benchmark" in report[
        "explicit_operator_authorization_text"
    ]
    assert "Do not run production DB apply" in report["explicit_operator_authorization_text"]
    assert report["expected_proof_paths_after_authorized_run"]["capture_receipt_json"] == str(
        packet.DEFAULT_CAPTURE_RECEIPT
    )
    assert report["expected_proof_paths_after_authorized_run"]["capture_results_json"] == str(
        packet.DEFAULT_CAPTURE_RESULTS
    )
    assert "does not send Telegram messages" in report["claim_ceiling"]


def test_packet_preserves_raw_no_context_dc_messages():
    report = packet.build_packet(git_sha="262ddb9")

    packet_messages = [item["message"] for item in report["exact_messages"]]
    catalog_messages = [item["message"] for item in benchmark.M3TAVERSAL_DIRECT_CLAIM_FOLLOWUP_SCENARIOS]

    assert packet_messages == catalog_messages
    assert packet_messages[0] == "Did we actually update the knowledge base, or is it still just proposals?"
    assert packet_messages[1] == "Is Helmer's 7 Powers in Leo now?"
    assert "read-only benchmark" not in packet_messages[0].lower()
    assert "Do not change the KB" not in "\n".join(packet_messages)


def test_packet_markdown_contains_exact_messages_and_cta(tmp_path: Path):
    report = packet.build_packet(git_sha="262ddb9")
    out = tmp_path / "telegram-dc-auth.md"

    packet.write_markdown(out, report)

    text = out.read_text(encoding="utf-8")
    assert "Telegram-Visible Direct-Claim Authorization Packet" in text
    assert "Telegram-visible messages sent: `False`" in text
    assert "Did we actually update the knowledge base" in text
    assert "If we changed SOUL.md" in text
    assert "Explicit Operator Authorization Text" in text
    assert "Do Not Run Without" in text


def test_packet_not_ready_when_handler_score_fails(monkeypatch):
    real_load = packet._load_json

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

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

    report = packet.build_packet(git_sha="262ddb9")

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