#!/bin/bash

filename="/mnt/truenas/media/Anime/Pokemon/Season 03 (The Johto Journeys)/Pokemon - 081 - Pallet Party Panic.mkv"
first_episode="081"
season="Season 03 (The Johto Journeys)"

if [ -z "$filename" ]; then
    echo "Usage: clean_basename 'filename.mkv'" >&2
    return 1
fi

# Extract just the filename without path
filename=$(basename "$filename")

new_filename=$(echo "$filename" | sed 's/\[[^]]*\]//g; s/^[[:space:]]*//; s/[[:space:]]*$//')

# Get file extension
extension="${new_filename##*.}"

if [[ $season =~ ([0-9]{2}) ]]; then
    season_number="${BASH_REMATCH[1]}"
fi

# Extract episode (e.g., 001)
if [[ $filename =~ ([0-9]{3}) ]]; then
    episode="${BASH_REMATCH[1]}"

    # Calculate the new episode number
    let new_episode=10#$episode-10#$first_episode+1
    new_episode=$(printf "%02d" $new_episode)

    seasonepisode="S${season_number}E${new_episode}"

    # Get the part before the season/episode
    show_part="${filename%%$episode*}"

    # Replace dots with spaces and clean up
    show_name=$(echo "$show_part" | sed 's/\.\./\./g' | sed 's/\./ /g' | sed 's/ *$//')

    # Remove trailing " -"
    show_name="${show_name% -}"

    # Get the part after the season/episode
    episode_part="${filename#*$episode}"

    # Remove trailing " -"
    episode_name="${episode_part#*- }"

    # Return formatted filename
    echo "${show_name} - ${seasonepisode} - ${episode_name}" #.${extension}"
else
    echo "${new_filename}.${extension}"
    #echo "Error: Could not find season/episode pattern in filename" >&2
    #return 1
fi
