"""
core/youtube_api.py
- YouTube Data API v3 wrapper with multi-key rotation
- Supports user-provided keys (BYOK)
"""

import os
import re
import isodate
from typing import Optional
from dotenv import load_dotenv
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

load_dotenv()


# =====================================================
# Multi-Key Loading (User Keys → .env Fallback)
# =====================================================
def _load_keys() -> list[str]:
    """Load keys — user keys first, then .env fallback"""
    # Priority 1: User keys
    try:
        from core.user_keys import load_user_keys
        user = load_user_keys()
        user_yt = [k for k in (user.get("youtube_keys") or []) if k and k.strip()]
        if user_yt:
            return user_yt
    except Exception:
        pass

    # Priority 2: .env keys
    keys = []
    multi = os.getenv("YOUTUBE_API_KEYS", "")
    if multi:
        keys.extend([k.strip() for k in multi.split(",") if k.strip()])

    i = 1
    while True:
        k = os.getenv(f"YOUTUBE_API_KEY_{i}")
        if not k:
            break
        keys.append(k.strip())
        i += 1

    single = os.getenv("YOUTUBE_API_KEY", "")
    if single and single.strip() and single.strip() not in keys:
        keys.append(single.strip())

    seen, unique = set(), []
    for k in keys:
        if k not in seen:
            seen.add(k)
            unique.append(k)
    return unique


_KEYS = _load_keys()
_current_idx = 0
_services: dict[str, any] = {}


def reload_keys():
    """Reload keys (called after user saves new keys)"""
    global _KEYS, _current_idx, _services
    _KEYS = _load_keys()
    _current_idx = 0
    _services = {}


def get_keys_count() -> int:
    return len(_KEYS)


def _get_service(key: str):
    if key not in _services:
        _services[key] = build("youtube", "v3", developerKey=key, cache_discovery=False)
    return _services[key]


def _rotate() -> bool:
    global _current_idx
    if len(_KEYS) <= 1:
        return False
    _current_idx = (_current_idx + 1) % len(_KEYS)
    return True


def _is_quota_error(e: Exception) -> bool:
    s = str(e).lower()
    return any(x in s for x in [
        "quotaexceeded", "quota exceeded", "quota",
        "403", "429", "ratelimit", "rate limit",
        "dailylimitexceeded", "userratelimitexceeded",
    ])


def _execute(request_builder):
    """Execute a YouTube API request with auto key rotation"""
    if not _KEYS:
        raise RuntimeError(
            "No YouTube API keys found.\n"
            "Add keys in ⚙️ Settings or in .env file."
        )

    last_err = None
    attempts = max(len(_KEYS) * 2, 2)

    for _ in range(attempts):
        key = _KEYS[_current_idx]
        try:
            service = _get_service(key)
            return request_builder(service).execute()
        except HttpError as e:
            last_err = e
            if _is_quota_error(e):
                if _rotate():
                    continue
                break
            else:
                raise
        except Exception as e:
            last_err = e
            break

    raise RuntimeError(f"All YouTube API keys failed. Last error: {last_err}")


# Legacy compatibility
def get_client():
    if not _KEYS:
        raise RuntimeError("YOUTUBE_API_KEY missing in .env")
    return _get_service(_KEYS[_current_idx])


# =====================================================
# URL Parsing
# =====================================================
VIDEO_ID_RE = re.compile(
    r"(?:youtube\.com/(?:watch\?v=|embed/|v/|shorts/)|youtu\.be/)([A-Za-z0-9_-]{11})"
)


def extract_video_id(url: str) -> Optional[str]:
    if not url:
        return None
    url = url.strip()
    if re.fullmatch(r"[A-Za-z0-9_-]{11}", url):
        return url
    m = VIDEO_ID_RE.search(url)
    return m.group(1) if m else None


# =====================================================
# Helpers
# =====================================================
def _parse_duration(iso: str) -> str:
    try:
        d = isodate.parse_duration(iso)
        total = int(d.total_seconds())
        h, r = divmod(total, 3600)
        m, s = divmod(r, 60)
        return f"{h}:{m:02d}:{s:02d}" if h else f"{m}:{s:02d}"
    except Exception:
        return iso


def _format_number(n) -> str:
    try:
        n = int(n)
        if n >= 1_000_000_000:
            return f"{n/1_000_000_000:.2f}B"
        if n >= 1_000_000:
            return f"{n/1_000_000:.2f}M"
        if n >= 1_000:
            return f"{n/1_000:.2f}K"
        return str(n)
    except Exception:
        return str(n)


# =====================================================
# Public API
# =====================================================
def get_video_details(video_id: str) -> dict | None:
    def _req(service):
        return service.videos().list(
            part="snippet,statistics,contentDetails,topicDetails,status",
            id=video_id,
        )

    resp = _execute(_req)
    items = resp.get("items", [])
    if not items:
        return None

    v = items[0]
    sn = v.get("snippet", {})
    st = v.get("statistics", {})
    cd = v.get("contentDetails", {})
    td = v.get("topicDetails", {})

    return {
        "id": v["id"],
        "url": f"https://www.youtube.com/watch?v={v['id']}",
        "title": sn.get("title", ""),
        "description": sn.get("description", ""),
        "channel_id": sn.get("channelId", ""),
        "channel_title": sn.get("channelTitle", ""),
        "published_at": sn.get("publishedAt", ""),
        "thumbnail": sn.get("thumbnails", {}).get("high", {}).get("url", ""),
        "thumbnails": sn.get("thumbnails", {}),
        "tags": sn.get("tags", []),
        "category_id": sn.get("categoryId", ""),
        "default_language": sn.get("defaultLanguage", ""),
        "default_audio_language": sn.get("defaultAudioLanguage", ""),
        "live_broadcast": sn.get("liveBroadcastContent", "none"),
        "duration": _parse_duration(cd.get("duration", "")),
        "duration_iso": cd.get("duration", ""),
        "definition": cd.get("definition", ""),
        "caption": cd.get("caption", "false"),
        "licensed_content": cd.get("licensedContent", False),
        "views": int(st.get("viewCount", 0) or 0),
        "likes": int(st.get("likeCount", 0) or 0),
        "comments": int(st.get("commentCount", 0) or 0),
        "favorites": int(st.get("favoriteCount", 0) or 0),
        "views_fmt": _format_number(st.get("viewCount", 0)),
        "likes_fmt": _format_number(st.get("likeCount", 0)),
        "comments_fmt": _format_number(st.get("commentCount", 0)),
        "topics": td.get("topicCategories", []),
    }


def search_videos(query: str, max_results: int = 25,
                  order: str = "relevance",
                  region: str = "US") -> list[dict]:
    def _req(service):
        return service.search().list(
            part="snippet",
            q=query,
            type="video",
            maxResults=max_results,
            order=order,
            regionCode=region,
        )

    resp = _execute(_req)
    out = []
    for it in resp.get("items", []):
        sn = it["snippet"]
        out.append({
            "id": it["id"]["videoId"],
            "url": f"https://www.youtube.com/watch?v={it['id']['videoId']}",
            "title": sn.get("title", ""),
            "channel": sn.get("channelTitle", ""),
            "published_at": sn.get("publishedAt", ""),
            "description": sn.get("description", ""),
            "thumbnail": sn.get("thumbnails", {}).get("medium", {}).get("url", ""),
        })
    return out


def get_trending_videos(region: str = "US", category: str = "0",
                        max_results: int = 25) -> list[dict]:
    params = {
        "part": "snippet,statistics,contentDetails",
        "chart": "mostPopular",
        "regionCode": region,
        "maxResults": max_results,
    }
    if category and category != "0":
        params["videoCategoryId"] = category

    def _req(service):
        return service.videos().list(**params)

    resp = _execute(_req)
    out = []
    for v in resp.get("items", []):
        sn = v["snippet"]
        st = v.get("statistics", {})
        cd = v.get("contentDetails", {})
        out.append({
            "id": v["id"],
            "url": f"https://www.youtube.com/watch?v={v['id']}",
            "title": sn.get("title", ""),
            "channel": sn.get("channelTitle", ""),
            "published_at": sn.get("publishedAt", ""),
            "description": sn.get("description", ""),
            "thumbnail": sn.get("thumbnails", {}).get("medium", {}).get("url", ""),
            "views": int(st.get("viewCount", 0) or 0),
            "likes": int(st.get("likeCount", 0) or 0),
            "comments": int(st.get("commentCount", 0) or 0),
            "duration": _parse_duration(cd.get("duration", "")),
            "views_fmt": _format_number(st.get("viewCount", 0)),
            "likes_fmt": _format_number(st.get("likeCount", 0)),
        })
    return out


def get_video_categories(region: str = "US") -> list[dict]:
    try:
        def _req(service):
            return service.videoCategories().list(part="snippet", regionCode=region)

        resp = _execute(_req)
        return [
            {"id": it["id"], "title": it["snippet"]["title"]}
            for it in resp.get("items", [])
            if it["snippet"].get("assignable", True)
        ]
    except Exception:
        return []


def get_channel_details(channel_id: str) -> dict | None:
    try:
        def _req(service):
            return service.channels().list(part="snippet,statistics", id=channel_id)

        resp = _execute(_req)
        items = resp.get("items", [])
        if not items:
            return None
        c = items[0]
        return {
            "id": c["id"],
            "title": c["snippet"]["title"],
            "description": c["snippet"].get("description", ""),
            "subscribers": int(c.get("statistics", {}).get("subscriberCount", 0) or 0),
            "videos": int(c.get("statistics", {}).get("videoCount", 0) or 0),
            "views": int(c.get("statistics", {}).get("viewCount", 0) or 0),
            "thumbnail": c["snippet"].get("thumbnails", {}).get("medium", {}).get("url", ""),
        }
    except Exception:
        return None