#!/bin/bash

# Check if an argument is provided
if [ -z "$1" ]; then
    echo "Usage: $0 <directory>"
    exit 1
fi

# Set target directory from argument
TARGET_DIR="$1"

# Check if directory exists
if [ ! -d "$TARGET_DIR" ]; then
    echo "Error: Directory '$TARGET_DIR' does not exist."
    exit 1
fi

# Navigate to the target directory
cd "$TARGET_DIR" || exit

# Declare an associative array to track filenames
declare -A file_count

# Process each .mp4 file
for file in *.mp4; do
    # Generate a sanitized filename: remove special chars, emojis, and extra spaces
    new_name=$(echo "$file" | sed -E 's/_\[[0-9]+\]//g' | tr -d '[:punct:]' | tr -d '[:cntrl:]' | tr -d '[:space:]' | sed 's/[^a-zA-Z0-9]/_/g')

    # Remove leading/trailing underscores
    new_name=$(echo "$new_name" | sed 's/^_//;s/_$//')

    # Ensure the filename is unique by adding _1, _2, etc.
    base_name="${new_name%.mp4}"  # Remove .mp4 extension for counting
    extension=".mp4"

    # If filename exists, append _1, _2, etc.
    if [[ -v "file_count[$base_name]" ]]; then
        file_count[$base_name]=$((file_count[$base_name] + 1))
    else
        file_count[$base_name]=1
    fi

    unique_name="${base_name}_${file_count[$base_name]}$extension"

    # Rename the file
    mv "$file" "$unique_name"
done

echo "Renaming complete in $TARGET_DIR"
