import logging

from cinemagoerng import web as imdb
from videos.metadata import VideoMetadata, VideoType

logger = logging.getLogger(__name__)


def lookup_video_from_imdb(imdb_id: str) -> VideoMetadata:
    if not imdb_id.startswith("tt"):
        logger.warning("This method requires an IMDB ID starting with 'tt'")
        return VideoMetadata()

    video_metadata = VideoMetadata(imdb_id=imdb_id)
    imdb_result: dict = {}

    imdb_result = imdb.get_title(imdb_id)
    logger.debug(f"Found result from IMDB: {imdb_result.title}")

    if not imdb_result:
        logger.info(
            f"[lookup_video_from_imdb] no video found on imdb",
            extra={"name_or_id": name_or_id},
        )
        return None

    if imdb_result.type_id.lower() in ["movie", "tvepisode"]:
        video_metadata.base_run_time_seconds = (
            imdb_result.runtime * 60
        )
    video_metadata.imdb_id = imdb_id
    video_metadata.title = imdb_result.title
    video_metadata.year = imdb_result.year
    video_metadata.plot = imdb_result.plot.get("en-US", "")
    video_metadata.imdb_rating = imdb_result.rating
    video_metadata.genres = imdb_result.genres
    video_metadata.cover_url = imdb_result.primary_image

    video_metadata.video_type = VideoType.MOVIE.value
    if imdb_result.type_id == "tvEpisode":
        video_metadata.video_type = VideoType.TV_EPISODE.value

        series = imdb_result.series
        video_metadata.tv_series_imdb_id = series.imdb_id
        video_metadata.tv_series_title = series.title
        video_metadata.episode_number = imdb_result.episode
        video_metadata.season_number = imdb_result.season
        video_metadata.next_imdb_id = imdb_result.next_episode_id


    return video_metadata
