import logging
import os

import pendulum
from django.conf import settings
from themoviedb import TMDb
from tmdbv3api import TV, Movie
from videos.metadata import VideoMetadata, VideoType

TMDB_KEY = getattr(settings, "TMDB_API_KEY", "")

os.environ.setdefault("TMDB_API_KEY", TMDB_KEY)

tmdb = TMDb(key=TMDB_KEY, language="en-US", region="US")

TMDB_IMAGE_URL = "https://image.tmdb.org/t/p/original"

logger = logging.getLogger(__name__)


def lookup_video_from_tmdb(name_or_id: str, kind: str = "movie") -> VideoMetadata:
    from videos.models import Series

    imdb_id = name_or_id
    video_metadata = VideoMetadata(imdb_id=imdb_id)

    tmdb_result = tmdb.find().by_imdb(imdb_id)

    if not tmdb_result:
        logger.info(
            "[lookup_video_from_tmdb] no video found on tmdb",
            extra={"name_or_id": name_or_id},
        )
        return None

    video_metadata = VideoMetadata(imdb_id=imdb_id)

    media = None
    show_data = None
    if len(tmdb_result.movie_results) > 0:
        media = Movie().details(tmdb_result.movie_results[0].id)
        video_metadata.video_type = VideoType.MOVIE.value
        video_metadata.title = media.title
        video_metadata.cover_url = (
            TMDB_IMAGE_URL + media.poster_path
        )  # TODO: enrich this with TMDB url
        video_metadata.year = pendulum.parse(media.release_date).year
        video_metadata.genres = [g.get("name", "") for g in media.genres]
        video_metadata.tmdb_id = media.id
        video_metadata.base_run_time_seconds = media.runtime * 60
        video_metadata.plot = media.overview
        video_metadata.overview = media.overview
        video_metadata.tmdb_rating = media.vote_average

    if len(tmdb_result.tv_results) > 0:
        media = TV().details(tmdb_result.tv_results[0].id)
        video_metadata.video_type = VideoType.TV_EPISODE.value
        video_metadata.title = media.name
        video_metadata.cover_url = (
            TMDB_IMAGE_URL + media.poster_path
        )
        video_metadata.year = pendulum.parse(media.first_air_date).year if media.first_air_date else None
        video_metadata.genres = [g.get("name", "") for g in media.genres]
        video_metadata.tmdb_id = media.id
        video_metadata.base_run_time_seconds = (
            media.episode_run_time[0] * 60 if media.episode_run_time else 1800
        )
        video_metadata.plot = media.overview
        video_metadata.overview = media.overview
        video_metadata.tmdb_rating = media.vote_average

    if len(tmdb_result.tv_episode_results) > 0:
        video_metadata.video_type = VideoType.TV_EPISODE.value
        media = tmdb_result.tv_episode_results[0]
        video_metadata.title = media.name
        video_metadata.cover_url = (
            TMDB_IMAGE_URL + media.still_path
        )  # TODO: enrich this with TMDB url
        video_metadata.episode_number = media.episode_number
        video_metadata.season_number = media.season_number
        video_metadata.year = media.air_date.year

        series_imdb_id = TV().external_ids(media.show_id).imdb_id
        series, created = Series.objects.get_or_create(imdb_id=series_imdb_id)
        if created:
            show_data = TV().details(tv_id=media.show_id)
            series.name = show_data.name
            series.save()
        video_metadata.tv_series_id = series.id

        video_metadata.tmdb_id = media.id
        video_metadata.plot = media.overview
        video_metadata.overview = media.overview

    if not media:
        logger.warning("Video not found on TMDB", extra={"imdb_id": imdb_id})
        return video_metadata

    return video_metadata
