from __future__ import annotations

from typing import Any


_DEDUPED_BUDGET_RISK_EVENT_TYPES = {
    "budget_frozen",
    "budget_insufficient",
    "budget_missing",
    "budget_warning",
}


def dedupe_budget_risk_flags(flags: list[Any] | None) -> list[Any]:
    """Collapse repeated budget risk warnings while preserving non-risk audit flags."""

    deduped: list[Any] = []
    key_to_index: dict[tuple[str, str, str, str], int] = {}

    for flag in list(flags or []):
        key = budget_risk_flag_key(flag)
        if key is None:
            deduped.append(flag)
            continue
        existing_index = key_to_index.get(key)
        if existing_index is None:
            key_to_index[key] = len(deduped)
            deduped.append(flag)
            continue
        deduped[existing_index] = flag

    return deduped


def budget_risk_flag_key(flag: Any) -> tuple[str, str, str, str] | None:
    if not isinstance(flag, dict):
        return None

    source = str(flag.get("source") or "").strip()
    event_type = str(flag.get("event_type") or flag.get("eventType") or "").strip()
    if source != "budget_control" or event_type not in _DEDUPED_BUDGET_RISK_EVENT_TYPES:
        return None

    allocation_key = str(flag.get("allocation_id") or flag.get("allocationId") or "").strip()
    budget_no = str(flag.get("budget_no") or flag.get("budgetNo") or "").strip()
    subject_code = str(flag.get("subject_code") or flag.get("subjectCode") or "").strip()
    return (source, event_type, allocation_key or budget_no, subject_code)
