import os
import time
from pod2gen import Podcast, Episode, Media, Person
from mutagen import mp4, mp3
from datetime import timedelta, datetime as dt
from dateutil.tz import UTC


def get_mp3_metadata(file_path: str, filename: str) -> (timedelta, str):
    """Extract MP3 metadata from a file.

    Args:
        file_path (str): Path to the MP3 file.
        filename (str): Name of the MP3 file.

    Returns:
        tuple: Timedelta and description of the MP3 file.
    """
    try:
        mp3_file = mp3.MP3(file_path)
        track_seconds = round(mp3_file.info.length)
        time_split = time.strftime("%H:%M:%S", time.gmtime(track_seconds)).split(":")
        duration = timedelta(
            hours=int(time_split[0]),
            minutes=int(time_split[1]),
            seconds=int(time_split[2]),
        )
        description = mp3_file.tags.get("COMM::'eng'", [filename.replace("_", " ")])[0].text[0]
    except Exception as e:
        print(f"Error processing file {file_path}: {e}")
        duration = timedelta(0)
        description = filename.replace("_", " ")

    return duration, description

def get_mp4_metadata(file_path: str, filename: str) -> (timedelta, str):
    """Extract MP4 metadata from a file.

    Args:
        file_path (_type_): File path to the MP4 file.
        str (_type_): Name of the MP4 file.

    Returns:
        _type_: Timedelta and description of the MP4 file.
    """
    track_seconds = round(mp4.MP4(file_path).info.length)
    time_split = time.strftime("%H:%M:%S", time.gmtime(track_seconds)).split(":")
    try:
        description = mp4.MP4(file_path).tags["\xa9cmt"][0]
    except KeyError:
        description = filename.replace("_", " ")
    return (
        timedelta(
            hours=int(time_split[0]),
            minutes=int(time_split[1]),
            seconds=int(time_split[2]),
        ),
        description,
    )


def add_episodes_from_folder(folder_path: str, season:int) -> None:
    """Loop over all files in a folder and add them to the Podcast.

    Args:
        folder_path (str): Folder to loop over.
        season (int): Season number for for the podcast
    """
    file_list = os.listdir(folder_path)
    list_of_episodes = sorted([x for x in file_list if "mp3" in x], key=lambda x: int(x.split()[1].split('.')[0]))
    # file_list.pop(0)
    for file in list_of_episodes:
        filename = file[:-4]
        ep_details = filename.split(" ")
        file_size = os.stat(f"./{folder_path}/{file}").st_size
        file_length, description = get_mp3_metadata(f"./{folder_path}/{file}", filename)
        p.add_episode(
            Episode(
                title=f"{folder_path} - {filename}",
                media=Media(
                    f"https://kithub.k-world.me.uk/Karl/GTPStories/raw/master/{folder_path}/{file}",
                    size=file_size,
                    type="mp3",
                ),
                summary=description,
                season=season,
                episode_number=int(ep_details[1][-0]),
                image=f'https://kithub.k-world.me.uk/Karl/GTPStories/raw/master/{folder_path}/{folder_path}_wide.png',
                publication_date=dt.fromtimestamp(
                    os.stat(f"./{folder_path}/{file}").st_ctime, tz=UTC
                ),
            )
        )


owner = Person("Example", "email@example.com")
# Create the Podcast
p = Podcast(
    name="GPT Stories",
    description="GPT Stories in audio form",
    website="http://kithub.k-world.me.uk/Karl/GTPStories",
    explicit=True,
)
p.image = "https://kithub.k-world.me.uk/Karl/GTPStories/raw/master/logo.png"
p.owner = owner
p.locked = True
p.withhold_from_itunes = True

add_episodes_from_folder("Reboot", 1)
add_episodes_from_folder("Pathfinders", 2)
# add_episodes_from_folder("Season 3")

# Generate the RSS feed
p.rss_file("feed.xml", minimize=True)