"""Which weather source answered, and the attributions their licences ask
for (AV-051): Open-Meteo (CC BY 4.0) and MET Norway (CC BY 4.0), read from
each answer's own provenance (``variable_models``)."""

from __future__ import annotations

from typing import Any

OPEN_METEO_ATTRIBUTION = "Weather data by Open-Meteo.com (CC BY 4.0)"
MET_NORWAY_ATTRIBUTION = "Dane: MET Norway (CC BY 4.0)"


def budget_document() -> dict[str, Any]:
    """AV-052: the weather services' levels when any is past GREEN (the page
    says what is held back), and when the day's limits renew."""
    from mountain_twin import budgets

    levels = {service: budgets.level(service) for service in ("open_meteo", "met_norway")}
    if all(value == "GREEN" for value in levels.values()):
        return {"service_budget": None}
    return {"service_budget": {"levels": levels, "renews_at": budgets.renews_at()}}


def sources_document(answers) -> dict[str, Any]:
    """{"sources": {"open_meteo": n, "met_norway": m}, "attributions": [...]}
    over (sample, failure) answers."""
    counts = {"open_meteo": 0, "met_norway": 0}
    for sample, _ in answers:
        if sample is None:
            continue
        models = dict(sample.variable_models).values()
        counts["met_norway" if "met_norway" in models else "open_meteo"] += 1
    attributions = []
    if counts["open_meteo"]:
        attributions.append(OPEN_METEO_ATTRIBUTION)
    if counts["met_norway"]:
        attributions.append(MET_NORWAY_ATTRIBUTION)
    return {"sources": counts, "attributions": attributions}
