"""Trust gate evaluator for execution/promotion policy checks."""

from __future__ import annotations

from typing import Any, Dict, List, Optional


def evaluate_trust_gate(
    *,
    trust_events: Optional[List[Dict[str, Any]]] = None,
    parity_status: str = "",
    active_alerts_by_severity: Optional[Dict[str, int]] = None,
    block_on_warning: bool = False,
) -> Dict[str, Any]:
    """Evaluate whether a run is eligible for execution/promotion.

    Gate fails when:
    - Any trust event has result.ok == False
    - Parity status indicates failure
    - Critical alerts exist
    - Warning alerts exist and block_on_warning=True
    """
    trust_events = trust_events or []
    active_alerts_by_severity = active_alerts_by_severity or {}
    reasons: List[str] = []

    trust_failures = [
        e for e in trust_events
        if not bool((e.get("result") or {}).get("ok", False))
    ]
    if trust_failures:
        reasons.append(f"trust_failures:{len(trust_failures)}")

    normalized_parity = (parity_status or "").strip().lower()
    if normalized_parity in {"failed", "fail", "error", "not_certified"}:
        reasons.append(f"parity_status:{normalized_parity}")

    critical_count = int(active_alerts_by_severity.get("critical", 0))
    warning_count = int(active_alerts_by_severity.get("warning", 0))

    if critical_count > 0:
        reasons.append(f"critical_alerts:{critical_count}")
    if block_on_warning and warning_count > 0:
        reasons.append(f"warning_alerts:{warning_count}")

    passed = len(reasons) == 0
    return {
        "passed": passed,
        "reasons": reasons,
        "trust_event_count": len(trust_events),
        "trust_failure_count": len(trust_failures),
        "critical_alerts": critical_count,
        "warning_alerts": warning_count,
        "parity_status": normalized_parity or "unknown",
    }
