Generic

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

get_season() {
    local filename="$1"

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

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

    # Extract season number (e.g., S01)
    if [[ $filename =~ S([0-9]{2}) ]]; then
        if [ "${BASH_REMATCH[1]}" = "00" ]; then
            echo "Specials"
        else
            echo "Season ${BASH_REMATCH[1]}"
        fi
    else
        echo "Error: Could not find season pattern in filename" >&2
        return 1
    fi
}

#get_resolution() {
#    local input="$1"
#    local width=$(ffprobe -v error -select_streams v:0 -show_entries stream=width -of csv=p=0 "$input")
#    local height=$(ffprobe -v error -select_streams v:0 -show_entries stream=height -of csv=p=0 "$input")
#    
#    # Determine resolution based on width (more reliable for ultra-wide content)
#    if [ "$width" -ge 3800 ]; then
#        echo "2160p"
#    elif [ "$width" -ge 2500 ]; then
#        echo "1440p"
#    elif [ "$width" -ge 1900 ]; then
#        echo "1080p"
#    elif [ "$width" -ge 1260 ]; then
#        echo "720p"
#    elif [ "$width" -ge 700 ]; then
#        echo "576p"
#    elif [ "$width" -ge 640 ]; then
#        echo "480p"
#    else
#        echo "${height}p"
#    fi
#}

get_resolution() {
    local input="$1"
    local width=$(ffprobe -v error -select_streams v:0 -show_entries stream=width -of csv=p=0 "$input")
    local height=$(ffprobe -v error -select_streams v:0 -show_entries stream=height -of csv=p=0 "$input")

    # Remove any non-numeric characters (commas, etc.)
    width=$(echo "$width" | tr -cd '0-9')
    height=$(echo "$height" | tr -cd '0-9')

    # Validate we got numeric values
    if [ -z "$width" ] || [ -z "$height" ] || [ "$width" -eq 0 ] || [ "$height" -eq 0 ]; then
        echo "Unknown"
        return 1
    fi

    # Check if video is interlaced
    local field_order=$(ffprobe -v error -select_streams v:0 -show_entries stream=field_order -of csv=p=0 "$input")
    local is_interlaced=false

    if [[ "$field_order" != "progressive" ]] && [[ "$field_order" != "unknown" ]] && [[ -n "$field_order" ]]; then
        is_interlaced=true
    fi

    # Calculate aspect ratio to detect letterboxing
    local aspect_ratio=$(awk "BEGIN {printf \"%.2f\", $width/$height}")

    # Determine resolution number
    local res_number=""

    # Detect letterboxed content by checking if aspect ratio is significantly wider than 16:9 (1.78)
    if awk "BEGIN {exit !($aspect_ratio > 2.0)}"; then
        # Likely letterboxed - estimate source resolution from width
        if [ "$width" -ge 3800 ]; then
            res_number="2160"
        elif [ "$width" -ge 2500 ]; then
            res_number="1440"
        elif [ "$width" -ge 1900 ]; then
            res_number="1080"
        elif [ "$width" -ge 1260 ]; then
            res_number="720"
        elif [ "$width" -ge 700 ]; then
            res_number="576"
        elif [ "$width" -ge 640 ]; then
            res_number="480"
        else
            res_number="$height"
        fi
    else
        # Not letterboxed - use actual height
        case $height in
            2160) res_number="2160" ;;
            1440) res_number="1440" ;;
            1080) res_number="1080" ;;
            720)  res_number="720"  ;;
            576)  res_number="576"  ;;
            480)  res_number="480"  ;;
            *)    res_number="$height" ;;
        esac
    fi

    # Add 'i' for interlaced, 'p' for progressive
    if [ "$is_interlaced" = true ]; then
        echo "${res_number}i"
    else
        echo "${res_number}p"
    fi
}

get_video_codec() {
    local input="$1"
    local codec=$(ffprobe -v error -select_streams v:0 -show_entries stream=codec_name -of csv=p=0 "$input")

    # Remove any commas or whitespace
    codec=$(echo "$codec" | tr -d ', ' | tr -d '\n')

    case "$codec" in
        h264)
            echo "x264"
            ;;
        hevc|h265)
            echo "x265"
            ;;
        av1)
            echo "AV1"
            ;;
        vp9)
            echo "VP9"
            ;;
        vp8)
            echo "VP8"
            ;;
        mpeg4)
            echo "MPEG4"
            ;;
        mpeg2video)
            echo "MPEG2"
            ;;
        *)
            # Uppercase and clean unknown codecs
            echo "${codec^^}"
            ;;
    esac
}

get_colour_depth() {
    local input="$1"
    local bit_depth=$(ffprobe -v error -select_streams v:0 -show_entries stream=bits_per_raw_sample -of csv=p=0 "$input")

    # Clean the output - remove commas, whitespace, and check for N/A
    bit_depth=$(echo "$bit_depth" | tr -d ', ' | tr -d '\n')

    if [[ -z "$bit_depth" ]] || [[ "$bit_depth" == "N/A" ]] || [[ "$bit_depth" == "0" ]]; then
        # Fallback to pix_fmt if bits_per_raw_sample is not available
        local pix_fmt=$(ffprobe -v error -select_streams v:0 -show_entries stream=pix_fmt -of csv=p=0 "$input")
        pix_fmt=$(echo "$pix_fmt" | tr -d ', ' | tr -d '\n')

        if [[ "$pix_fmt" == *"10"* ]]; then
            echo "10bit"
        elif [[ "$pix_fmt" == *"12"* ]]; then
            echo "12bit"
        else
            echo "8bit"
        fi
    else
        echo "${bit_depth}bit"
    fi
}

get_hdr_status() {
    local input="$1"
    local color_transfer=$(ffprobe -v error -select_streams v:0 -show_entries stream=color_transfer -of csv=p=0 "$input")

    if [[ "$color_transfer" == "smpte2084" ]] || [[ "$color_transfer" == "arib-std-b67" ]]; then
        echo "HDR"
    else
        echo "SDR"
    fi
}

get_audio_tracks() {
    local input="$1"
    ffprobe -v error -select_streams a -show_entries stream=index,codec_name,profile,channels:stream_tags=language -of csv=p=0 "$input" | while IFS=',' read -r index codec profile channels lang; do
        [[ -z "$lang" ]] && lang="und"

        # Check for codec variants
        case "$codec" in
            aac)
                if [[ "$profile" =~ HE|SBR ]]; then
                    codec="heaac"
                fi
                ;;
            dts)
                if [[ "$profile" =~ "DTS-HD MA" ]]; then
                    codec="dts-hdma"
                elif [[ "$profile" =~ "DTS-HD HRA" ]]; then
                    codec="dts-hd"
                elif [[ "$profile" =~ "DTS:X" ]]; then
                    codec="dtsx"
                fi
                ;;
            truehd)
                if [[ "$profile" =~ "Atmos" ]]; then
                    codec="truehd-atmos"
                fi
                ;;
        esac

        echo "$index:$codec:$channels:$lang"
    done
}

format_channels() {
    local channels="$1"
    case "$channels" in
        2) echo "" ;;      # Stereo - no suffix
        6) echo " 51" ;;   # 5.1
        8) echo " 71" ;;   # 7.1
        *) echo "" ;;      # Other channel counts - no suffix
    esac
}

create_output_directory() {
	local path="$1"

	mkdir -p "$path"
}
