{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Load imports and create config directory"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# __main__.py\n",
    "import argparse\n",
    "import os\n",
    "\n",
    "from loguru import logger\n",
    "\n",
    "from mkv_episode_matcher_vob.config import get_config, set_config\n",
    "from mkv_episode_matcher_vob.utils import check_filename, cleanup_ocr_files, get_subtitles\n",
    "from mkv_episode_matcher_vob.tmdb_client import fetch_show_id,fetch_season_details\n",
    "import os\n",
    "import re\n",
    "import shutil\n",
    "from typing import Set\n",
    "\n",
    "import requests\n",
    "from loguru import logger\n",
    "from opensubtitlescom import OpenSubtitles\n",
    "# Log the start of the application\n",
    "logger.info(\"Starting the application\")\n",
    "\n",
    "\n",
    "\n",
    "# Check if the configuration directory exists, if not create it\n",
    "if not os.path.exists(os.path.join(os.path.expanduser(\"~\"), \".mkv-episode-matcher\")):\n",
    "    os.makedirs(os.path.join(os.path.expanduser(\"~\"), \".mkv-episode-matcher\"))\n",
    "\n",
    "# Define the paths for the configuration file and cache directory\n",
    "CONFIG_FILE = os.path.join(\n",
    "    os.path.expanduser(\"~\"), \".mkv-episode-matcher\", \"config.ini\"\n",
    ")\n",
    "CACHE_DIR = os.path.join(os.path.expanduser(\"~\"), \".mkv-episode-matcher\", \"cache\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Load configuration settings from config.ini"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "config = get_config(CONFIG_FILE)\n",
    "show_dir = config.get(\"show_dir\")\n",
    "show_name = os.path.basename(show_dir)\n",
    "series_name = os.path.basename(show_dir)\n",
    "tmdb_api_key = config.get(\"tmdb_api_key\")\n",
    "open_subtitles_api_key = config.get(\"open_subtitles_api_key\")\n",
    "open_subtitles_user_agent = config.get(\"open_subtitles_user_agent\")\n",
    "open_subtitles_username = config.get(\"open_subtitles_username\")\n",
    "open_subtitles_password = config.get(\"open_subtitles_password\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Make sure all required info exists in config.ini"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for x in     [\n",
    "        show_dir,\n",
    "        tmdb_api_key,\n",
    "        open_subtitles_api_key,\n",
    "        open_subtitles_user_agent,\n",
    "        open_subtitles_username,\n",
    "        open_subtitles_password,\n",
    "    ]:\n",
    "    try:\n",
    "        print(x)\n",
    "    except:\n",
    "        print('failed')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "if not all(\n",
    "    [\n",
    "        show_dir,\n",
    "        tmdb_api_key,\n",
    "        open_subtitles_api_key,\n",
    "        open_subtitles_user_agent,\n",
    "        open_subtitles_username,\n",
    "        open_subtitles_password,\n",
    "    ]\n",
    "):\n",
    "    logger.error(\"Missing configuration settings. Please run the setup script.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Make sure show can be found on TMDb\n",
    "The show id is used to search on opensubtitles"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "show_id = fetch_show_id(show_name)\n",
    "if show_id is None:\n",
    "    logger.error(f\"Could not find show '{os.path.basename(show_name)}' on TMDb.\")\n",
    "else:\n",
    "    print(show_id)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Try getting the first season automatically"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "get_subtitles(show_id, seasons=set([1]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Check if there's an issue in the get_subtitles function"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "try:\n",
    "    # Initialize the OpenSubtitles client\n",
    "    subtitles = OpenSubtitles(open_subtitles_user_agent, open_subtitles_api_key)\n",
    "\n",
    "    # Log in (retrieve auth token)\n",
    "    subtitles.login(open_subtitles_username, open_subtitles_password)\n",
    "except Exception as e:\n",
    "    logger.error(f\"Failed to log in to OpenSubtitles: {e}\")\n",
    "\n",
    "for season in [1]:\n",
    "    episodes = fetch_season_details(show_id, season)\n",
    "    logger.info(f\"Found {episodes} episodes in Season {season}\")\n",
    "\n",
    "    for episode in range(1, episodes + 1):\n",
    "        logger.info(f\"Processing Season {season}, Episode {episode}...\")\n",
    "        series_cache_dir =os.path.join(\n",
    "            CACHE_DIR,\n",
    "            \"data\",\n",
    "            series_name)\n",
    "        os.makedirs(series_cache_dir,exist_ok=True)\n",
    "        srt_filepath = os.path.join(\n",
    "            series_cache_dir,\n",
    "            f\"{series_name} - S{season:02d}E{episode:02d}.srt\",\n",
    "        )\n",
    "        if not os.path.exists(srt_filepath):\n",
    "            # get the episode info from TMDB\n",
    "            url = f\"https://api.themoviedb.org/3/tv/{show_id}/season/{season}/episode/{episode}?api_key={tmdb_api_key}\"\n",
    "            response = requests.get(url)\n",
    "            response.raise_for_status()\n",
    "            episode_data = response.json()\n",
    "            episode_name = episode_data[\"name\"]\n",
    "            episode_id = episode_data[\"id\"]\n",
    "            # search for the subtitle\n",
    "            response = subtitles.search(tmdb_id=episode_id, languages=\"en\")\n",
    "            if len(response.data) == 0:\n",
    "                logger.warning(\n",
    "                    f\"No subtitles found for {series_name} - S{season:02d}E{episode:02d}\"\n",
    "                )\n",
    "\n",
    "            for subtitle in response.data:\n",
    "                subtitle_dict = subtitle.to_dict()\n",
    "                # Remove special characters and convert to uppercase\n",
    "                filename_clean = re.sub(\n",
    "                    r\"\\W+\", \" \", subtitle_dict[\"file_name\"]\n",
    "                ).upper()\n",
    "                if f\"E{episode:02d}\" in filename_clean:\n",
    "                    logger.info(f\"Original filename: {subtitle_dict['file_name']}\")\n",
    "                    srt_file = subtitles.download_and_save(subtitle)\n",
    "                    series_name = series_name.replace(\":\", \" -\")\n",
    "                    shutil.move(os.path.join(os.getcwd(),srt_file), srt_filepath)\n",
    "                    logger.info(f\"Subtitle saved to {srt_filepath}\")\n",
    "                    break\n",
    "                else:\n",
    "                    continue\n",
    "        else:\n",
    "            logger.info(\n",
    "                f\"Subtitle already exists for {series_name} - S{season:02d}E{episode:02d}\"\n",
    "            )\n",
    "            continue"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "mkv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
