#!/usr/bin/env bash

source ./secrets.sh

# Function to URL encode a string
urlencode() {
    local string="$1"
    local encoded=""
    local char

    for (( i=0; i<${#string}; i++ )); do
        char="${string:i:1}"
        case "$char" in
            [a-zA-Z0-9.~_-]) encoded+="$char" ;;
            *) encoded+=$(printf '%%%02X' "'$char") ;;
        esac
    done
    echo "$encoded"
}

echo "Enter Movie Title:"

read -r title

# URL encode the movie title
encoded_title=$(urlencode "$title")

# mkdir "../$title/temp"

# Search The Movie Database
json_results=$(curl -s --request GET \
     --url "https://api.themoviedb.org/3/search/movie?query=$encoded_title&include_adult=false&language=en-US&page=1" \
     --header "Authorization: Bearer $themoviedb_token" \
     --header 'accept: application/json' | ./jq)

echo "Select the correct movie title:"
echo "$json_results" | ./jq -r '.results[:3] | to_entries[] | "\(.key + 1). \(.value.title) (\(.value.release_date))"'
read -r -p "Selection: " selection

# Get the selected movie details
selected_movie=$(echo "$json_results" | ./jq -r ".results[$((selection - 1))]")

full_title=$(echo "$selected_movie" | ./jq -r '. | "\(.original_title) (\(.release_date | split("-")[0]))"')
poster_path="https://image.tmdb.org/t/p/original$(echo "$selected_movie" | ./jq -r '.poster_path')"

echo "$full_title"


echo "Downloading Poster..."
curl -s -o "./poster.${poster_path##*.}" "$poster_path"

# HandBrakeCLI -i "../$title/$title - 4k DV.mkv" -o "../$title/temp/handbrake.mkv" -f av_mkv -m -e x265_10bit --encoder-preset slower -q 20 --encoder-profile auto --all-audio -E copy --audio-copy-mask aac,eac3,dts,ac3,truehd,dtshd,mp3 --crop-mode auto --auto-anamorphic --all-subtitles

# ffmpeg -i "../$title/$title - 4k DV.mkv" -c:v copy -f hevc - | ./dovi_tool -m 2 --crop extract-rpu - -o "../$title/temp/rpu.bin"

# ffmpeg -i "../$title/temp/handbrake.mkv" -c:v copy "../$title/temp/nonhdr.hevc"

# ./dovi_tool inject-rpu -i "../$title/temp/nonhdr.hevc" --rpu-in "../$title/temp/rpu.bin" -o "../$title/temp/hdrcompressed.hevc"

# mkvmerge --output "../$title/$title - 4k DVP8 Subs.mkv" "../$title/temp/hdrcompressed.hevc" -D -S -B -T --no-chapters -M --no-global-tags "../$title/temp/handbrake.mkv" --default-track-flag 0:no --language 0:en "../$title/$title.en.srt" -D -A "../$title/temp/handbrake.mkv"
