# Apply ItemValues Optimized Indexes
# These indexes target the critical ItemValues table performance issue
# Note: Creates SQL file first, then executes it to avoid CONCURRENTLY transaction issues

. .\db-config.ps1

Write-Host "========================================" -ForegroundColor Cyan
Write-Host "Creating Optimized ItemValues Indexes" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "Target: library.ItemValues table" -ForegroundColor Yellow
Write-Host "Problem: 1.3 BILLION rows being scanned sequentially" -ForegroundColor Red
Write-Host "Solution: 3 targeted indexes" -ForegroundColor Green
Write-Host ""
Write-Host "This may take 10-30 minutes..." -ForegroundColor Yellow
Write-Host ""

# Create temporary SQL file (CONCURRENTLY requires running outside transaction)
$tempSqlFile = "temp_itemvalues_indexes.sql"

$sqlContent = @"
-- Optimized indexes for ItemValues table
-- Fixes the 1.3 billion row sequential scan issue

-- Index 1: CleanValue lookups (for genre/tag searches)
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_itemvalues_cleanvalue 
ON library."ItemValues" ("CleanValue") 
WHERE "CleanValue" IS NOT NULL;

-- Index 2: Value lookups (for direct value searches)
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_itemvalues_value 
ON library."ItemValues" ("Value") 
WHERE "Value" IS NOT NULL;

-- Index 3: ItemValueId + CleanValue for joins (ItemValuesMap to ItemValues)
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_itemvalues_id_cleanvalue 
ON library."ItemValues" ("ItemValueId", "CleanValue");
"@

# Write SQL to temp file WITHOUT BOM (UTF8 without BOM)
[System.IO.File]::WriteAllText((Join-Path $PWD $tempSqlFile), $sqlContent, (New-Object System.Text.UTF8Encoding $false))

Write-Host "Executing index creation script..." -ForegroundColor Cyan
Write-Host ""

# Execute the SQL file (allows CONCURRENTLY to work)
& $PSQL_PATH -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME -f $tempSqlFile

if ($LASTEXITCODE -eq 0) {
    Write-Host ""
    Write-Host "[OK] All 3 indexes created successfully!" -ForegroundColor Green
} else {
    Write-Host ""
    Write-Host "[FAILED] Some indexes may have failed to create" -ForegroundColor Red
    Write-Host "Check the output above for details" -ForegroundColor Yellow
}

# Clean up temp file
Remove-Item $tempSqlFile -ErrorAction SilentlyContinue

Write-Host ""
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "Index Creation Complete!" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""

# Verify indexes were created
Write-Host "Verifying indexes..." -ForegroundColor Yellow
$queryVerify = "SELECT indexrelname as indexname, pg_size_pretty(pg_relation_size(indexrelid)) as size FROM pg_stat_user_indexes WHERE schemaname = 'library' AND relname = 'ItemValues' AND indexrelname LIKE 'idx_itemvalues_%' ORDER BY indexrelname;"
& $PSQL_PATH -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME -c $queryVerify

Write-Host ""
Write-Host "Next steps:" -ForegroundColor Cyan
Write-Host "1. Use Jellyfin normally - browse, filter by genre and tags" -ForegroundColor Gray
Write-Host "2. Wait 1 week" -ForegroundColor Gray
Write-Host "3. Run diagnostics again using db-quick.ps1" -ForegroundColor Gray
Write-Host "4. Check improvement in ItemValues sequential scans" -ForegroundColor Gray
Write-Host ""
Write-Host "Expected improvement: 70-90 percent faster genre and tag queries!" -ForegroundColor Green
