"""Image fallback chain: source-provided -> og:image scrape -> Unsplash thematic."""

from __future__ import annotations

import re
import sys
from urllib.parse import urlparse, quote

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

# Unsplash Source (free, no API key, returns a redirect to a photo)
# https://source.unsplash.com/featured/400x200?{query}
_UNSPLASH_BASE = "https://images.unsplash.com/photo-"

# Curated Unsplash photo IDs per category for reliable, good-looking fallbacks
_CATEGORY_PHOTOS = {
    "AI":         "https://images.unsplash.com/photo-1677442136019-21780ecad995?w=400&h=200&fit=crop",
    "Physics":    "https://images.unsplash.com/photo-1462331940025-496dfbfc7564?w=400&h=200&fit=crop",
    "Business":   "https://images.unsplash.com/photo-1486406146926-c627a92ad1ab?w=400&h=200&fit=crop",
    "Food":       "https://images.unsplash.com/photo-1504674900247-0877df9cc836?w=400&h=200&fit=crop",
    "Culture":    "https://images.unsplash.com/photo-1533174072545-7a4b6ad7a6c3?w=400&h=200&fit=crop",
    "Trivia":     "https://images.unsplash.com/photo-1457369804613-52c61a468e7d?w=400&h=200&fit=crop",
    "Cats":       "https://images.unsplash.com/photo-1514888286974-6c03e2ca1dba?w=400&h=200&fit=crop",
    "Crafts":     "https://images.unsplash.com/photo-1452587925148-ce544e77e70d?w=400&h=200&fit=crop",
    "Korean":     "https://images.unsplash.com/photo-1517154421773-0529f29ea451?w=400&h=200&fit=crop",
    "Beauty":     "https://images.unsplash.com/photo-1596462502278-27bfdc403348?w=400&h=200&fit=crop",
    "Chemistry":  "https://images.unsplash.com/photo-1532187863486-abf9dbad1b69?w=400&h=200&fit=crop",
}

_DEFAULT_PHOTO = "https://images.unsplash.com/photo-1451187580459-43490279c0fa?w=400&h=200&fit=crop"

# Regex to extract og:image from HTML — fast, doesn't need a parser
_OG_IMAGE_RE = re.compile(
    r'<meta\s+(?:[^>]*?\s+)?'
    r'(?:property=["\']og:image["\']|name=["\']og:image["\'])'
    r'\s+(?:[^>]*?\s+)?content=["\']([^"\']+)["\']',
    re.IGNORECASE,
)
_OG_IMAGE_RE2 = re.compile(
    r'<meta\s+(?:[^>]*?\s+)?'
    r'content=["\']([^"\']+)["\']'
    r'\s+(?:[^>]*?\s+)?'
    r'(?:property=["\']og:image["\']|name=["\']og:image["\'])',
    re.IGNORECASE,
)

# Skip domains where og:image scraping is pointless or slow
_SKIP_DOMAINS = {
    "news.ycombinator.com",
    "lobste.rs",
    "reddit.com", "www.reddit.com", "old.reddit.com",
}


def scrape_og_image(url: str, fetcher: Fetcher) -> str:
    """Try to extract og:image from a URL. Returns image URL or empty string."""
    try:
        domain = urlparse(url).netloc.lower()
        if domain in _SKIP_DOMAINS:
            return ""
        # Only read first 50KB to find the meta tag quickly
        resp = fetcher.get(url)
        if not resp:
            return ""
        # Only look in the head section (first 50k chars)
        html = resp.text[:50000]
        match = _OG_IMAGE_RE.search(html) or _OG_IMAGE_RE2.search(html)
        if match:
            img_url = match.group(1).strip()
            # Decode HTML entities
            img_url = img_url.replace("&amp;", "&")
            if img_url.startswith("http"):
                return img_url
    except Exception:
        pass
    return ""


def get_category_image(category: str) -> str:
    """Return a curated Unsplash photo URL for a category."""
    return _CATEGORY_PHOTOS.get(category, _DEFAULT_PHOTO)


def enrich_images(items: list[Item], fetcher: Fetcher, max_scrapes: int = 20):
    """Fill in missing images using og:image scraping + category fallbacks.

    Mutates items in place.
    """
    scrape_count = 0
    scraped = 0

    for item in items:
        if item.image_url:
            continue

        # Try og:image scraping (limited to avoid slowing things down)
        if scrape_count < max_scrapes:
            scrape_count += 1
            og_img = scrape_og_image(item.url, fetcher)
            if og_img:
                item.image_url = og_img
                scraped += 1
                continue

        # Fallback: themed Unsplash photo for the category
        item.image_url = get_category_image(item.category)

    print(f"  Images: {scraped} scraped via og:image, "
          f"{sum(1 for i in items if i.image_url)} total with images")
