from __future__ import annotations

from datetime import datetime, timezone
from typing import Any


def analytics_envelope(
    data: dict[str, Any],
    *,
    view: str,
    filters: dict[str, Any] | None = None,
    totals: dict[str, Any] | None = None,
    series: list[Any] | None = None,
    rows: list[Any] | None = None,
    warnings: list[Any] | None = None,
    errors: list[Any] | None = None,
) -> dict[str, Any]:
    """Attach a backwards-compatible Budget Analytics envelope.

    Legacy keys stay in the returned mapping so existing frontend/tests can migrate
    gradually. New consumers should prefer meta/filters_applied/totals/series/rows.
    """
    return data | {
        "meta": {
            "view": view,
            "generated_at": datetime.now(timezone.utc).isoformat(),
            "currency": "CHF",
        },
        "filters_applied": {k: v for k, v in (filters or {}).items() if v not in (None, "")},
        "totals": totals or {},
        "series": series or [],
        "rows": rows or [],
        "warnings": warnings or [],
        "errors": errors or [],
    }
