"""Trivia sources — Wikimedia On This Day + random facts. Free, no API key."""

from __future__ import annotations

import json
from datetime import datetime

from platoon.models import Item
from platoon.fetcher import Fetcher


def fetch_trivia(cfg: dict, fetcher: Fetcher) -> list[Item]:
    """Fetch trivia items: On This Day events + random facts."""
    max_items = cfg.get("max_items", 8)
    items = []

    # 1. Wikimedia "On This Day"
    if cfg.get("on_this_day", True):
        items.extend(_fetch_on_this_day(fetcher, max_items // 2 + 2))

    # 2. Useless Facts
    if cfg.get("random_facts", True):
        items.extend(_fetch_random_facts(fetcher, max_items // 2))

    return items[:max_items]


def _fetch_on_this_day(fetcher: Fetcher, max_items: int) -> list[Item]:
    """Fetch Wikimedia 'On This Day' events."""
    now = datetime.now()
    url = f"https://api.wikimedia.org/feed/v1/wikipedia/en/onthisday/all/{now.month:02d}/{now.day:02d}"
    print("Fetching Wikimedia On This Day...")
    resp = fetcher.get(url)
    if not resp:
        return []

    data = resp.json()
    items = []

    # Combine events + births + deaths, prefer events
    for section in ["events", "births", "deaths"]:
        for entry in data.get(section, []):
            if len(items) >= max_items:
                break
            text = entry.get("text", "")
            year = entry.get("year", "")
            pages = entry.get("pages", [])

            # Get the first Wikipedia page link and thumbnail
            url = ""
            image_url = ""
            if pages:
                page = pages[0]
                url = page.get("content_urls", {}).get("desktop", {}).get("page", "")
                thumb = page.get("thumbnail", {})
                if thumb:
                    image_url = thumb.get("source", "")

            prefix = f"On this day in {year}: " if year else "On this day: "
            items.append(Item(
                title=f"{prefix}{text[:100]}",
                url=url or f"https://en.wikipedia.org/wiki/{now.strftime('%B_%d')}",
                source="On This Day",
                summary=text[:400],
                image_url=image_url,
                tags=["history", "trivia"],
                engagement={},
            ))

    print(f"  -> {len(items)} items")
    return items


def _fetch_random_facts(fetcher: Fetcher, max_items: int) -> list[Item]:
    """Fetch random fun facts from uselessfacts API."""
    print("Fetching random facts...")
    items = []
    for _ in range(max_items):
        resp = fetcher.get("https://uselessfacts.jsph.pl/random.json?language=en")
        if not resp:
            break
        data = resp.json()
        text = data.get("text", "")
        source_url = data.get("source_url", "")
        if text:
            items.append(Item(
                title=text[:120],
                url=source_url or "https://uselessfacts.jsph.pl/",
                source="Fun Fact",
                summary=text,
                tags=["trivia", "fun fact"],
            ))

    print(f"  -> {len(items)} items")
    return items
