# Familiar - Self-Hosted AI Companion Platform
# Copyright (c) 2026 George Scott Foley
# ORCID: 0009-0006-4957-0540
# Email: Georgescottfoley@proton.me
# Licensed under the MIT License - see LICENSE file for details

"""
Radio Browser API client.

Free API, no auth, no rate limit.
Docs: https://de1.api.radio-browser.info/
"""

from __future__ import annotations

import logging

from familiar.core.api_cache import cached
from familiar.skills._api_utils import APIError, api_get

logger = logging.getLogger(__name__)

RADIO_BROWSER_BASE = "https://de1.api.radio-browser.info"
_HEADERS = {"User-Agent": "Familiar/1.14.60"}


def _format_station(station: dict) -> dict:
    """Normalize a Radio Browser station response."""
    tags_raw = station.get("tags", "")
    tags = [t.strip() for t in tags_raw.split(",") if t.strip()] if tags_raw else []
    return {
        "id": station.get("stationuuid", ""),
        "name": station.get("name", "").strip(),
        "stream_url": station.get("url_resolved") or station.get("url", ""),
        "favicon": station.get("favicon", ""),
        "tags": tags,
        "country": station.get("country", ""),
        "codec": station.get("codec", ""),
        "bitrate": station.get("bitrate", 0),
        "votes": station.get("votes", 0),
    }


@cached(prefix="radio_search", ttl=300)
def search_stations(
    name: str = "",
    tag: str = "",
    country: str = "",
    limit: int = 25,
) -> list[dict]:
    """Search radio stations by name, tag, or country."""
    params: dict = {
        "limit": min(limit, 100),
        "hidebroken": "true",
        "order": "votes",
        "reverse": "true",
    }
    if name:
        params["name"] = name
    if tag:
        params["tag"] = tag
    if country:
        params["country"] = country

    try:
        data = api_get(
            f"{RADIO_BROWSER_BASE}/json/stations/search",
            headers=_HEADERS,
            params=params,
            service_name="Radio Browser",
        )
        if isinstance(data, list):
            return [_format_station(s) for s in data]
        return []
    except APIError as e:
        logger.warning("Radio search failed: %s", e)
        return []


@cached(prefix="radio_genres", ttl=3600)
def get_genres(limit: int = 50) -> list[dict]:
    """Get popular genre tags with station counts."""
    try:
        data = api_get(
            f"{RADIO_BROWSER_BASE}/json/tags",
            headers=_HEADERS,
            params={
                "order": "stationcount",
                "reverse": "true",
                "limit": min(limit, 200),
                "hidebroken": "true",
            },
            service_name="Radio Browser",
        )
        if isinstance(data, list):
            return [
                {"name": t.get("name", ""), "stationcount": t.get("stationcount", 0)}
                for t in data
                if t.get("name", "").strip()
            ]
        return []
    except APIError as e:
        logger.warning("Radio genres failed: %s", e)
        return []


@cached(prefix="radio_popular", ttl=300)
def get_popular(limit: int = 25) -> list[dict]:
    """Get popular stations sorted by votes."""
    try:
        data = api_get(
            f"{RADIO_BROWSER_BASE}/json/stations/search",
            headers=_HEADERS,
            params={
                "order": "votes",
                "reverse": "true",
                "limit": min(limit, 100),
                "hidebroken": "true",
            },
            service_name="Radio Browser",
        )
        if isinstance(data, list):
            return [_format_station(s) for s in data]
        return []
    except APIError as e:
        logger.warning("Radio popular failed: %s", e)
        return []
