from backend.app.db.models.recommendations import InstalledMeasure
from typing import Dict, List, Set
from collections import defaultdict


def get_installed_measure_types_by_uprns(
    session,
    uprns: List[int],
) -> Dict[int, Set[str]]:
    """
    Returns installed measure types per UPRN.

    {
        uprn: {"cavity_wall_insulation", "mechanical_ventilation", ...}
    }
    """

    if not uprns:
        return {}

    rows = (
        session.query(
            InstalledMeasure.uprn,
            InstalledMeasure.measure_type,
        )
        .filter(InstalledMeasure.is_active.is_(True))
        .filter(InstalledMeasure.uprn.in_(uprns))
        .all()
    )

    out: Dict[int, Set[str]] = defaultdict(set)

    for uprn, measure_type in rows:
        out[uprn].add(
            measure_type.value
            if hasattr(measure_type, "value")
            else measure_type
        )

    return out
