import logging
import re
from typing import Optional

import requests
from django.conf import settings
from videos.metadata import VideoMetadata, VideoType

logger = logging.getLogger(__name__)

OMDB_API_KEY = getattr(settings, "OMDB_API_KEY", "")

OMDB_URL = "https://www.omdbapi.com/"
RUNTIME_RE = re.compile(r"(\d+)\s*min")


def lookup_video_from_omdb(imdb_id: str) -> Optional[VideoMetadata]:
    if not imdb_id.startswith("tt"):
        imdb_id = f"tt{imdb_id}"

    if not OMDB_API_KEY:
        logger.warning("No OMDB API key configured")
        return None

    params = {"apikey": OMDB_API_KEY, "i": imdb_id, "plot": "full"}

    try:
        response = requests.get(OMDB_URL, params=params)
        response.raise_for_status()
        data = response.json()
    except requests.exceptions.RequestException as e:
        logger.error(f"OMDB API error for {imdb_id}: {e}")
        return None

    if data.get("Response") == "False":
        logger.info(f"OMDB no result for {imdb_id}: {data.get('Error')}")
        return None

    metadata = VideoMetadata(imdb_id=imdb_id)
    metadata.title = data.get("Title")
    metadata.plot = data.get("Plot")
    metadata.overview = data.get("Plot")

    raw_year = data.get("Year")
    if raw_year and raw_year.isdigit():
        metadata.year = int(raw_year)

    raw_rating = data.get("imdbRating")
    if raw_rating and raw_rating != "N/A":
        metadata.imdb_rating = raw_rating

    raw_cover = data.get("Poster")
    if raw_cover and raw_cover != "N/A":
        metadata.cover_url = raw_cover

    raw_runtime = data.get("Runtime")
    if raw_runtime:
        match = RUNTIME_RE.match(raw_runtime)
        if match:
            metadata.base_run_time_seconds = int(match.group(1)) * 60

    media_type = data.get("Type")
    if media_type == "movie":
        metadata.video_type = VideoType.MOVIE.value
    elif media_type in ("series", "episode"):
        metadata.video_type = VideoType.TV_EPISODE.value

    if media_type == "episode":
        raw_season = data.get("Season")
        if raw_season and raw_season != "N/A":
            metadata.season_number = int(raw_season)
        raw_episode = data.get("Episode")
        if raw_episode and raw_episode != "N/A":
            metadata.episode_number = int(raw_episode)
        series_imdb_id = data.get("seriesID")
        if series_imdb_id and series_imdb_id != "N/A":
            metadata.tv_series_imdb_id = series_imdb_id

    raw_genres = data.get("Genre")
    if raw_genres:
        metadata.genres = [g.strip() for g in raw_genres.split(",") if g.strip()]

    return metadata
