#!/bin/bash
# Database Cleanup Script
# Scans database for missing files and removes their references
# Runs via systemd timer nightly at 3:00 AM

set -e

# Configuration
API_URL="http://localhost:8000/api/maintenance/cleanup/missing-files"
STATUS_URL="http://localhost:8000/api/maintenance/cleanup/status"
LOG_FILE="/opt/media-downloader/logs/db-cleanup.log"
TOKEN_SCRIPT="/opt/media-downloader/scripts/get-api-token.sh"

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

# Get API token
if [ ! -f "$TOKEN_SCRIPT" ]; then
    log "ERROR: API token script not found at $TOKEN_SCRIPT"
    exit 1
fi

$TOKEN_SCRIPT > /dev/null 2>&1
TOKEN=$(cat /tmp/api_token.txt 2>/dev/null)
if [ -z "$TOKEN" ]; then
    log "ERROR: Failed to get API token"
    exit 1
fi

log "Starting database cleanup (dry_run=false)"

# Start cleanup
RESPONSE=$(curl -s -X POST "$API_URL" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -d '{"dry_run": false}')

if [ $? -ne 0 ]; then
    log "ERROR: Failed to start cleanup"
    exit 1
fi

log "Cleanup started, waiting for completion..."

# Poll for status
MAX_WAIT=300  # 5 minutes max
WAITED=0
INTERVAL=5

while [ $WAITED -lt $MAX_WAIT ]; do
    sleep $INTERVAL
    WAITED=$((WAITED + INTERVAL))

    STATUS=$(curl -s "$STATUS_URL" -H "Authorization: Bearer $TOKEN")

    STATUS_CODE=$(echo "$STATUS" | grep -o '"status":"[^"]*"' | cut -d'"' -f4)

    case "$STATUS_CODE" in
        "completed")
            TOTAL_CHECKED=$(echo "$STATUS" | grep -o '"total_checked":[0-9]*' | cut -d':' -f2)
            TOTAL_MISSING=$(echo "$STATUS" | grep -o '"total_missing":[0-9]*' | cut -d':' -f2)
            TOTAL_REMOVED=$(echo "$STATUS" | grep -o '"total_removed":[0-9]*' | cut -d':' -f2)
            DURATION=$(echo "$STATUS" | grep -o '"duration_seconds":[0-9.]*' | cut -d':' -f2)

            log "SUCCESS: Cleanup completed"
            log "  Checked: $TOTAL_CHECKED files"
            log "  Missing: $TOTAL_MISSING files"
            log "  Removed: $TOTAL_REMOVED references"
            log "  Duration: ${DURATION}s"
            exit 0
            ;;
        "failed")
            ERROR=$(echo "$STATUS" | grep -o '"error":"[^"]*"' | cut -d'"' -f4)
            log "ERROR: Cleanup failed - $ERROR"
            exit 1
            ;;
        "running")
            log "Still running... (${WAITED}s elapsed)"
            ;;
        "no_scan")
            log "ERROR: Cleanup job not found"
            exit 1
            ;;
        *)
            log "WARNING: Unknown status - $STATUS_CODE"
            ;;
    esac
done

log "ERROR: Cleanup timed out after ${MAX_WAIT}s"
exit 1
