"""Shared release-gate summarization for live kernel batteries.

Gate mode: exit nonzero only on hard gating failures. Flaky passes (agent battery)
and monitor-only failures (delivery battery) are reported but do not fail the gate.
"""
from __future__ import annotations

from typing import Any, Protocol


class _GateResult(Protocol):
    passed: bool
    flaky: bool
    monitor_only: bool
    skipped: bool


def summarize_agent_results(results: list[Any]) -> dict[str, Any]:
    """Agent battery gate summary.

    Flaky cases passed on retry (``passed=True``, ``flaky=True``) are non-gating.
    """
    hard_failed = [r for r in results if not r.passed]
    flaky = [r for r in results if r.passed and getattr(r, "flaky", False)]
    passed = [r for r in results if r.passed and not getattr(r, "flaky", False)]
    return {
        "passed": len(passed),
        "flaky": len(flaky),
        "failed": len(hard_failed),
        "total": len(results),
        "hard_failed": hard_failed,
        "flaky_cases": flaky,
        "exit_code": 0 if not hard_failed else 1,
    }


def summarize_worker_results(results: list[Any]) -> dict[str, Any]:
    """Worker battery gate summary.

    Flaky cases passed on retry (``passed=True``, ``flaky=True``) are non-gating.
    """
    hard_failed = [r for r in results if not r.passed]
    flaky = [r for r in results if r.passed and getattr(r, "flaky", False)]
    passed = [r for r in results if r.passed and not getattr(r, "flaky", False)]
    return {
        "passed": len(passed),
        "flaky": len(flaky),
        "failed": len(hard_failed),
        "total": len(results),
        "hard_failed": hard_failed,
        "flaky_cases": flaky,
        "exit_code": 0 if not hard_failed else 1,
    }


def format_gate_summary_line(label: str, summary: dict[str, Any]) -> str:
    """One-line gate summary for stdout."""
    flaky = summary.get("flaky", 0)
    flaky_note = f", {flaky} flaky (non-gating)" if flaky else ""
    return (
        f"GATE {label}: {summary['passed']}/{summary['total']} passed, "
        f"{summary['failed']} failed{flaky_note}"
    )
