TV

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")

    # Extract season and episode (e.g., S01E01)
    if [[ $filename =~ (S[0-9]{2}E[0-9]{2}) ]]; then
        season_episode="${BASH_REMATCH[1]}"

        # Get the part before the season/episode
        show_part="${filename%%$season_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_year(){
	local filename="$1"

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

	if [[ $filename =~ (\([0-9]{4}\)) ]]; then
		year="${BASH_REMATCH[1]}"
    else
        echo "Error: Could not find year pattern in filename" >&2
        return 1
	fi

	#echo "$filename"
	echo "$year"
}

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")

    # Extract season and episode (e.g., S01E01)
    if [[ $filename =~ (S[0-9]{2}E[0-9]{2}) ]]; then
        season_episode="${BASH_REMATCH[1]}"

        # Get the part before the season/episode
        show_part="${filename%%$season_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 file extension
        extension="${filename##*.}"

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

format_audio_info() {
    local input="$1"
    local tracks=$(get_audio_tracks "$input")

    # Store tracks in arrays
    local -a codecs languages channel_counts
    while IFS=':' read -r index codec channels lang; do
        codecs+=("$codec")
        channel_counts+=("$channels")
        languages+=("$lang")
    done <<< "$tracks"

    # Check if all codecs and channels are the same
    local all_same=true
    local first_codec="${codecs[0]}"
    local first_channels="${channel_counts[0]}"
    for i in "${!codecs[@]}"; do
        if [[ "${codecs[$i]}" != "$first_codec" ]] || [[ "${channel_counts[$i]}" != "$first_channels" ]]; then
            all_same=false
            break
        fi
    done

    # Format output
    if [[ "$all_same" == true ]] && [[ ${#codecs[@]} -gt 1 ]]; then
        local channel_suffix=$(format_channels "$first_channels")
        echo "Dual Audio ${first_codec^^}${channel_suffix}"
    else
        local output=""
        for i in "${!codecs[@]}"; do
            local channel_suffix=$(format_channels "${channel_counts[$i]}")
            [[ -n "$output" ]] && output+=" "
            output+="${codecs[$i]^^}${channel_suffix}"
        done
        echo "$output"
    fi
}

generate_output_filename() {
    local input="$1"
    local resolution="$2"
    local hdr="$3"
    local audio="$4"
    local basename=$(basename "$input" | sed 's/\.\(mkv\|mp4\|avi\)$//')

    echo "${basename} [${resolution}] [AV1 10bit ${hdr}] [${audio}].mkv"
}

# Find external subtitle files matching the input video
find_external_subtitles() {
    local input="$1"
    local input_dir=$(dirname "$input")
    local input_basename=$(basename "$input")
    # Remove extension to get base name
    local base_name="${input_basename%.*}"

    # Find all .srt files that start with the base name
    find "$input_dir" -maxdepth 1 -type f -name "${base_name}*.srt" 2>/dev/null | sort
}

# Parse subtitle filename to extract metadata
parse_subtitle_metadata() {
    local subtitle_file="$1"
    local base_name=$(basename "$subtitle_file" .srt)

    local language="eng"  # Default to English
    local title=""
    local is_forced=false
    local is_sdh=false
    local is_cc=false
    local is_hi=false

    # Convert to lowercase for case-insensitive matching
    local lower_name=$(echo "$base_name" | tr '[:upper:]' '[:lower:]')

    # Check for forced
    if [[ "$lower_name" =~ forced ]]; then
        is_forced=true
        title="${title}Forced "
    fi

    # Check for SDH
    if [[ "$lower_name" =~ sdh ]]; then
        is_sdh=true
        title="${title}SDH "
    fi

    # Check for CC
    if [[ "$lower_name" =~ \.cc\. ]]; then
        is_cc=true
        title="${title}CC "
    fi

    # Check for HI (Hearing Impaired)
    if [[ "$lower_name" =~ \.hi\. ]]; then
        is_hi=true
        title="${title}HI "
    fi

    # Extract language code (look for common patterns like .eng. .spa. .fre.)
    if [[ "$lower_name" =~ \.(eng|fra|fre|spa|ger|deu|ita|por|jpn|kor|chi|zho)\. ]]; then
        language="${BASH_REMATCH[1]}"
        # Normalize some language codes
        case "$language" in
            fre) language="fra" ;;
            ger) language="deu" ;;
            chi) language="zho" ;;
        esac
    fi

    # Clean up title (remove trailing space)
    title=$(echo "$title" | sed 's/ *$//')

    # If title is empty, use language
    if [ -z "$title" ]; then
        title="${language^^}"
    else
        title="${language^^} ${title}"
    fi

    echo "$language:$title:$is_forced"
}

reenocde_av1() {
    local input="$1"
    local path="$2"
    local output="$3"
    create_output_directory "$OUTPUT_PATH"

    # Find external subtitles
    local external_subs=$(find_external_subtitles "$input")
    local external_sub_count=$(echo "$external_subs" | grep -c '^' 2>/dev/null || echo 0)

    echo "Found $external_sub_count external subtitle file(s)"

    # Check if any English subtitles exist in the video file
    eng_subs_exist=$(ffprobe -v error -select_streams s -show_entries stream_tags=language -of csv=p=0 "$input" | grep -q "eng" && echo "yes" || echo "no")

    # Check subtitle codec if English subs exist
    local sub_codec_arg="-c:s copy"
    if [ "$eng_subs_exist" = "yes" ]; then
        # Get the subtitle codec
        sub_codec=$(ffprobe -v error -select_streams s:m:language:eng -show_entries stream=codec_name -of csv=p=0 "$input" | head -n1)

        # If mov_text (MP4 subtitles), convert to ass for MKV compatibility
        if [ "$sub_codec" = "mov_text" ]; then
            sub_codec_arg="-c:s srt"
        fi
    fi

    # Build input files list and map args separately
    local input_args="-i \"$input\""
    local map_args="-map 0:v:0 -map 0:a"
    local vf_args="scale=in_range=tv:out_range=tv"
    local metadata_args=""
    local forced_sub_file=""
    local forced_sub_index=-1

    # Add subtitle mapping if English subs exist in video
    if [ "$eng_subs_exist" = "yes" ]; then
        map_args="$map_args -map 0:s:m:language:eng"
    fi

    # Add external subtitle files
    local sub_index=0
    while IFS= read -r sub_file; do
        [ -z "$sub_file" ] && continue

        echo "Processing subtitle: $(basename "$sub_file")"

        # Parse subtitle metadata
        local sub_metadata=$(parse_subtitle_metadata "$sub_file")
        local sub_lang=$(echo "$sub_metadata" | cut -d':' -f1)
        local sub_title=$(echo "$sub_metadata" | cut -d':' -f2)
        local sub_forced=$(echo "$sub_metadata" | cut -d':' -f3)

        echo "  Language: $sub_lang, Title: $sub_title, Forced: $sub_forced"

        # Add input file
        local input_index=$((sub_index + 1))
        input_args="$input_args -i \"$sub_file\""

        # Map the subtitle stream from this input
        map_args="$map_args -map $input_index:s:0"

        # Add metadata for this subtitle track
        # Subtitle stream index in output (account for video + audio + existing subs)
        metadata_args="$metadata_args -metadata:s:s:$sub_index language=$sub_lang"
        metadata_args="$metadata_args -metadata:s:s:$sub_index title=\"$sub_title\""

        # Mark as forced if needed
        if [ "$sub_forced" = "true" ]; then
            metadata_args="$metadata_args -disposition:s:s:$sub_index forced"
            # Save first forced subtitle for potential burning
            if [ -z "$forced_sub_file" ]; then
                forced_sub_file="$sub_file"
                forced_sub_index=$sub_index
            fi
        fi

        ((sub_index++))
    done <<< "$external_subs"

    # TODO: Add forced subtitle burning logic here if desired
    # This would require:
    # 1. Detecting forced subtitle
    # 2. Adding subtitles filter to vf_args
    # 3. Excluding that subtitle from passthrough

    # Single ffmpeg command
    eval ffmpeg $input_args \
        $map_args \
        -c:v libsvtav1 \
        -preset 5 \
        -crf 30 \
        -pix_fmt yuv420p10le \
        -svtav1-params \"fast-decode=1:tune=0:film-grain=6:film-grain-denoise=0\" \
        -vf \"$vf_args\" \
        -map_metadata 0 \
        -map_metadata:s:v:0 0:s:v:0 \
        -c:a copy \
        $sub_codec_arg \
        $metadata_args \
        -f matroska \
        \"$path$output\"
}
