#!/bin/bash

# Check if the correct number of arguments are provided
if [ "$#" -ne 2 ]; then
    echo "Usage: $0 <csv_file> --token=<API_TOKEN>"
    exit 1
fi

# Extract arguments
CSV_FILE=$1
API_TOKEN=$(echo "$2" | sed 's/--token=//')

# Check if the API token is provided
if [ -z "$API_TOKEN" ]; then
    echo "Error: API token is required."
    exit 1
fi

# Temporary files
TMP_FILE=$(mktemp)
TMP_UPDATED_FILE=$(mktemp)

# Extract the header and data from the CSV file
awk -F, 'NR==1 {print $0} NR>1' "$CSV_FILE" > "$TMP_FILE"

# Add the ID column to the header if not already present
if ! grep -q 'ID' "$CSV_FILE"; then
    sed -i '1s/$/,ID/' "$CSV_FILE"
fi

# Process each line of the CSV file
while IFS=, read -r title year scanned format available id; do
    # Skip header line
    if [ "$title" == "Title" ]; then
        continue
    fi

    # Escape characters in title for URL
    encoded_title=$(echo "$title" | sed 's/ /%20/g')

    # Make the API request
    response=$(curl --silent --request GET \
        --url "https://api.themoviedb.org/3/search/movie?query=${encoded_title}&include_adult=false&language=en-US&page=1&year=${year}" \
        --header "Authorization: Bearer ${API_TOKEN}" \
        --header 'accept: application/json')

    # Extract the movie ID from the response
    movie_id=$(echo "$response" | jq -r '.results[0].id // empty')

    # Update the CSV with the movie ID
    if [ -n "$movie_id" ]; then
        echo "$title,$year,$scanned,$format,$available,$movie_id" >> "$TMP_UPDATED_FILE"
    else
        echo "$title,$year,$scanned,$format,$available," >> "$TMP_UPDATED_FILE"
    fi
done < "$TMP_FILE"

# Combine the header with the updated data
head -n 1 "$CSV_FILE" > "$TMP_FILE"
cat "$TMP_UPDATED_FILE" >> "$TMP_FILE"

# Overwrite the original CSV with the updated file
mv "$TMP_FILE" "$CSV_FILE"

# Clean up
rm "$TMP_UPDATED_FILE"

echo "CSV file has been updated with movie IDs."