"""Strommix und erneuerbare Energien — Quellen-Aufschlüsselung.

Nutzt:
- Carbon Intensity UK API (kostenlos, kein Key) für UK-Strommix
- Electricity Maps API (optional, mit Key) für globalen Mix
- SMARD API (kein Key) für deutschen Strommix
"""

import httpx
from mcp.server.fastmcp import FastMCP
from src.config import (
    CARBON_INTENSITY_BASE,
    ELECTRICITY_MAPS_BASE,
    ELECTRICITY_MAPS_TOKEN,
    SMARD_BASE,
)

# SMARD Indikator-IDs für die relevanten Quellen
SMARD_INDICATORS = {
    "photovoltaik": 4068,
    "wind_offshore": 1225,
    "wind_onshore": 4067,
    "biomasse": 4066,
    "wasserkraft": 1226,
    "sonstige_erneuerbare": 1228,
    "kernenergie": 1224,
    "braunkohle": 1223,
    "steinkohle": 4069,
    "erdgas": 4071,
    "pumpspeicher": 4070,
    "sonstige_konventionelle": 1227,
}


def register_power_mix_tools(mcp: FastMCP) -> None:
    """Registriert Strommix-Tools."""

    @mcp.tool()
    async def get_uk_power_mix() -> dict:
        """Aktueller Strommix des britischen Netzes — Erneuerbare vs. Fossil.

        Returns:
            Anteil jeder Energiequelle (%) inkl. Wind, Solar, Nuclear, Gas, Coal.
            Keine API-Registrierung nötig.
        """
        async with httpx.AsyncClient(timeout=15) as client:
            resp = await client.get(f"{CARBON_INTENSITY_BASE}/generation")
            resp.raise_for_status()
            data = resp.json()
            generation_mix = data.get("data", {}).get("generationmix", [])

        result = {source["fuel"]: source["perc"] for source in generation_mix}

        # Zusammenfassung: Erneuerbare Summe
        renewable_sources = ["wind", "solar", "hydro", "biomass", "nuclear"]
        renewable_pct = sum(result.get(s, 0) for s in renewable_sources)

        return {
            "mix": result,
            "erneuerbare_gesamt_pct": round(renewable_pct, 1),
            "fossil_gesamt_pct": round(100 - renewable_pct, 1),
            "quelle": "Carbon Intensity UK API",
        }

    @mcp.tool()
    async def get_renewable_percentage_uk(region: str = "") -> dict:
        """Prozentualer Anteil erneuerbarer Energien im UK-Stromnetz.

        Args:
            region: Optional — UK-Region für regionalen Vergleich.

        Returns:
            Aktueller Anteil erneuerbarer Energien inkl. Trend-Einschätzung.
        """
        async with httpx.AsyncClient(timeout=15) as client:
            if region:
                resp = await client.get(f"{CARBON_INTENSITY_BASE}/regional")
                resp.raise_for_status()
                data = resp.json()
                regions = data.get("data", [{}])[0].get("regions", [])
                for r in regions:
                    if region.lower() in r.get("shortname", "").lower() or \
                       region.lower() in r.get("dnoregion", "").lower():
                        mix = r.get("generationmix", [])
                        renewable = sum(
                            s["perc"] for s in mix
                            if s["fuel"] in ["wind", "solar", "hydro", "biomass", "nuclear"]
                        )
                        return {
                            "region": r.get("dnoregion"),
                            "erneuerbare_pct": round(renewable, 1),
                            "mix": {s["fuel"]: s["perc"] for s in mix},
                        }
            else:
                resp = await client.get(f"{CARBON_INTENSITY_BASE}/generation")
                resp.raise_for_status()
                data = resp.json()
                mix = data.get("data", {}).get("generationmix", [])
                renewable = sum(
                    s["perc"] for s in mix
                    if s["fuel"] in ["wind", "solar", "hydro", "biomass", "nuclear"]
                )
                return {
                    "region": "United Kingdom (national)",
                    "erneuerbare_pct": round(renewable, 1),
                    "mix": {s["fuel"]: s["perc"] for s in mix},
                }

        return {"error": "Daten nicht verfügbar"}

    @mcp.tool()
    async def get_global_power_mix(zone: str) -> dict:
        """Strommix für eine globale Zone (benötigt ELECTRICITY_MAPS_TOKEN).

        Args:
            zone: Zone-Code, z.B. 'DE', 'FR', 'ES', 'US-CAL-CISO'.

        Returns:
            Aufschlüsselung der Stromerzeugung nach Quelle (MW).
        """
        if not ELECTRICITY_MAPS_TOKEN:
            return {
                "error": "ELECTRICITY_MAPS_TOKEN nicht gesetzt.",
                "hinweis": "Kostenlosen Token unter https://api-portal.electricitymaps.com registrieren.",
            }

        async with httpx.AsyncClient(
            timeout=15,
            headers={"auth-token": ELECTRICITY_MAPS_TOKEN},
        ) as client:
            resp = await client.get(
                f"{ELECTRICITY_MAPS_BASE}/power-breakdown/latest",
                params={"zone": zone},
            )
            resp.raise_for_status()
            data = resp.json()

            production = data.get("powerProductionBreakdown", {})
            total = sum(v for v in production.values() if v)
            renewable_sources = ["wind", "solar", "hydro", "geothermal", "biomass", "nuclear"]
            renewable_mw = sum(production.get(s, 0) or 0 for s in renewable_sources)

            return {
                "zone": zone,
                "produktion_mw": production,
                "erneuerbare_mw": renewable_mw,
                "erneuerbare_pct": round(renewable_mw / total * 100, 1) if total else 0,
                "datetime": data.get("datetime"),
            }
