#!/bin/bash
#
# Retranscode Old Tournament Videos (Pre-October 2025)
#
# This script submits all recordings from tournaments before October 2025
# to pyProxy for re-encoding using the LOW PRIORITY queue.
#
# Usage:
#   screen -S proxy-regen-old
#   cd /var/www/html/brettZone/backend
#   ./retranscodeOldTournaments.sh 2>&1 | tee retranscode_old.log
#
# The script is idempotent - safe to restart if interrupted.
# Uses reprocess=true flag to force re-encoding of existing videos.
# Uses priority=low to avoid impacting normal priority work.
#

set -e

# Configuration
DB_USER="root"
DB_PASS="mclab1024"
DB_NAME="matchdb"
PROXY_API="https://live.nhrl.io/proxyMaker/api/jobs"
DELAY_MS=20  # Delay between submissions in milliseconds

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

echo "=========================================="
echo "  Retranscode Old Tournament Videos"
echo "  (Pre-October 2025, Low Priority)"
echo "=========================================="
echo ""
echo "Start time: $(date)"
echo ""

# Query for distinct s3paths from tournaments before October 2025
echo "Querying database for videos from tournaments before October 2025..."

QUERY="SELECT DISTINCT r.s3path 
FROM recordings r 
JOIN tournaments t ON r.tournamentID = t.tournamentID 
WHERE r.s3http = 200 
  AND t.startTime < '2025-10-01 00:00:00' 
  AND t.privacy != 'private'
  AND t.isTest = 0
ORDER BY t.startTime DESC"

# Get the list of video URLs
VIDEO_URLS=$(mysql -u "$DB_USER" -p"$DB_PASS" "$DB_NAME" -N -e "$QUERY" 2>/dev/null)

if [ -z "$VIDEO_URLS" ]; then
    echo -e "${RED}No videos found from tournaments before October 2025.${NC}"
    exit 1
fi

# Count total videos
TOTAL=$(echo "$VIDEO_URLS" | wc -l)
echo -e "${GREEN}Found $TOTAL unique videos to retranscode.${NC}"
echo -e "${CYAN}Using LOW PRIORITY queue (12 of 36 slots)${NC}"
echo -e "${CYAN}Submission delay: ${DELAY_MS}ms${NC}"
echo ""

# Counters
CURRENT=0
SUCCESS=0
FAILED=0
ALREADY_PROCESSING=0

# Process each video
while IFS= read -r VIDEO_URL; do
    CURRENT=$((CURRENT + 1))
    
    # Extract filename for display
    FILENAME=$(basename "$VIDEO_URL")
    
    # Show progress
    echo -n "[$CURRENT/$TOTAL] $FILENAME ... "
    
    # Submit to proxyMaker with reprocess=true and priority=low
    RESPONSE=$(curl -s -X POST "$PROXY_API" \
        -H "Content-Type: application/json" \
        -d "{\"videoUrl\": \"$VIDEO_URL\", \"reprocess\": true, \"priority\": \"low\"}" \
        -w "\n%{http_code}" 2>/dev/null)
    
    # Extract HTTP status code (last line)
    HTTP_CODE=$(echo "$RESPONSE" | tail -n1)
    # Extract JSON response (all but last line)
    JSON_RESPONSE=$(echo "$RESPONSE" | sed '$d')
    
    # Check response
    if [ "$HTTP_CODE" = "201" ]; then
        echo -e "${GREEN}Queued (new)${NC}"
        SUCCESS=$((SUCCESS + 1))
    elif [ "$HTTP_CODE" = "200" ]; then
        # Check if it's processing or was resubmitted
        STATUS=$(echo "$JSON_RESPONSE" | grep -o '"status":"[^"]*"' | cut -d'"' -f4)
        if [ "$STATUS" = "processing" ]; then
            echo -e "${YELLOW}Already processing${NC}"
            ALREADY_PROCESSING=$((ALREADY_PROCESSING + 1))
        elif [ "$STATUS" = "pending" ]; then
            echo -e "${YELLOW}Already pending${NC}"
            ALREADY_PROCESSING=$((ALREADY_PROCESSING + 1))
        else
            echo -e "${GREEN}Resubmitted${NC}"
            SUCCESS=$((SUCCESS + 1))
        fi
    else
        echo -e "${RED}Failed (HTTP $HTTP_CODE)${NC}"
        echo "  Response: $JSON_RESPONSE"
        FAILED=$((FAILED + 1))
    fi
    
    # Delay between submissions (20ms)
    if [ "$DELAY_MS" -gt 0 ]; then
        sleep $(echo "scale=3; $DELAY_MS/1000" | bc)
    fi
    
done <<< "$VIDEO_URLS"

echo ""
echo "=========================================="
echo "  Retranscoding Complete"
echo "=========================================="
echo ""
echo "End time: $(date)"
echo ""
echo "Summary:"
echo "  Total videos:        $TOTAL"
echo -e "  ${GREEN}Successfully queued:   $SUCCESS${NC}"
echo -e "  ${YELLOW}Already processing:    $ALREADY_PROCESSING${NC}"
echo -e "  ${RED}Failed:                $FAILED${NC}"
echo ""
echo "Note: Jobs were submitted with LOW PRIORITY"
echo "Monitor progress at: https://live.nhrl.io/proxyMaker/"
echo ""


