"""AI-first compatibility contracts for PChome mapping receipts."""

from __future__ import annotations

from typing import Any

from services.ai_exception_contract import (
    AI_EXCEPTION_MODE_KEY,
    AI_EXCEPTION_MODE_MACHINE_VERIFIABLE,
    AI_EXCEPTION_REQUIRED_COUNT_KEY,
    AI_EXCEPTION_REQUIRED_KEY,
    LEGACY_HUMAN_REVIEW_REQUIRED_COUNT_KEY,
    LEGACY_HUMAN_REVIEW_REQUIRED_KEY,
    LEGACY_HUMAN_REVIEW_REQUIRED_LEGACY_KEY,
    LEGACY_PRIMARY_FLOW_COUNT_KEY,
    LEGACY_REVIEW_MODE_EXCEPTION_ONLY,
    LEGACY_REVIEW_MODE_KEY,
    LEGACY_REVIEW_REQUIRED_COUNT_KEY,
    LEGACY_REVIEW_REQUIRED_KEY,
    PRIMARY_HUMAN_GATE_COUNT_KEY,
)


def _ai_exception_compatibility_fields(ai_exception_required: bool) -> dict[str, Any]:
    """Return the AI-first exception contract with legacy readback aliases."""
    return {
        LEGACY_HUMAN_REVIEW_REQUIRED_KEY: False,
        LEGACY_HUMAN_REVIEW_REQUIRED_LEGACY_KEY: bool(ai_exception_required),
        AI_EXCEPTION_REQUIRED_KEY: bool(ai_exception_required),
        PRIMARY_HUMAN_GATE_COUNT_KEY: 0,
        AI_EXCEPTION_MODE_KEY: AI_EXCEPTION_MODE_MACHINE_VERIFIABLE,
    }


def _legacy_review_compatibility_fields(ai_exception_required: bool = False) -> dict[str, Any]:
    """Keep old review-mode keys false while exposing the AI exception state."""
    return {
        LEGACY_REVIEW_REQUIRED_KEY: False,
        LEGACY_REVIEW_MODE_KEY: LEGACY_REVIEW_MODE_EXCEPTION_ONLY,
        AI_EXCEPTION_REQUIRED_KEY: bool(ai_exception_required),
        AI_EXCEPTION_MODE_KEY: AI_EXCEPTION_MODE_MACHINE_VERIFIABLE,
    }


def _evidence_requires_ai_exception(evidence: dict[str, Any]) -> bool:
    return bool(
        evidence.get(AI_EXCEPTION_REQUIRED_KEY)
        or evidence.get(LEGACY_HUMAN_REVIEW_REQUIRED_LEGACY_KEY)
        or evidence.get(LEGACY_HUMAN_REVIEW_REQUIRED_KEY)
    )


def _summary_exception_count(summary: dict[str, Any]) -> int:
    return int(
        summary.get(AI_EXCEPTION_REQUIRED_COUNT_KEY)
        or summary.get(LEGACY_REVIEW_REQUIRED_COUNT_KEY)
        or 0
    )


__all__ = (
    "_ai_exception_compatibility_fields",
    "_evidence_requires_ai_exception",
    "_legacy_review_compatibility_fields",
    "_summary_exception_count",
)
