#!/bin/bash

LOG_DIR="/var/log/rename"
LOG_FILE="$LOG_DIR/anime-batch-absolute-to-seasonal-$(date '+%Y%m%d-%H%M%S').log"

# Log function
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

# Usage: ./script.sh [directory]
# If no directory specified, uses current directory
get_showname() {
    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")

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

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

        # 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% -}"

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

get_season() {
    local filename="$1"

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

    # Extract episode (e.g., 001) --------------- Change the number in the {} to a 3 or 4 depending on the number of digits in the absolute number
#    pattern='Season [0-9]{2} \([^)]+\)'
    pattern='Season [0-9]{2}'
    if [[ $filename =~ $pattern ]]; then
        echo "${BASH_REMATCH[0]}"
    else
        echo "Pattern not found"
    fi
}

clean_basename() {
    local filename="$1"
    local first_episode="$2"
    local season="$3"

    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) --------------- Change the number in the {} to a 3 or 4 depending on the number of digits in the absolute number
    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
}

get_file_extension() {
    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")

    extension="${filename##*.}"

    echo $extension
}

generate_output_filename() {
    local input="$1"
    local extension="$2"

    # Remove common video extensions from basename
    local basename=$(basename "$input" | sed 's/\.\(mkv\|mp4\|avi\|mov\|m4v\|flv\|wmv\|webm\)$//')

    echo "${basename}.${extension}"
}

create_output_directory() {
	local path="$1"

	mkdir -p "$path"
}

rename_video_file() {
    local input="$1"          # e.g. /path/to/Movie (2023).mkv
    local path="$2"           # Target directory (with trailing slash)
    local output="$3"         # New filename only, e.g. Movie.2023.1080p.mkv

    #create_output_directory "$OUTPUT_PATH"

    local full_output_path="${path}${output}"
    local src_dir="$(dirname "$input")"
    local src_base="$(basename "$input")"
    local src_name="${src_base%.*}"    # original basename without extension
    local dst_name="${output%.*}"      # new basename without extension

    echo "Input: $input"
    echo "Path: $path"
    echo "L Output: $output"

}

process_file() {
    local INPUT="$1"
    local file_num="$2"
    local total_files="$3"
    local first_episode="$4"

    log "Starting: $INPUT"
    echo ""
    echo "========================================"
    echo "Processing file $file_num of $total_files: $(basename "$INPUT")"
    echo "========================================"

    # Naming
    showname=$(get_showname "$INPUT")
    season=$(get_season "$INPUT")
    new_name=$(clean_basename "$INPUT" "$first_episode" "$season")
    echo "$season"

    # Extract information
    EXTENSION=$(get_file_extension "$INPUT")
    OUTPUT=$(generate_output_filename "$new_name" "$EXTENSION")
    OUTPUT_PATH="/mnt/truenas/media/Anime/$showname/$season/"

    echo "Output: $OUTPUT_PATH$OUTPUT"

    # Check for existing file and encode if doesn't exist
    # Check for existing file and encode if doesn't exist
    if [ -f "$OUTPUT_PATH$OUTPUT" ]; then
        log "File exists, skipping..."
        echo "File exists, skipping..."
    else
        rename_video_file "$INPUT" "$OUTPUT_PATH" "$OUTPUT"
        log "Finished: $OUTPUT"
        echo "Completed: $(basename "$INPUT")"
    fi
}

# Main script
SEARCH_DIR="${1:-.}"

# Check if directory exists
if [[ ! -d "$SEARCH_DIR" ]]; then
    echo "Error: Directory not found: $SEARCH_DIR"
    exit 1
fi

# Find all .mkv files
shopt -s nullglob
FILES=("$SEARCH_DIR"/*.{mkv,mp4,avi})
shopt -u nullglob

# Check if any files found
if [ ${#FILES[@]} -eq 0 ]; then
    echo "No .mkv,.mp4,.avi files found in $SEARCH_DIR"
    exit 0
fi

echo "Found ${#FILES[@]} .mkv,.mp4,.avi file(s) to process"

FIRST_FILE="${FILES[0]}"
FIRST_FILE=$(basename "$FIRST_FILE")
#echo "$FIRST_FILE"

# --------------- Change the number in the {} to a 3 or 4 depending on the number of digits in the absolute number
if [[ $FIRST_FILE =~ ([0-9]{3}) ]]; then
    FIRST_EPISODE="${BASH_REMATCH[1]}"
fi

#FIRST_EPISODE="0877"
#echo "$FIRST_EPISODE"

# Process each file
count=0
for file in "${FILES[@]}"; do
    ((count++))
    process_file "$file" "$count" "${#FILES[@]}" "$FIRST_EPISODE"
done

echo ""
echo "========================================"
echo "Batch processing complete!"
echo "Processed $count file(s)"
echo "========================================"
