"""Telegram alert learning context post-apply verifier readback.

Verifies metadata-only Telegram alert learning context receipts emitted by the
AI Loop consumer readback. This module only reads public-safe receipt metadata;
it does not write KM/RAG/PlayBook, call MCP tools, send Telegram, or touch
runtime infrastructure.
"""

from __future__ import annotations

from collections.abc import Mapping
from typing import Any

from src.services.ai_agent_log_controlled_writeback_consumer_readback import (
    load_latest_ai_agent_log_controlled_writeback_consumer_readback,
)

SCHEMA_VERSION = "telegram_alert_learning_context_post_apply_verifier_v1"
DEFAULT_PROJECT_ID = "awoooi"
_TARGETS = ("km", "rag", "playbook", "mcp", "verifier", "ai_agent")
_REQUIRED_TARGET_SELECTOR_FIELDS = (
    "project_id",
    "run_id",
    "message_id",
    "target",
    "source_ref",
)
_REQUIRED_CHECKS = (
    "ai_alert_card_delivery_receipt_present",
    "learning_registry_binding_ready",
    "metadata_only_raw_payload_absent",
    "ai_agent_context_ref_present",
)


async def load_latest_telegram_alert_learning_context_post_apply_verifier(
    *,
    project_id: str = DEFAULT_PROJECT_ID,
) -> dict[str, Any]:
    """Return post-apply verifier results for Telegram alert context receipts."""

    consumer_readback = (
        await load_latest_ai_agent_log_controlled_writeback_consumer_readback(
            project_id=project_id
        )
    )
    return build_telegram_alert_learning_context_post_apply_verifier(
        consumer_readback=consumer_readback,
        project_id=project_id,
    )


def build_telegram_alert_learning_context_post_apply_verifier(
    *,
    consumer_readback: Mapping[str, Any],
    project_id: str = DEFAULT_PROJECT_ID,
) -> dict[str, Any]:
    """Build a deterministic verifier readback from consumer context receipts."""

    consumer = _dict(consumer_readback)
    telegram_context = _dict(consumer.get("telegram_alert_learning_context"))
    context_receipts = [
        _dict(receipt) for receipt in _list(telegram_context.get("context_receipts"))
    ]
    verifier_results = [
        _verify_context_receipt(receipt) for receipt in context_receipts
    ]

    target_count = _safe_int(telegram_context.get("target_count")) or len(_TARGETS)
    verified_targets = sorted(
        {
            str(item["target"])
            for item in verifier_results
            if item["verifier_status"] == "passed"
        }
    )
    verified_ai_agent_count = sum(
        1
        for item in verifier_results
        if item["target"] == "ai_agent" and item["verifier_status"] == "passed"
    )
    failed_results = [
        item for item in verifier_results if item["verifier_status"] != "passed"
    ]
    source_ready = (
        telegram_context.get("status") == "ai_loop_agent_context_receipt_ready"
    )
    ready = bool(
        source_ready
        and context_receipts
        and not failed_results
        and len(verified_targets) == target_count
        and verified_ai_agent_count > 0
    )
    active_blockers = _active_blockers(
        source_ready=source_ready,
        context_receipts=context_receipts,
        failed_results=failed_results,
        verified_targets=verified_targets,
        target_count=target_count,
        verified_ai_agent_count=verified_ai_agent_count,
    )

    return {
        "schema_version": SCHEMA_VERSION,
        "priority": "P0-TELEGRAM-AI-LOOP-POST-APPLY-VERIFIER",
        "priority_work_item_id": "CIR-P0-TG-001",
        "project_id": project_id,
        "status": (
            "telegram_alert_learning_context_post_apply_verified"
            if ready
            else "blocked_telegram_alert_learning_context_post_apply_verifier"
        ),
        "source_readback": {
            "source_endpoint": (
                "/api/v1/agents/agent-log-controlled-writeback-consumer-readback"
            ),
            "source_schema_version": consumer.get("schema_version"),
            "telegram_context_schema_version": telegram_context.get("schema_version"),
            "telegram_context_status": telegram_context.get("status"),
            "consumer_context_route": telegram_context.get("consumer_context_route"),
            "source_registry_status": telegram_context.get("source_registry_status"),
        },
        "controlled_verifier": {
            "mode": "metadata_only_post_apply_verifier_readback",
            "post_apply_verifier_executed": True,
            "controlled_apply_allowed_for_low_medium_high": ready,
            "owner_review_required_for_low_medium_high": False,
            "critical_break_glass_required": True,
            "target_selector_verified": ready,
            "source_of_truth_diff_verified": ready,
            "check_mode_verified": ready,
            "rollback_verified": ready,
            "raw_payload_absence_verified": ready,
        },
        "verifier_results": verifier_results,
        "rollups": {
            "telegram_alert_learning_context_post_apply_verifier_ready": ready,
            "source_context_ready": source_ready,
            "context_receipt_count": len(context_receipts),
            "verified_context_receipt_count": sum(
                1 for item in verifier_results if item["verifier_status"] == "passed"
            ),
            "failed_context_receipt_count": len(failed_results),
            "target_count": target_count,
            "verified_target_count": len(verified_targets),
            "verified_targets": verified_targets,
            "verified_ai_agent_context_receipt_count": verified_ai_agent_count,
            "target_selector_verified_count": sum(
                1 for item in verifier_results if item["target_selector_verified"]
            ),
            "source_of_truth_diff_verified_count": sum(
                1
                for item in verifier_results
                if item["source_of_truth_diff_verified"]
            ),
            "check_mode_verified_count": sum(
                1 for item in verifier_results if item["check_mode_verified"]
            ),
            "rollback_verified_count": sum(
                1 for item in verifier_results if item["rollback_verified"]
            ),
            "post_apply_verifier_ref_count": sum(
                len(item["post_apply_verifier_refs"]) for item in verifier_results
            ),
            "metadata_only_receipt_count": sum(
                1 for item in verifier_results if item["metadata_only"] is True
            ),
            "raw_payload_included_count": sum(
                1 for item in verifier_results if item["raw_payload_included"] is True
            ),
            "runtime_write_performed_count": 0,
            "telegram_send_performed_count": 0,
            "mcp_tool_call_performed_count": 0,
            "secret_value_read_count": 0,
        },
        "active_blockers": active_blockers,
        "next_action": (
            "surface_verified_telegram_alert_context_receipts_in_awooop_runs_work_items_alerts"
            if ready
            else "fix_failed_telegram_alert_context_receipts_then_rerun_post_apply_verifier"
        ),
        "operation_boundaries": {
            "metadata_read_performed": True,
            "post_apply_verifier_read_performed": True,
            "runtime_target_write_performed": False,
            "km_write_performed": False,
            "rag_index_write_performed": False,
            "playbook_trust_write_performed": False,
            "mcp_tool_call_performed": False,
            "agent_runtime_action_performed": False,
            "telegram_send_performed": False,
            "workflow_trigger_performed": False,
            "raw_payload_included": False,
            "secret_value_collection_allowed": False,
            "github_api_used": False,
        },
    }


def _verify_context_receipt(receipt: dict[str, Any]) -> dict[str, Any]:
    target = str(receipt.get("target") or "")
    target_selector = _dict(receipt.get("target_selector"))
    source_diff = _dict(receipt.get("source_of_truth_diff"))
    check_mode = _dict(receipt.get("check_mode"))
    rollback = _dict(receipt.get("rollback"))
    post_apply_verifier = _dict(receipt.get("post_apply_verifier"))
    verifier_refs = _strings(post_apply_verifier.get("verifier_refs"))

    target_selector_missing = [
        key for key in _REQUIRED_TARGET_SELECTOR_FIELDS if not target_selector.get(key)
    ]
    checks = _strings(check_mode.get("checks"))
    missing_checks = [check for check in _REQUIRED_CHECKS if check not in checks]
    failed_checks: list[str] = []

    if target not in _TARGETS:
        failed_checks.append("target_in_allowed_set")
    if receipt.get("status") != "ready_for_ai_loop_context":
        failed_checks.append("receipt_ready_for_ai_loop_context")
    if target_selector_missing:
        failed_checks.append("target_selector_required_fields_present")
    if not _source_diff_verified(source_diff, target):
        failed_checks.append("source_of_truth_diff_verified")
    if check_mode.get("enabled") is not True or missing_checks:
        failed_checks.append("check_mode_required_checks_present")
    if rollback.get("required") is not True or not rollback.get("rollback_ref"):
        failed_checks.append("rollback_ref_present")
    if post_apply_verifier.get("required") is not True or not verifier_refs:
        failed_checks.append("post_apply_verifier_refs_present")
    if receipt.get("metadata_only") is not True:
        failed_checks.append("metadata_only_receipt")
    if receipt.get("raw_payload_included") is not False:
        failed_checks.append("raw_payload_absent")
    if receipt.get("target_write_performed") is not False:
        failed_checks.append("target_write_not_performed_by_verifier")
    if not receipt.get("ai_agent_context_ref"):
        failed_checks.append("ai_agent_context_ref_present")

    passed_checks = [
        "target_in_allowed_set",
        "receipt_ready_for_ai_loop_context",
        "target_selector_required_fields_present",
        "source_of_truth_diff_verified",
        "check_mode_required_checks_present",
        "rollback_ref_present",
        "post_apply_verifier_refs_present",
        "metadata_only_receipt",
        "raw_payload_absent",
        "target_write_not_performed_by_verifier",
        "ai_agent_context_ref_present",
    ]
    passed_checks = [check for check in passed_checks if check not in failed_checks]

    return {
        "receipt_id": str(receipt.get("receipt_id") or ""),
        "source_receipt_id": str(receipt.get("source_receipt_id") or ""),
        "source_run_id": str(receipt.get("source_run_id") or ""),
        "source_message_id": str(receipt.get("source_message_id") or ""),
        "work_item_id": str(receipt.get("work_item_id") or "CIR-P0-TG-001"),
        "target": target,
        "consumer_surface": str(receipt.get("consumer_surface") or ""),
        "verifier_status": "passed" if not failed_checks else "failed",
        "passed_checks": passed_checks,
        "failed_checks": failed_checks,
        "target_selector_verified": not target_selector_missing,
        "target_selector_missing_fields": target_selector_missing,
        "source_of_truth_diff_verified": _source_diff_verified(source_diff, target),
        "check_mode_verified": check_mode.get("enabled") is True and not missing_checks,
        "check_mode_missing_checks": missing_checks,
        "rollback_verified": (
            rollback.get("required") is True and bool(rollback.get("rollback_ref"))
        ),
        "post_apply_verifier_refs": verifier_refs,
        "metadata_only": receipt.get("metadata_only") is True,
        "raw_payload_included": receipt.get("raw_payload_included") is True,
        "runtime_target_write_performed": False,
        "telegram_send_performed": False,
        "evidence_refs": _unique(
            [
                str(receipt.get("source_ref") or ""),
                str(receipt.get("ai_agent_context_ref") or ""),
                *verifier_refs,
            ]
        ),
    }


def _active_blockers(
    *,
    source_ready: bool,
    context_receipts: list[dict[str, Any]],
    failed_results: list[dict[str, Any]],
    verified_targets: list[str],
    target_count: int,
    verified_ai_agent_count: int,
) -> list[str]:
    blockers: list[str] = []
    if not source_ready:
        blockers.append("telegram_alert_learning_context_source_not_ready")
    if not context_receipts:
        blockers.append("telegram_alert_learning_context_receipts_missing")
    if len(verified_targets) < target_count:
        blockers.append("telegram_alert_learning_context_verified_target_count_below_target")
    if verified_ai_agent_count <= 0:
        blockers.append("telegram_alert_learning_context_ai_agent_receipt_not_verified")
    for item in failed_results:
        receipt_id = item.get("receipt_id") or "unknown-receipt"
        blockers.append(f"telegram_alert_context_receipt_verifier_failed:{receipt_id}")
    return blockers


def _source_diff_verified(source_diff: dict[str, Any], target: str) -> bool:
    return bool(
        source_diff.get("current_state") == "telegram_alert_learning_registry_readable"
        and source_diff.get("desired_state")
        == "ai_loop_agent_context_receipt_available"
        and source_diff.get("delta_kind") == f"telegram_alert_{target}_context_binding"
        and source_diff.get("raw_payload_included") is False
    )


def _dict(value: Any) -> dict[str, Any]:
    return value if isinstance(value, dict) else {}


def _list(value: Any) -> list[Any]:
    return value if isinstance(value, list) else []


def _strings(value: Any) -> list[str]:
    return [str(item) for item in _list(value) if str(item)]


def _unique(values: list[str]) -> list[str]:
    seen: set[str] = set()
    result: list[str] = []
    for value in values:
        if value in seen:
            continue
        seen.add(value)
        result.append(value)
    return result


def _safe_int(value: Any) -> int:
    try:
        return int(value)
    except (TypeError, ValueError):
        return 0
