"""发布复核标签的独立人员票数归并。"""

from __future__ import annotations

from collections.abc import Iterable
from dataclasses import dataclass
from typing import Any

_CANONICAL_LABELS = {
    "confirmed": "confirmed",
    "risk_present": "confirmed",
    "false_positive": "false_positive",
    "risk_absent": "false_positive",
}


@dataclass(frozen=True, slots=True)
class ReleaseLabelVoteState:
    label: str | None
    reviewer_count: int
    required_reviewers: int
    conflicted: bool


def resolve_release_label_votes(
    labels: Iterable[Any],
    *,
    required_reviewers: int,
    required_reviewers_by_observation: dict[str, int] | None = None,
) -> dict[str, ReleaseLabelVoteState]:
    default_quorum = max(1, min(2, int(required_reviewers)))
    quorum_by_observation = required_reviewers_by_observation or {}
    latest_by_actor: dict[tuple[str, str], str] = {}
    for item in labels:
        observation_id = str(item.observation_id)
        actor = str(item.actor_fingerprint)
        label = _CANONICAL_LABELS.get(str(item.label))
        if label is not None:
            latest_by_actor[(observation_id, actor)] = label

    votes: dict[str, dict[str, int]] = {}
    reviewers: dict[str, int] = {}
    for (observation_id, _actor), label in latest_by_actor.items():
        reviewers[observation_id] = reviewers.get(observation_id, 0) + 1
        bucket = votes.setdefault(observation_id, {})
        bucket[label] = bucket.get(label, 0) + 1

    states: dict[str, ReleaseLabelVoteState] = {}
    for observation_id, counts in votes.items():
        quorum = max(
            1,
            min(2, int(quorum_by_observation.get(observation_id, default_quorum))),
        )
        eligible = [label for label, count in counts.items() if count >= quorum]
        states[observation_id] = ReleaseLabelVoteState(
            label=eligible[0] if len(eligible) == 1 else None,
            reviewer_count=reviewers[observation_id],
            required_reviewers=quorum,
            conflicted=len(counts) > 1,
        )
    return states


def release_reviewer_quorum(state: dict[str, Any]) -> int:
    policy = state.get("policy") if isinstance(state.get("policy"), dict) else {}
    try:
        return max(1, min(2, int(policy.get("reviewer_quorum") or 1)))
    except (TypeError, ValueError, OverflowError):
        return 1
