"""Mail-V2 scope filter — drop MC findings that don't apply.

Some MC-DB entries are sector-specific (FIN = financial services,
GOV = public authority, MED = healthcare, INS = insurance, EDU =
education, LEG = legal profession). They have no business surfacing
for a normal B2C company like Elli (energy/EV charging).

This filter inspects the MC ID prefix and, when the prefix denotes
a sector that doesn't match the detected `business_scope`, drops the
check from the V2 finding renderers.

The MC pipeline itself is unchanged — MCs are still evaluated; we
just suppress them in the report when out of scope. Set
`KEEP_OOS_MCS=true` in the env to disable the filter (useful for
DSB debug runs).
"""

from __future__ import annotations

import os

# Prefix -> sector token expected in business_scope to KEEP the check.
SECTOR_PREFIXES: dict[str, set[str]] = {
    "FIN": {"financial_services", "bank", "bafin", "fintech",
            "payment_provider"},
    "GOV": {"public_authority", "government", "behoerde"},
    "MED": {"healthcare", "medical", "pharma", "klinik"},
    "INS": {"insurance", "versicherung"},
    "EDU": {"education", "schule", "hochschule", "university"},
    "LEG": {"legal_profession", "anwaltskammer", "kanzlei"},
    "REL": {"church", "religion", "religious"},
    "POL": {"political_party", "partei"},
}

# Cheap counter so the renderer can show "X MCs gefiltert (out of scope)".
_LAST_DROPPED: dict[str, int] = {"count": 0, "by_prefix": {}}


def _enabled() -> bool:
    return os.environ.get("KEEP_OOS_MCS", "false").lower() not in (
        "true", "1", "yes", "on",
    )


def _extract_prefix(check_id: str) -> str | None:
    """Return the sector prefix (e.g. 'FIN') from mc-FIN-814-A03."""
    if not check_id:
        return None
    parts = check_id.split("-")
    # mc-XXX-NNN-AYY → parts = ["mc", "XXX", "NNN", "AYY"]
    if len(parts) >= 2 and parts[0].lower() == "mc":
        prefix = parts[1].upper()
        if prefix in SECTOR_PREFIXES:
            return prefix
    return None


def is_out_of_scope(check, business_scope: set[str] | None) -> bool:
    """Decide whether the check is sector-specific AND out of scope."""
    if not _enabled():
        return False
    prefix = _extract_prefix(getattr(check, "id", "") or "")
    if not prefix:
        return False
    required = SECTOR_PREFIXES.get(prefix) or set()
    scope_lc = {s.lower() for s in (business_scope or set())}
    return not (scope_lc & required)


def filter_out_of_scope(checks, business_scope: set[str] | None) -> list:
    """Return `checks` with out-of-scope items removed; mutates counter."""
    _LAST_DROPPED["count"] = 0
    _LAST_DROPPED["by_prefix"] = {}
    out = []
    for c in checks:
        if is_out_of_scope(c, business_scope):
            _LAST_DROPPED["count"] += 1
            prefix = _extract_prefix(getattr(c, "id", "") or "") or "?"
            _LAST_DROPPED["by_prefix"][prefix] = (
                _LAST_DROPPED["by_prefix"].get(prefix, 0) + 1
            )
            continue
        out.append(c)
    return out


def get_last_drop_stats() -> dict:
    return dict(_LAST_DROPPED)
