# Remove SQLite from Deployment - Quick Implementation
# This script removes SQLite dependencies for PostgreSQL-only deployment

param(
    [Parameter(Mandatory=$false)]
    [switch]$DryRun,
    
    [Parameter(Mandatory=$false)]
    [switch]$RemoveProject
)

$ErrorActionPreference = "Stop"
$SolutionRoot = "E:\Projects\pgsql-jellyfin"

Write-Host ""
Write-Host "================================================================" -ForegroundColor Cyan
Write-Host "     Remove SQLite for PostgreSQL-Only Deployment" -ForegroundColor Cyan
Write-Host "================================================================" -ForegroundColor Cyan
Write-Host ""

if ($DryRun) {
    Write-Host "DRY RUN MODE - No changes will be made" -ForegroundColor Yellow
    Write-Host ""
}

# Step 1: Backup current state
Write-Host "Step 1: Creating backup..." -ForegroundColor Cyan
if (-not $DryRun) {
    Push-Location $SolutionRoot
    git stash push -m "Before SQLite removal"
    Write-Host "  Changes stashed" -ForegroundColor Green
} else {
    Write-Host "  Would stash current changes" -ForegroundColor Gray
}

# Step 2: Find SQLite references
Write-Host ""
Write-Host "Step 2: Finding SQLite references..." -ForegroundColor Cyan

$sqliteReferences = @()

# Check Jellyfin.Server.Implementations
$serverImpl = "$SolutionRoot\Jellyfin.Server.Implementations\Jellyfin.Server.Implementations.csproj"
if (Test-Path $serverImpl) {
    $content = Get-Content $serverImpl -Raw
    if ($content -match 'Jellyfin\.Database\.Providers\.Sqlite') {
        Write-Host "  Found: SQLite reference in Jellyfin.Server.Implementations" -ForegroundColor Yellow
        $sqliteReferences += @{
            File = $serverImpl
            Pattern = '<ProjectReference Include="[^"]*Jellyfin\.Database\.Providers\.Sqlite[^"]*" />'
        }
    }
}

# Check Emby.Server.Implementations
$embyImpl = "$SolutionRoot\Emby.Server.Implementations\Emby.Server.Implementations.csproj"
if (Test-Path $embyImpl) {
    $content = Get-Content $embyImpl -Raw
    if ($content -match 'Microsoft\.Data\.Sqlite') {
        Write-Host "  Found: SQLite package in Emby.Server.Implementations" -ForegroundColor Yellow
        $sqliteReferences += @{
            File = $embyImpl
            Pattern = '<PackageReference Include="Microsoft\.Data\.Sqlite"[^/]*/>'
        }
    }
}

if ($sqliteReferences.Count -eq 0) {
    Write-Host "  No SQLite references found" -ForegroundColor Green
    exit 0
}

# Step 3: Remove references
Write-Host ""
Write-Host "Step 3: Removing SQLite references..." -ForegroundColor Cyan

foreach ($ref in $sqliteReferences) {
    $fileName = Split-Path $ref.File -Leaf
    Write-Host "  Processing: $fileName" -ForegroundColor Gray
    
    if (-not $DryRun) {
        $content = Get-Content $ref.File -Raw
        $newContent = $content -replace $ref.Pattern, ''
        $newContent = $newContent -replace '(\r?\n){3,}', "`r`n`r`n"
        Set-Content -Path $ref.File -Value $newContent -NoNewline
        Write-Host "    Removed reference" -ForegroundColor Green
    } else {
        Write-Host "    Would remove SQLite reference" -ForegroundColor Gray
    }
}

# Step 4: Exclude SQLite project from solution (optional)
if ($RemoveProject) {
    Write-Host ""
    Write-Host "Step 4: Excluding SQLite project from solution..." -ForegroundColor Cyan
    
    $solutionFile = "$SolutionRoot\Jellyfin.sln"
    if (Test-Path $solutionFile) {
        if (-not $DryRun) {
            $slnContent = Get-Content $solutionFile -Raw
            $pattern = '(Project\("[^"]*"\) = "Jellyfin\.Database\.Providers\.Sqlite"[^E]*EndProject)'
            $replacement = "# REMOVED: SQLite Provider`r`n# " + '$1'
            $newSlnContent = $slnContent -replace $pattern, $replacement
            Set-Content -Path $solutionFile -Value $newSlnContent -NoNewline
            Write-Host "  SQLite project commented out in solution" -ForegroundColor Green
        } else {
            Write-Host "  Would comment out SQLite project" -ForegroundColor Gray
        }
    }
}

# Step 5: Clean build directories
Write-Host ""
Write-Host "Step 5: Cleaning build directories..." -ForegroundColor Cyan

$buildDirs = @(
    "$SolutionRoot\lib",
    "$SolutionRoot\Jellyfin.Server.Implementations\bin",
    "$SolutionRoot\Jellyfin.Server.Implementations\obj",
    "$SolutionRoot\Emby.Server.Implementations\bin",
    "$SolutionRoot\Emby.Server.Implementations\obj"
)

foreach ($dir in $buildDirs) {
    if (Test-Path $dir) {
        if (-not $DryRun) {
            Remove-Item $dir -Recurse -Force
            $dirName = Split-Path $dir -Leaf
            Write-Host "  Cleaned: $dirName" -ForegroundColor Green
        } else {
            $dirName = Split-Path $dir -Leaf
            Write-Host "  Would clean: $dirName" -ForegroundColor Gray
        }
    }
}

# Step 6: Test build
Write-Host ""
Write-Host "Step 6: Testing build..." -ForegroundColor Cyan

if (-not $DryRun) {
    Push-Location $SolutionRoot
    
    Write-Host "  Building solution..." -ForegroundColor Gray
    $buildOutput = dotnet build --configuration Release 2>&1
    
    if ($LASTEXITCODE -eq 0) {
        Write-Host "  Build successful" -ForegroundColor Green
    } else {
        Write-Host "  Build failed" -ForegroundColor Red
        Write-Host $buildOutput
        
        Write-Host ""
        Write-Host "Rolling back changes..." -ForegroundColor Yellow
        git stash pop
        exit 1
    }
    
    Pop-Location
} else {
    Write-Host "  Would run: dotnet build --configuration Release" -ForegroundColor Gray
}

# Step 7: Verify no SQLite DLLs
Write-Host ""
Write-Host "Step 7: Verifying no SQLite DLLs..." -ForegroundColor Cyan

$libFolder = "$SolutionRoot\lib\Release\net11.0"
if (Test-Path $libFolder) {
    $sqliteDlls = Get-ChildItem $libFolder -Filter "*Sqlite*" -Recurse
    
    if ($sqliteDlls.Count -eq 0) {
        Write-Host "  No SQLite DLLs found in output" -ForegroundColor Green
    } else {
        Write-Host "  Found SQLite DLLs:" -ForegroundColor Yellow
        $sqliteDlls | ForEach-Object { 
            Write-Host "    - $($_.Name)" -ForegroundColor Gray 
        }
    }
}

# Step 8: Calculate size reduction
Write-Host ""
Write-Host "Step 8: Calculating deployment size..." -ForegroundColor Cyan

if (Test-Path $libFolder) {
    $totalSize = (Get-ChildItem $libFolder -Recurse -File | Measure-Object -Property Length -Sum).Sum
    $sizeMB = [math]::Round($totalSize / 1MB, 2)
    Write-Host "  Deployment size: $sizeMB MB" -ForegroundColor White
}

# Summary
Write-Host ""
Write-Host "================================================================" -ForegroundColor Green
Write-Host "            SQLite Removal Complete" -ForegroundColor Green
Write-Host "================================================================" -ForegroundColor Green
Write-Host ""

if (-not $DryRun) {
    Write-Host "Changes made:" -ForegroundColor Cyan
    Write-Host "  - Removed SQLite project references" -ForegroundColor Green
    Write-Host "  - Removed SQLite package references" -ForegroundColor Green
    if ($RemoveProject) {
        Write-Host "  - Excluded SQLite project from solution" -ForegroundColor Green
    }
    Write-Host "  - Cleaned build directories" -ForegroundColor Green
    Write-Host "  - Verified build" -ForegroundColor Green
    
    Write-Host ""
    Write-Host "Next steps:" -ForegroundColor Cyan
    Write-Host "  1. Review changes: git diff" -ForegroundColor Gray
    Write-Host "  2. Test application: dotnet run --project Jellyfin.Server" -ForegroundColor Gray
    Write-Host "  3. Commit changes: git commit -am 'Remove SQLite support'" -ForegroundColor Gray
    
    Write-Host ""
    Write-Host "Rollback if needed:" -ForegroundColor Yellow
    Write-Host "  git stash pop" -ForegroundColor Gray
} else {
    Write-Host "Dry run complete - no changes made" -ForegroundColor Yellow
    Write-Host "Run without -DryRun to apply changes" -ForegroundColor Gray
}

if (-not $DryRun) {
    Pop-Location
}

Write-Host ""