#!/bin/bash

clean_basename() {
    local filename="$1"

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

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

    # Try to match season/episode pattern (case-insensitive, S2025E10 or s2020e02)
    if [[ $filename =~ ([Ss][0-9]{4}[Ee][0-9]{2}) ]]; then
        season_episode="${BASH_REMATCH[1]}"
        echo "$season_episode"
        # Normalize to uppercase
        season_episode=$(echo "$season_episode" | tr '[:lower:]' '[:upper:]')
        echo "$season_episode"

        # Get the part before the season/episode
        show_part="${filename%%[Ss][0-9]*}"
        echo "$show_part"

        # Get the part after season/episode
        after_episode="${filename#*${BASH_REMATCH[1]}}"
        echo "$after_episode"

        # Get file extension first
        extension="${filename##*.}"
        echo "$extension"

        # Extract race name - three different patterns:
        # Pattern 1: " - Race Name [" (newer format with brackets)
        # Pattern 2: " - Race Name " followed by resolution/codec info (older format with tech info)
        # Pattern 3: " - Race Name.ext" (oldest format, just race name and extension)
        local race_info=""

        if [[ $after_episode =~ ^[[:space:]]*-[[:space:]]*([^[]+)\[ ]]; then
            # Newer format: everything between " - " and first "["
            race_info="${BASH_REMATCH[1]}"
        elif [[ $after_episode =~ ^[[:space:]]*-[[:space:]]*(.+)\.$extension$ ]]; then
            # Oldest format: everything between " - " and file extension
            race_info="${BASH_REMATCH[1]}"
        elif [[ $after_episode =~ ^[[:space:]]*-[[:space:]]*([^.]+) ]]; then
            # Older format: everything between " - " and technical info
            race_info="${BASH_REMATCH[1]}"
            # Remove trailing resolution/codec info (like "1080p50" or "720p")
            race_info=$(echo "$race_info" | sed 's/[[:space:]]*[0-9]*[pi][0-9]*[[:space:]]*$//')
        fi

        # Clean up race info: remove trailing spaces and dashes
        race_info=$(echo "$race_info" | sed 's/[[:space:]]*$//' | sed 's/[[:space:]]*-[[:space:]]*$//')

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

        # Build the cleaned filename
        if [ -n "$race_info" ]; then
            echo "${show_name} - ${season_episode} - ${race_info}.${extension}"
        else
            echo "${show_name} - ${season_episode}.${extension}"
        fi
    else
        echo "Error: Could not find season/episode pattern in filename" >&2
        return 1
    fi
}

INPUT="$1"
new_name=$(clean_basename "$INPUT")
echo "$new_name"
