from __future__ import annotations

import json
from pathlib import Path

from scripts import build_telegram_visible_unseen_chain_packet as packet


def test_packet_binds_handler_receipt_and_preserves_exact_messages() -> None:
    data = packet.build_packet(git_sha="a" * 40)

    assert data["schema"] == packet.SCHEMA
    assert data["ready_to_request_action_time_authorization"] is True
    assert data["telegram_visible_messages_sent"] is False
    assert data["telegram_visible_message_authorization_present"] is False
    assert data["mutates_db"] is False
    assert data["target"]["chat_label"] == "Leo"
    assert data["target"]["chat_id"] == "-5146042086"
    assert data["target"]["allowed_transport"] == "authenticated_chrome_telegram_ui"
    assert [item["message"] for item in data["exact_messages"]] == [item["message"] for item in packet.unseen.PROMPTS]
    assert [item["sequence"] for item in data["exact_messages"]] == [1, 2, 3]
    assert all(len(item["message_sha256"]) == 64 for item in data["exact_messages"])
    assert data["handler_receipt_binding"]["sha256"] == packet._sha256_file(packet.DEFAULT_HANDLER_RECEIPT)
    assert data["tooling_binding"] == packet.tooling_binding()
    assert data["manifest_binding"] == packet.manifest_binding()
    assert data["manifest_binding"]["path"] == "ops/postgres_parity_manifest.sql"
    assert data["manifest_binding"]["execution_contract"]["effective_role"] == "pg_read_all_data"
    assert data["manifest_binding"]["execution_contract"]["transaction_read_only"] == "on"
    assert data["protocol"]["manifest_binding"] == data["manifest_binding"]
    assert data["operator_context"]["codex_thread_id"] == packet.DEFAULT_CODEX_THREAD_ID
    assert data["protocol"]["operator_context"] == data["operator_context"]
    assert packet._canonical_sha256(data["protocol"]) == data["protocol_sha256"]
    assert all(data["checks"].values())


def test_action_time_authorization_contains_destination_transport_and_full_messages() -> None:
    data = packet.build_packet(git_sha="a" * 40)
    authorization = data["explicit_operator_authorization_text"]

    assert "Telegram group Leo (chat ID -5146042086)" in authorization
    assert "already-authenticated Chrome Telegram UI" in authorization
    assert "do not use the Bot API" in authorization
    assert "Codex rollout's user-authorization and Chrome tool events" in authorization
    assert "no additional messages" in authorization
    for item in data["exact_messages"]:
        assert item["prompt_id"] in authorization
        assert json.dumps(item["message"], ensure_ascii=True) in authorization


def test_packet_fails_closed_when_handler_receipt_no_longer_passes(tmp_path: Path) -> None:
    receipt = json.loads(packet.DEFAULT_HANDLER_RECEIPT.read_text(encoding="utf-8"))
    receipt["status"] = "fail"
    receipt_path = tmp_path / "handler.json"
    receipt_path.write_text(json.dumps(receipt), encoding="utf-8")

    data = packet.build_packet(handler_receipt_path=receipt_path, git_sha="a" * 40)

    assert data["ready_to_request_action_time_authorization"] is False
    assert data["authorization_gate_status"] == "not_ready"
    assert data["checks"]["handler_receipt_passed"] is False


def test_markdown_retains_exact_cta_and_no_send_ceiling(tmp_path: Path) -> None:
    data = packet.build_packet(git_sha="a" * 40)
    out = tmp_path / "packet.md"

    packet.write_markdown(out, data)

    text = out.read_text(encoding="utf-8")
    assert "Telegram-Visible Unseen Chain Authorization Packet" in text
    assert "Telegram-visible messages sent: `False`" in text
    assert "Exact Action-Time Authorization" in text
    assert data["exact_messages"][2]["message"] in text
