from __future__ import annotations

import json

from fastapi import FastAPI
from fastapi.testclient import TestClient

from src.api.v1 import agents
from src.api.v1.agents import router
from src.services.telegram_alert_learning_context_post_apply_verifier import (
    build_telegram_alert_learning_context_post_apply_verifier,
)


def _context_receipts() -> list[dict]:
    targets = [
        ("km", "knowledge_memory_context"),
        ("rag", "rag_index_candidate_context"),
        ("playbook", "playbook_trust_candidate_context"),
        ("mcp", "mcp_audit_feedback_context"),
        ("verifier", "post_apply_verifier_feedback_context"),
        ("ai_agent", "autonomous_runtime_decision_context"),
    ]
    return [
        {
            "receipt_id": f"telegram_alert_learning_context::msg-telegram-1::{target}",
            "source_receipt_id": "msg-telegram-1",
            "source_run_id": "run-telegram-1",
            "source_message_id": "msg-telegram-1",
            "work_item_id": "CIR-P0-TG-001",
            "target": target,
            "consumer_surface": surface,
            "source_ref": f"{target}://awoooi/telegram-alert/msg-telegram-1",
            "ai_agent_context_ref": (
                "ai-agent://awoooi/telegram-alert-learning-context/"
                "run-telegram-1/msg-telegram-1"
            ),
            "status": "ready_for_ai_loop_context",
            "metadata_only": True,
            "target_write_performed": False,
            "raw_payload_included": False,
            "target_selector": {
                "project_id": "awoooi",
                "run_id": "run-telegram-1",
                "message_id": "msg-telegram-1",
                "target": target,
                "source_ref": f"{target}://awoooi/telegram-alert/msg-telegram-1",
            },
            "source_of_truth_diff": {
                "current_state": "telegram_alert_learning_registry_readable",
                "desired_state": "ai_loop_agent_context_receipt_available",
                "delta_kind": f"telegram_alert_{target}_context_binding",
                "raw_payload_included": False,
            },
            "check_mode": {
                "enabled": True,
                "checks": [
                    "ai_alert_card_delivery_receipt_present",
                    "learning_registry_binding_ready",
                    "metadata_only_raw_payload_absent",
                    "ai_agent_context_ref_present",
                ],
            },
            "rollback": {
                "required": True,
                "rollback_ref": (
                    "rollback://telegram-alert-learning-context/"
                    f"msg-telegram-1/{target}"
                ),
            },
            "post_apply_verifier": {
                "required": True,
                "verifier_refs": [
                    "verifier://awoooi/telegram-alert-delivery-receipt/run-telegram-1",
                    f"{target}://awoooi/telegram-alert/msg-telegram-1",
                ],
            },
        }
        for target, surface in targets
    ]


def _consumer_readback(*, receipts: list[dict] | None = None) -> dict:
    return {
        "schema_version": "ai_agent_log_controlled_writeback_consumer_readback_v1",
        "status": "controlled_writeback_consumer_readback_ready",
        "telegram_alert_learning_context": {
            "schema_version": "telegram_alert_ai_loop_consumer_context_readback_v1",
            "status": "ai_loop_agent_context_receipt_ready",
            "project_id": "awoooi",
            "source_registry_status": "learning_registry_ready",
            "consumer_context_route": "ai_loop_agent.telegram_alert_learning_context",
            "target_count": 6,
            "ready_target_count": 6,
            "context_receipt_count": 6,
            "ai_agent_context_receipt_count": 1,
            "context_receipts": receipts if receipts is not None else _context_receipts(),
        },
    }


def test_telegram_alert_learning_context_post_apply_verifier_passes_receipts():
    payload = build_telegram_alert_learning_context_post_apply_verifier(
        consumer_readback=_consumer_readback()
    )

    assert payload["schema_version"] == (
        "telegram_alert_learning_context_post_apply_verifier_v1"
    )
    assert payload["status"] == (
        "telegram_alert_learning_context_post_apply_verified"
    )
    assert payload["active_blockers"] == []
    assert payload["controlled_verifier"]["post_apply_verifier_executed"] is True
    assert payload["controlled_verifier"]["raw_payload_absence_verified"] is True
    assert payload["operation_boundaries"]["runtime_target_write_performed"] is False
    assert payload["operation_boundaries"]["telegram_send_performed"] is False
    assert payload["operation_boundaries"]["secret_value_collection_allowed"] is False

    rollups = payload["rollups"]
    assert rollups["telegram_alert_learning_context_post_apply_verifier_ready"] is True
    assert rollups["context_receipt_count"] == 6
    assert rollups["verified_context_receipt_count"] == 6
    assert rollups["verified_target_count"] == 6
    assert rollups["verified_ai_agent_context_receipt_count"] == 1
    assert rollups["raw_payload_included_count"] == 0
    assert rollups["runtime_write_performed_count"] == 0

    ai_agent_result = [
        result
        for result in payload["verifier_results"]
        if result["target"] == "ai_agent"
    ][0]
    assert ai_agent_result["verifier_status"] == "passed"
    assert ai_agent_result["target_selector_verified"] is True
    assert ai_agent_result["rollback_verified"] is True
    assert ai_agent_result["post_apply_verifier_refs"]

    serialized = json.dumps(payload, ensure_ascii=False)
    assert "TELEGRAM_BOT_TOKEN" not in serialized
    assert "raw Telegram payload" not in serialized


def test_telegram_alert_learning_context_post_apply_verifier_blocks_bad_receipt():
    receipts = _context_receipts()
    receipts[0]["rollback"] = {"required": True, "rollback_ref": ""}

    payload = build_telegram_alert_learning_context_post_apply_verifier(
        consumer_readback=_consumer_readback(receipts=receipts)
    )

    assert payload["status"] == (
        "blocked_telegram_alert_learning_context_post_apply_verifier"
    )
    assert payload["rollups"]["failed_context_receipt_count"] == 1
    assert any(
        blocker.startswith("telegram_alert_context_receipt_verifier_failed:")
        for blocker in payload["active_blockers"]
    )


def test_telegram_alert_learning_context_post_apply_verifier_endpoint(monkeypatch):
    async def fake_loader():
        return build_telegram_alert_learning_context_post_apply_verifier(
            consumer_readback=_consumer_readback()
        )

    monkeypatch.setattr(
        agents,
        "load_latest_telegram_alert_learning_context_post_apply_verifier",
        fake_loader,
    )
    app = FastAPI()
    app.include_router(router, prefix="/api/v1")
    client = TestClient(app)

    response = client.get(
        "/api/v1/agents/telegram-alert-learning-context-post-apply-verifier"
    )

    assert response.status_code == 200
    data = response.json()
    assert data["status"] == "telegram_alert_learning_context_post_apply_verified"
    assert data["rollups"]["verified_target_count"] == 6
