"""AI Agent LOG controlled writeback consumer readback.

Reads live metadata-only dispatch receipts from automation_operation_log and
turns them into KM / RAG / PlayBook / MCP / verifier / AI Agent consumer
bindings. This endpoint does not write those target systems, call MCP tools,
trigger workflows, or persist raw log payloads.
Keep this service in the API-scoped CD profile; web-only deploy markers do not
prove this route has rolled out.
"""

from __future__ import annotations

import asyncio
from collections.abc import Mapping
from typing import Any

from sqlalchemy import text

from src.core.logging import get_logger
from src.db.base import get_db_context
from src.services.ai_agent_log_controlled_writeback_dispatch import (
    EXECUTOR_ROUTE,
    OPERATION_TYPE,
)
from src.services.platform_operator_service import list_ai_alert_card_delivery_readback

SCHEMA_VERSION = "ai_agent_log_controlled_writeback_consumer_readback_v1"
TELEGRAM_ALERT_CONTEXT_SCHEMA_VERSION = (
    "telegram_alert_ai_loop_consumer_context_readback_v1"
)
DEFAULT_PROJECT_ID = "awoooi"
CONSUMER_OPERATION_TYPE = "log_controlled_writeback_consumed"
CONSUMER_EXECUTOR_ROUTE = "ai_agent_metadata_writeback_consumer"
TELEGRAM_ALERT_CONTEXT_PER_PAGE = 6
_TARGETS = ("km", "rag", "playbook", "mcp", "verifier", "ai_agent")
_CONSUMER_SURFACES = {
    "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",
}
_DB_RETRY_DELAYS_SECONDS = (0.0, 0.25, 1.0)
logger = get_logger(__name__)


async def load_latest_ai_agent_log_controlled_writeback_consumer_readback(
    *,
    project_id: str = DEFAULT_PROJECT_ID,
) -> dict[str, Any]:
    """Return live consumer bindings for LOG controlled writeback receipts."""

    try:
        rows, consumer_rows = await _load_consumer_rows_with_retry(project_id=project_id)
    except Exception as exc:  # pragma: no cover - live DB pool pressure
        logger.warning(
            "log_controlled_writeback_consumer_readback_db_unavailable",
            project_id=project_id,
            error_type=type(exc).__name__,
        )
        return _fallback_consumer_readback(
            project_id=project_id,
            error_type=type(exc).__name__,
        )

    telegram_alert_learning_context = await _load_telegram_alert_learning_context(
        project_id=project_id
    )
    return _build_consumer_readback(
        rows=rows,
        consumer_rows=consumer_rows,
        telegram_alert_learning_context=telegram_alert_learning_context,
    )


async def _load_consumer_rows_with_retry(
    *,
    project_id: str,
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
    last_error: Exception | None = None
    for attempt, delay_seconds in enumerate(_DB_RETRY_DELAYS_SECONDS, start=1):
        if delay_seconds:
            await asyncio.sleep(delay_seconds)
        try:
            return await _load_consumer_rows_once(project_id=project_id)
        except Exception as exc:  # pragma: no cover - exercised by live pressure
            last_error = exc
            logger.warning(
                "log_controlled_writeback_consumer_readback_attempt_failed",
                project_id=project_id,
                attempt=attempt,
                error_type=type(exc).__name__,
            )
    if last_error is not None:
        raise last_error
    return [], []


async def _load_consumer_rows_once(
    *,
    project_id: str,
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
    async with get_db_context(project_id) as db:
        await db.execute(text("SET LOCAL statement_timeout = '5000ms'"), {})
        result = await db.execute(
            text("""
                SELECT
                    op_id::text AS op_id,
                    operation_type,
                    actor,
                    status,
                    created_at,
                    input ->> 'semantic_operation_type' AS semantic_operation_type,
                    input ->> 'ledger_operation_type' AS ledger_operation_type,
                    input ->> 'dispatch_receipt_id' AS dispatch_receipt_id,
                    input ->> 'batch_id' AS batch_id,
                    input ->> 'target' AS target,
                    input ->> 'target_surface' AS target_surface,
                    input ->> 'risk_tier' AS risk_tier,
                    input ->> 'project_id' AS project_id,
                    input ->> 'raw_payload_included' AS raw_payload_included,
                    output ->> 'next_action' AS next_action,
                    output ->> 'km_write_performed' AS km_write_performed,
                    output ->> 'rag_index_write_performed' AS rag_index_write_performed,
                    output ->> 'playbook_trust_write_performed' AS playbook_trust_write_performed,
                    output ->> 'mcp_tool_call_performed' AS mcp_tool_call_performed,
                    output ->> 'telegram_send_performed' AS telegram_send_performed,
                    output -> 'post_apply_verifier_refs' AS post_apply_verifier_refs
                FROM automation_operation_log
                WHERE coalesce(input ->> 'semantic_operation_type', operation_type)
                    = :operation_type
                ORDER BY created_at DESC, op_id DESC
                LIMIT 50
            """),
            {"operation_type": OPERATION_TYPE},
        )
        consumer_result = await db.execute(
            text("""
                SELECT
                    op_id::text AS op_id,
                    operation_type,
                    actor,
                    status,
                    created_at,
                    input ->> 'semantic_operation_type' AS semantic_operation_type,
                    input ->> 'ledger_operation_type' AS ledger_operation_type,
                    input ->> 'consumer_receipt_id' AS consumer_receipt_id,
                    input ->> 'source_dispatch_receipt_id' AS source_dispatch_receipt_id,
                    input ->> 'target' AS target,
                    input ->> 'target_surface' AS target_surface,
                    input ->> 'consumer_surface' AS consumer_surface,
                    input ->> 'runtime_target_write_performed' AS runtime_target_write_performed,
                    input ->> 'raw_payload_included' AS raw_payload_included,
                    output ->> 'consumer_context_receipt_recorded'
                        AS consumer_context_receipt_recorded,
                    output ->> 'target_context_receipt_write_performed'
                        AS target_context_receipt_write_performed,
                    output ->> 'next_action' AS next_action,
                    output -> 'post_apply_verifier_refs' AS post_apply_verifier_refs
                FROM automation_operation_log
                WHERE coalesce(input ->> 'semantic_operation_type', operation_type)
                    = :operation_type
                ORDER BY created_at DESC, op_id DESC
                LIMIT 50
            """),
            {"operation_type": CONSUMER_OPERATION_TYPE},
        )
    return _result_rows(result), _result_rows(consumer_result)


def _build_consumer_readback(
    *,
    rows: list[dict[str, Any]],
    consumer_rows: list[dict[str, Any]],
    telegram_alert_learning_context: dict[str, Any],
) -> dict[str, Any]:
    consumer_receipts = _consumer_receipts_by_dispatch_id(consumer_rows)
    bindings = [_consumer_binding(row, consumer_receipts) for row in rows]
    active_blockers = _active_blockers(bindings)
    target_rollups = _target_rollups(bindings)
    runtime_target_write_performed = (
        not active_blockers
        and bool(bindings)
        and all(item["target_write_performed"] is True for item in target_rollups)
    )

    return {
        "schema_version": SCHEMA_VERSION,
        "priority": "P1-LOG-KM-RAG-MCP-PLAYBOOK",
        "scope": "ai_agent_log_controlled_writeback_consumer_readback",
        "status": (
            "controlled_writeback_consumer_readback_ready"
            if not active_blockers
            else "blocked_waiting_controlled_writeback_consumer_receipts"
        ),
        "readback": {
            "workplan_id": "P1-LOG-CONTROLLED-WRITEBACK-CONSUMER-READBACK",
            "workplan_title": (
                "LOG metadata ledger receipts consumable by KM / RAG / PlayBook / "
                "MCP / verifier / AI Agent context"
            ),
            "source_operation_type": OPERATION_TYPE,
            "source_executor_route": EXECUTOR_ROUTE,
            "safe_next_step": (
                "consume_metadata_receipts_in_km_rag_playbook_agent_context_with_post_apply_verifier"
            ),
        },
        "controlled_consume": {
            "mode": "controlled_consumer_readback_ready"
            if not active_blockers
            else "blocked_waiting_consumer_readback",
            "controlled_consume_allowed": not active_blockers,
            "owner_review_required_for_low_medium_high": False,
            "critical_break_glass_required": True,
            "target_selector_required": True,
            "source_of_truth_diff_required": True,
            "check_mode_required": True,
            "rollback_required": True,
            "post_apply_verifier_required": True,
            "runtime_target_write_performed": runtime_target_write_performed,
            "consumer_apply_route": (
                "/api/v1/agents/agent-log-controlled-writeback-consumer-apply"
            ),
        },
        "consumer_bindings": bindings,
        "target_rollups": target_rollups,
        "rollups": {
            "target_count": len(_TARGETS),
            "dispatch_ledger_row_count": len(rows),
            "consumer_apply_receipt_row_count": len(consumer_rows),
            "consumer_binding_count": len(bindings),
            "ready_consumer_binding_count": sum(
                1 for binding in bindings if binding["status"] == "ready_for_consumer_context"
            ),
            "ready_target_count": sum(
                1 for item in _target_rollups(bindings) if item["ready_binding_count"] > 0
            ),
            "metadata_only_receipt_count": sum(
                1 for binding in bindings if binding["raw_payload_included"] is False
            ),
            "post_apply_verifier_ref_count": sum(
                len(binding["post_apply_verifier_refs"]) for binding in bindings
            ),
            "controlled_consumer_readback_ready": not active_blockers,
            "km_consumer_binding_count": _target_count(bindings, "km"),
            "rag_consumer_binding_count": _target_count(bindings, "rag"),
            "playbook_consumer_binding_count": _target_count(bindings, "playbook"),
            "mcp_consumer_binding_count": _target_count(bindings, "mcp"),
            "verifier_consumer_binding_count": _target_count(bindings, "verifier"),
            "ai_agent_consumer_binding_count": _target_count(bindings, "ai_agent"),
            "target_context_receipt_write_count": sum(
                1 for binding in bindings if binding["target_write_performed"] is True
            ),
            "km_context_receipt_write_count": _target_write_count(bindings, "km"),
            "rag_context_receipt_write_count": _target_write_count(bindings, "rag"),
            "playbook_context_receipt_write_count": _target_write_count(
                bindings, "playbook"
            ),
            "mcp_context_receipt_write_count": _target_write_count(bindings, "mcp"),
            "verifier_context_receipt_write_count": _target_write_count(
                bindings, "verifier"
            ),
            "ai_agent_context_receipt_write_count": _target_write_count(
                bindings, "ai_agent"
            ),
            "telegram_alert_learning_context_readback_ready": (
                telegram_alert_learning_context.get("status")
                == "ai_loop_agent_context_receipt_ready"
            ),
            "telegram_alert_learning_context_receipt_count": _safe_int(
                telegram_alert_learning_context.get("context_receipt_count")
            ),
            "telegram_alert_learning_ai_agent_context_receipt_count": _safe_int(
                telegram_alert_learning_context.get(
                    "ai_agent_context_receipt_count"
                )
            ),
            "telegram_alert_learning_ready_target_count": _safe_int(
                telegram_alert_learning_context.get("ready_target_count")
            ),
            "telegram_alert_learning_target_count": _safe_int(
                telegram_alert_learning_context.get("target_count")
            ),
            "runtime_target_write_performed": runtime_target_write_performed,
        },
        "telegram_alert_learning_context": telegram_alert_learning_context,
        "active_blockers": active_blockers,
        "operation_boundaries": {
            "consumer_readback_only": True,
            "metadata_ledger_read_performed": True,
            "consumer_apply_receipt_read_performed": True,
            "telegram_alert_registry_metadata_read_performed": (
                telegram_alert_learning_context["operation_boundaries"][
                    "metadata_read_performed"
                ]
            ),
            "runtime_target_write_performed": runtime_target_write_performed,
            "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_log_payload_persisted": False,
            "secret_value_collection_allowed": False,
            "github_api_used": False,
        },
    }


def _fallback_consumer_readback(
    *,
    project_id: str,
    error_type: str,
) -> dict[str, Any]:
    return {
        "schema_version": SCHEMA_VERSION,
        "priority": "P1-LOG-KM-RAG-MCP-PLAYBOOK",
        "scope": "ai_agent_log_controlled_writeback_consumer_readback",
        "status": "blocked_waiting_controlled_writeback_consumer_db_readback",
        "readback": {
            "workplan_id": "P1-LOG-CONTROLLED-WRITEBACK-CONSUMER-READBACK",
            "workplan_title": (
                "LOG metadata ledger receipts consumable by KM / RAG / PlayBook / "
                "MCP / verifier / AI Agent context"
            ),
            "source_operation_type": OPERATION_TYPE,
            "source_executor_route": EXECUTOR_ROUTE,
            "db_read_status": "unavailable",
            "error_type": error_type,
            "safe_next_step": "retry_consumer_readback_after_db_pool_pressure_clears",
        },
        "controlled_consume": {
            "mode": "blocked_waiting_consumer_db_readback",
            "controlled_consume_allowed": False,
            "owner_review_required_for_low_medium_high": False,
            "critical_break_glass_required": True,
            "target_selector_required": True,
            "source_of_truth_diff_required": True,
            "check_mode_required": True,
            "rollback_required": True,
            "post_apply_verifier_required": True,
            "runtime_target_write_performed": False,
            "consumer_apply_route": (
                "/api/v1/agents/agent-log-controlled-writeback-consumer-apply"
            ),
        },
        "consumer_bindings": [],
        "target_rollups": _target_rollups([]),
        "rollups": {
            "target_count": len(_TARGETS),
            "dispatch_ledger_row_count": 0,
            "consumer_apply_receipt_row_count": 0,
            "consumer_binding_count": 0,
            "ready_consumer_binding_count": 0,
            "ready_target_count": 0,
            "metadata_only_receipt_count": 0,
            "post_apply_verifier_ref_count": 0,
            "controlled_consumer_readback_ready": False,
            "km_consumer_binding_count": 0,
            "rag_consumer_binding_count": 0,
            "playbook_consumer_binding_count": 0,
            "mcp_consumer_binding_count": 0,
            "verifier_consumer_binding_count": 0,
            "ai_agent_consumer_binding_count": 0,
            "target_context_receipt_write_count": 0,
            "km_context_receipt_write_count": 0,
            "rag_context_receipt_write_count": 0,
            "playbook_context_receipt_write_count": 0,
            "mcp_context_receipt_write_count": 0,
            "verifier_context_receipt_write_count": 0,
            "ai_agent_context_receipt_write_count": 0,
            "telegram_alert_learning_context_readback_ready": False,
            "telegram_alert_learning_context_receipt_count": 0,
            "telegram_alert_learning_ai_agent_context_receipt_count": 0,
            "telegram_alert_learning_ready_target_count": 0,
            "telegram_alert_learning_target_count": 0,
            "runtime_target_write_performed": False,
        },
        "telegram_alert_learning_context": _telegram_alert_learning_context_unavailable(
            project_id=project_id,
            error_type=error_type,
        ),
        "active_blockers": [
            "log_controlled_writeback_consumer_readback_db_unavailable"
        ],
        "operation_boundaries": {
            "consumer_readback_only": True,
            "metadata_ledger_read_performed": False,
            "consumer_apply_receipt_read_performed": False,
            "telegram_alert_registry_metadata_read_performed": False,
            "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_log_payload_persisted": False,
            "secret_value_collection_allowed": False,
            "github_api_used": False,
        },
    }


def _consumer_binding(
    row: Mapping[str, Any],
    consumer_receipts: Mapping[str, Mapping[str, Any]],
) -> dict[str, Any]:
    target = str(row.get("target") or "")
    dispatch_receipt_id = str(row.get("dispatch_receipt_id") or "")
    consumer_receipt = consumer_receipts.get(dispatch_receipt_id)
    verifier_refs = _strings(row.get("post_apply_verifier_refs"))
    raw_payload_included = str(row.get("raw_payload_included") or "").lower() == "true"
    return {
        "consumer_binding_id": f"consumer::{dispatch_receipt_id or row.get('op_id')}",
        "dispatch_receipt_id": dispatch_receipt_id,
        "ledger_op_id": str(row.get("op_id") or ""),
        "consumer_receipt_id": (
            str(consumer_receipt.get("consumer_receipt_id") or "")
            if consumer_receipt
            else ""
        ),
        "consumer_receipt_op_id": (
            str(consumer_receipt.get("op_id") or "") if consumer_receipt else ""
        ),
        "target": target,
        "target_surface": str(row.get("target_surface") or ""),
        "consumer_surface": _CONSUMER_SURFACES.get(target, "unknown_consumer_surface"),
        "risk_tier": str(row.get("risk_tier") or ""),
        "status": (
            "ready_for_consumer_context"
            if _binding_ready(row, raw_payload_included)
            else "blocked_waiting_consumer_binding_controls"
        ),
        "project_id": str(row.get("project_id") or ""),
        "executor_route": str(row.get("actor") or ""),
        "semantic_operation_type": str(row.get("semantic_operation_type") or ""),
        "ledger_operation_type": str(row.get("ledger_operation_type") or ""),
        "ledger_status": str(row.get("status") or ""),
        "raw_payload_included": raw_payload_included,
        "next_action": str(row.get("next_action") or ""),
        "post_apply_verifier_refs": verifier_refs,
        "target_selector": {
            "dispatch_receipt_id": str(row.get("dispatch_receipt_id") or ""),
            "target": target,
            "target_surface": str(row.get("target_surface") or ""),
            "consumer_surface": _CONSUMER_SURFACES.get(target, "unknown_consumer_surface"),
        },
        "source_of_truth_diff": {
            "current_state": "metadata_dispatch_receipt_in_ledger",
            "desired_state": "metadata_receipt_available_to_consumer_context",
            "delta_kind": f"{target}_consumer_context_binding",
            "raw_payload_included": raw_payload_included,
        },
        "check_mode": {
            "enabled": True,
            "checks": [
                "dispatch_receipt_id_present",
                "target_surface_present",
                "metadata_only_raw_payload_absent",
                "post_apply_verifier_refs_present",
                "ledger_status_success",
            ],
        },
        "rollback": {
            "required": True,
            "rollback_ref": (
                "rollback://ai-agent-log-controlled-writeback-consumer/"
                f"{row.get('dispatch_receipt_id') or row.get('op_id')}"
            ),
            "strategy": "ignore_consumer_binding_and_mark_receipt_superseded",
        },
        "post_apply_verifier": {
            "required": True,
            "verifier_refs": verifier_refs,
        },
        "target_write_performed": consumer_receipt is not None,
        "target_write_receipt": (
            {
                "consumer_receipt_id": str(consumer_receipt.get("consumer_receipt_id") or ""),
                "ledger_op_id": str(consumer_receipt.get("op_id") or ""),
                "status": str(consumer_receipt.get("status") or ""),
                "actor": str(consumer_receipt.get("actor") or ""),
                "semantic_operation_type": str(
                    consumer_receipt.get("semantic_operation_type") or ""
                ),
                "runtime_target_write_performed": (
                    str(
                        consumer_receipt.get("runtime_target_write_performed") or ""
                    ).lower()
                    == "true"
                ),
                "target_context_receipt_write_performed": (
                    str(
                        consumer_receipt.get("target_context_receipt_write_performed")
                        or ""
                    ).lower()
                    == "true"
                ),
            }
            if consumer_receipt
            else None
        ),
    }


def _binding_ready(row: Mapping[str, Any], raw_payload_included: bool) -> bool:
    if str(row.get("semantic_operation_type") or "") != OPERATION_TYPE:
        return False
    if str(row.get("actor") or "") != EXECUTOR_ROUTE:
        return False
    if str(row.get("status") or "") != "success":
        return False
    if str(row.get("target") or "") not in _TARGETS:
        return False
    if not str(row.get("dispatch_receipt_id") or ""):
        return False
    if not str(row.get("target_surface") or ""):
        return False
    if raw_payload_included:
        return False
    return bool(_strings(row.get("post_apply_verifier_refs")))


def _active_blockers(bindings: list[dict[str, Any]]) -> list[str]:
    blockers: list[str] = []
    if not bindings:
        blockers.append("log_controlled_writeback_dispatch_receipts_missing")
    missing_targets = [target for target in _TARGETS if _target_count(bindings, target) == 0]
    for target in missing_targets:
        blockers.append(f"{target}_consumer_binding_missing")
    for binding in bindings:
        if binding["status"] != "ready_for_consumer_context":
            blockers.append(f"{binding['target'] or 'unknown'}_consumer_binding_not_ready")
        if binding["raw_payload_included"] is not False:
            blockers.append(f"{binding['target'] or 'unknown'}_raw_payload_included")
    return _unique(blockers)


def _target_rollups(bindings: list[dict[str, Any]]) -> list[dict[str, Any]]:
    return [
        {
            "target": target,
            "consumer_surface": _CONSUMER_SURFACES[target],
            "binding_count": _target_count(bindings, target),
            "ready_binding_count": sum(
                1
                for binding in bindings
                if binding["target"] == target
                and binding["status"] == "ready_for_consumer_context"
            ),
            "metadata_only": all(
                binding["raw_payload_included"] is False
                for binding in bindings
                if binding["target"] == target
            ),
            "target_write_performed": any(
                binding["target_write_performed"] is True
                for binding in bindings
                if binding["target"] == target
            ),
        }
        for target in _TARGETS
    ]


def _target_count(bindings: list[dict[str, Any]], target: str) -> int:
    return sum(1 for binding in bindings if binding["target"] == target)


def _target_write_count(bindings: list[dict[str, Any]], target: str) -> int:
    return sum(
        1
        for binding in bindings
        if binding["target"] == target and binding["target_write_performed"] is True
    )


def _consumer_receipts_by_dispatch_id(
    rows: list[dict[str, Any]],
) -> dict[str, dict[str, Any]]:
    receipts: dict[str, dict[str, Any]] = {}
    for row in rows:
        if str(row.get("semantic_operation_type") or "") != CONSUMER_OPERATION_TYPE:
            continue
        if str(row.get("actor") or "") != CONSUMER_EXECUTOR_ROUTE:
            continue
        if str(row.get("status") or "") != "success":
            continue
        if str(row.get("raw_payload_included") or "").lower() == "true":
            continue
        dispatch_receipt_id = str(row.get("source_dispatch_receipt_id") or "")
        if not dispatch_receipt_id or dispatch_receipt_id in receipts:
            continue
        receipts[dispatch_receipt_id] = row
    return receipts


async def _load_telegram_alert_learning_context(
    *,
    project_id: str,
) -> dict[str, Any]:
    """Read Telegram alert learning registry as AI Loop consumer context."""
    try:
        readback = await list_ai_alert_card_delivery_readback(
            project_id=project_id,
            page=1,
            per_page=TELEGRAM_ALERT_CONTEXT_PER_PAGE,
            refresh=True,
        )
    except Exception as exc:  # pragma: no cover - live DB pool pressure
        logger.warning(
            "telegram_alert_learning_context_readback_unavailable",
            project_id=project_id,
            error_type=type(exc).__name__,
        )
        return _telegram_alert_learning_context_unavailable(
            project_id=project_id,
            error_type=type(exc).__name__,
        )
    return _telegram_alert_learning_context_from_alert_cards(readback)


def _telegram_alert_learning_context_from_alert_cards(
    readback: Mapping[str, Any],
) -> dict[str, Any]:
    registry = _dict(readback.get("learning_registry"))
    summary = _dict(readback.get("summary"))
    project_id = str(
        registry.get("project_id")
        or summary.get("project_id")
        or DEFAULT_PROJECT_ID
    )
    items = [_dict(item) for item in _list(readback.get("items"))]
    context_receipts = _telegram_alert_context_receipts(items)
    target_count = _safe_int(registry.get("target_count") or len(_TARGETS))
    ready_target_count = _safe_int(registry.get("ready_target_count"))
    ai_agent_context_receipt_count = sum(
        1 for receipt in context_receipts if receipt["target"] == "ai_agent"
    )
    ready = (
        registry.get("status") == "learning_registry_ready"
        and ready_target_count == target_count
        and target_count > 0
        and ai_agent_context_receipt_count > 0
    )

    return {
        "schema_version": TELEGRAM_ALERT_CONTEXT_SCHEMA_VERSION,
        "status": (
            "ai_loop_agent_context_receipt_ready"
            if ready
            else "waiting_telegram_alert_learning_registry"
        ),
        "priority_work_item_id": "CIR-P0-TG-001",
        "project_id": project_id,
        "source_endpoint": "/api/v1/platform/runs/ai-alert-cards",
        "source_registry_schema_version": registry.get("schema_version"),
        "source_registry_status": registry.get("status"),
        "consumer_context_route": "ai_loop_agent.telegram_alert_learning_context",
        "target_count": target_count,
        "ready_target_count": ready_target_count,
        "context_receipt_count": len(context_receipts),
        "ai_agent_context_receipt_count": ai_agent_context_receipt_count,
        "next_action": (
            "verify_telegram_alert_learning_context_receipts_with_ai_loop_post_apply_verifier"
            if ready
            else "wait_for_telegram_alert_learning_registry_before_context_receipt"
        ),
        "context_receipts": context_receipts,
        "active_blockers": (
            []
            if ready
            else ["telegram_alert_learning_registry_not_ready_for_ai_loop_context"]
        ),
        "operation_boundaries": {
            "metadata_read_performed": True,
            "db_or_log_receipt_read_performed": bool(items),
            "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,
            "raw_payload_included": False,
            "secret_value_collection_allowed": False,
            "github_api_used": False,
        },
    }


def _telegram_alert_context_receipts(
    items: list[dict[str, Any]],
) -> list[dict[str, Any]]:
    receipts: list[dict[str, Any]] = []
    for item in items:
        learning_refs = _dict(item.get("learning_writeback_refs"))
        message_id = str(item.get("message_id") or learning_refs.get("receipt_id") or "")
        run_id = str(item.get("run_id") or learning_refs.get("run_id") or "")
        for binding_value in _list(item.get("learning_registry_bindings")):
            binding = _dict(binding_value)
            target = str(binding.get("target") or "")
            if target not in _TARGETS:
                continue
            ref = str(binding.get("ref") or "")
            status = str(binding.get("status") or "")
            ready = status == "ready_for_consumer_context" and bool(ref)
            receipts.append({
                "receipt_id": (
                    "telegram_alert_learning_context::"
                    f"{message_id or 'unknown-message'}::{target}"
                ),
                "source_receipt_id": str(learning_refs.get("receipt_id") or message_id),
                "source_run_id": run_id,
                "source_message_id": message_id,
                "work_item_id": str(
                    binding.get("work_item_id")
                    or learning_refs.get("work_item_id")
                    or "CIR-P0-TG-001"
                ),
                "target": target,
                "consumer_surface": str(binding.get("consumer_surface") or ""),
                "source_ref": ref,
                "ai_agent_context_ref": str(
                    learning_refs.get("ai_agent_context_ref") or ""
                ),
                "event_type": str(item.get("event_type") or ""),
                "lane": str(item.get("lane") or ""),
                "status": (
                    "ready_for_ai_loop_context" if ready else "missing_source_ref"
                ),
                "metadata_only": True,
                "target_write_performed": False,
                "raw_payload_included": False,
                "target_selector": {
                    "project_id": str(item.get("project_id") or DEFAULT_PROJECT_ID),
                    "run_id": run_id,
                    "message_id": message_id,
                    "target": target,
                    "source_ref": ref,
                },
                "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"{message_id or 'unknown-message'}/{target}"
                    ),
                    "strategy": "ignore_context_receipt_and_wait_for_next_delivery_readback",
                },
                "post_apply_verifier": {
                    "required": True,
                    "verifier_refs": _unique([
                        str(learning_refs.get("post_verifier_ref") or ""),
                        str(binding.get("ref") or ""),
                    ]),
                },
            })
    return receipts


def _telegram_alert_learning_context_unavailable(
    *,
    project_id: str,
    error_type: str,
) -> dict[str, Any]:
    return {
        "schema_version": TELEGRAM_ALERT_CONTEXT_SCHEMA_VERSION,
        "status": "blocked_telegram_alert_learning_registry_readback_unavailable",
        "priority_work_item_id": "CIR-P0-TG-001",
        "project_id": project_id,
        "source_endpoint": "/api/v1/platform/runs/ai-alert-cards",
        "source_registry_schema_version": None,
        "source_registry_status": "unavailable",
        "consumer_context_route": "ai_loop_agent.telegram_alert_learning_context",
        "target_count": len(_TARGETS),
        "ready_target_count": 0,
        "context_receipt_count": 0,
        "ai_agent_context_receipt_count": 0,
        "next_action": "retry_telegram_alert_learning_registry_readback",
        "context_receipts": [],
        "active_blockers": [
            f"telegram_alert_learning_registry_readback_unavailable:{error_type}"
        ],
        "operation_boundaries": {
            "metadata_read_performed": False,
            "db_or_log_receipt_read_performed": False,
            "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,
            "raw_payload_included": False,
            "secret_value_collection_allowed": False,
            "github_api_used": False,
        },
    }


def _result_rows(result: Any) -> list[dict[str, Any]]:
    mappings = getattr(result, "mappings", None)
    if callable(mappings):
        return [dict(row) for row in mappings().all()]
    all_rows = getattr(result, "all", None)
    if callable(all_rows):
        return [_row_mapping(row) for row in all_rows()]
    return [_row_mapping(row) for row in result]


def _row_mapping(row: Any) -> dict[str, Any]:
    if isinstance(row, Mapping):
        return dict(row)
    mapping = getattr(row, "_mapping", None)
    if mapping is not None:
        return dict(mapping)
    return dict(row)


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


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


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


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


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