param([switch]$Silent = $false)

# Enhanced logging for debugging
$logFile = "update.log"
function Write-Log {
    param([string]$Message)
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logMessage = "[$timestamp] $Message"
    if (-not $Silent) {
        Write-Host $logMessage
    }
    Add-Content -Path $logFile -Value $logMessage -ErrorAction SilentlyContinue
}

Write-Log "Starting update process (Silent: $Silent)"

# Wait for the app to close before updating
Write-Log "Waiting for List Forge to exit..."
Start-Sleep -Seconds 3

# More robust process detection and termination
$maxWaitTime = 30 # seconds
$waitTime = 0
$processes = @()

while ($waitTime -lt $maxWaitTime) {
    $processes = Get-Process list_forge -ErrorAction SilentlyContinue
    if (-not $processes) {
        Write-Log "List Forge process has exited"
        break
    }
    Write-Log "List Forge still running, waiting... ($waitTime/$maxWaitTime seconds)"
    Start-Sleep -Seconds 1
    $waitTime++
}

# If process is still running after waiting, force terminate it
if ($processes) {
    Write-Log "WARNING: List Forge did not exit within $maxWaitTime seconds, force terminating..."
    try {
        foreach ($proc in $processes) {
            Write-Log "Force terminating process ID: $($proc.Id)"
            Stop-Process -Id $proc.Id -Force -ErrorAction Stop
        }
        Start-Sleep -Seconds 2  # Give it a moment to fully terminate
        Write-Log "Process termination completed"
    } catch {
        Write-Log "ERROR: Failed to force terminate process: $($_.Exception.Message)"
        Write-Log "Proceeding with update anyway - some files may be locked"
    }
}

# Check for List Forge Updates
$ErrorActionPreference = "Stop"

# Ensure we're in the right directory
try {
    if (-not (Test-Path "version.txt")) {
        Write-Log "ERROR: version.txt not found. Please run this script from the List Forge installation directory."
        if (-not $Silent) {
            Write-Host "Press any key to exit..."
            $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
        }
        exit 1
    }

    # Read current version
    $currentVersion = Get-Content "version.txt"
    Write-Log "Current version: $currentVersion"

    # Configuration
    $updateCheckUrl = "https://raw.githubusercontent.com/earth-seed/ListForge-Releases/main/latest-version.txt"
    $downloadBaseUrl = "https://github.com/earth-seed/ListForge-Releases/releases/download"

    if (-not $Silent) {
        Write-Host "List Forge Update Checker"
        Write-Host "========================"
        Write-Host "Current version: $currentVersion"
        Write-Host "Checking for updates..."
    }

    # Check latest version with retry logic
    $maxRetries = 3
    $retryCount = 0
    $latestVersion = $null
    
    while ($retryCount -lt $maxRetries -and $latestVersion -eq $null) {
        try {
            Write-Log "Checking for updates (attempt $($retryCount + 1)/$maxRetries)..."
            $response = Invoke-WebRequest -Uri $updateCheckUrl -UseBasicParsing -TimeoutSec 30
            $latestVersion = $response.Content.Trim()
            Write-Log "Latest version found: $latestVersion"
            break
        } catch {
            $retryCount++
            Write-Log "Failed to check for updates (attempt $retryCount/$maxRetries): $($_.Exception.Message)"
            if ($retryCount -lt $maxRetries) {
                Start-Sleep -Seconds 2
            }
        }
    }
    
    if ($latestVersion -eq $null) {
        throw "Failed to check for updates after $maxRetries attempts"
    }

    # Convert version strings to Version objects for proper comparison
    try {
        $currentVersionObj = [Version]$currentVersion
        $latestVersionObj = [Version]$latestVersion
        
        if ($latestVersionObj -gt $currentVersionObj) {
            Write-Log "New version available: $latestVersion"
            if (-not $Silent) {
                Write-Host "`nNew version available: $latestVersion"
                Write-Host "Changes in this version:"
                Write-Host "- Visit https://github.com/earth-seed/ListForge-Releases/releases for details"
                
                $choice = Read-Host "`nWould you like to download and install the update? (Y/N)"
                if ($choice -ne 'Y' -and $choice -ne 'y') {
                    Write-Log "User declined update"
                    exit 0
                }
            }
            
            $downloadUrl = "$downloadBaseUrl/v$latestVersion/ListForge-$latestVersion-windows.zip"
            $downloadPath = "ListForge-Update.zip"
            $backupPath = "ListForge-Backup-$currentVersion"
            
            Write-Log "Preparing to update..."
            if (-not $Silent) {
                Write-Host "`nPreparing to update..."
            }
            
            # Create backup of current version
            Write-Log "Creating backup..."
            if (-not $Silent) {
                Write-Host "Creating backup..."
            }
            if (Test-Path $backupPath) {
                Remove-Item -Path $backupPath -Recurse -Force
            }
            New-Item -ItemType Directory -Path $backupPath | Out-Null
            Get-ChildItem -Exclude @("ListForge-Update.zip", "ListForge-Backup-*", "update.log") | Copy-Item -Destination $backupPath -Recurse
            
            # Download update with retry logic
            Write-Log "Downloading update from: $downloadUrl"
            if (-not $Silent) {
                Write-Host "Downloading update..."
            }
            
            $downloadRetries = 3
            $downloadSuccess = $false
            
            for ($i = 1; $i -le $downloadRetries; $i++) {
                try {
                    Write-Log "Download attempt $i/$downloadRetries"
                    Invoke-WebRequest -Uri $downloadUrl -OutFile $downloadPath -UseBasicParsing -TimeoutSec 60
                    
                    # Verify download
                    if ((Test-Path $downloadPath) -and ((Get-Item $downloadPath).Length -gt 0)) {
                        Write-Log "Download completed successfully"
                        $downloadSuccess = $true
                        break
                    } else {
                        throw "Downloaded file is empty or missing"
                    }
                } catch {
                    Write-Log "Download attempt $i failed: $($_.Exception.Message)"
                    if ($i -lt $downloadRetries) {
                        Start-Sleep -Seconds 3
                    }
                }
            }
            
            if (-not $downloadSuccess) {
                throw "Failed to download update after $downloadRetries attempts"
            }
            
            if (-not $Silent) {
                Write-Host "Download complete."
            }
            
            # Extract update with retry logic
            Write-Log "Installing update..."
            if (-not $Silent) {
                Write-Host "Installing update..."
            }
            
            $extractRetries = 3
            $extractSuccess = $false
            
            for ($i = 1; $i -le $extractRetries; $i++) {
                try {
                    Write-Log "Extraction attempt $i/$extractRetries"
                    Expand-Archive -Path $downloadPath -DestinationPath "." -Force
                    Remove-Item -Path $downloadPath -Force
                    Write-Log "Update extraction completed"
                    $extractSuccess = $true
                    break
                } catch {
                    Write-Log "Extraction attempt $i failed: $($_.Exception.Message)"
                    if ($i -lt $extractRetries) {
                        Write-Log "Waiting 3 seconds before retry..."
                        Start-Sleep -Seconds 3
                    }
                }
            }
            
            if (-not $extractSuccess) {
                throw "Failed to extract update after $extractRetries attempts"
            }
            
            Write-Log "Update completed successfully!"
            if (-not $Silent) {
                Write-Host "`nUpdate completed successfully!"
                Write-Host "A backup of your previous version has been saved to: $backupPath"
                Write-Host "If you experience any issues, you can restore from the backup folder."
                Write-Host "COMPLETE"
            }
            
            # Start the updated application
            Write-Log "Starting the updated version..."
            if (-not $Silent) {
                Write-Host "`nStarting the updated version..."
            }
            
            try {
                Start-Process -FilePath ".\list_forge.exe" -ErrorAction Stop
                Write-Log "Successfully started updated application"
            } catch {
                Write-Log "ERROR: Failed to start updated application: $($_.Exception.Message)"
                if (-not $Silent) {
                    Write-Host "`nERROR: Failed to start the updated application."
                    Write-Host "Please manually start List Forge from the installation directory."
                    Write-Host "Press any key to exit..."
                    $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
                }
            }
            
            # Exit the script
            exit 0
        } else {
            Write-Log "Already up to date (version: $currentVersion)"
            if (-not $Silent) {
                Write-Host "`nYou have the latest version!"
                Write-Host "Press any key to exit..."
                $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
            }
        }
    } catch {
        Write-Log "ERROR: Version comparison failed: $($_.Exception.Message)"
        throw "Version comparison failed: $($_.Exception.Message)"
    }
} catch {
    Write-Log "ERROR: $($_.Exception.Message)"
    Write-Log "Stack trace: $($_.ScriptStackTrace)"
    
    if (-not $Silent) {
        Write-Host "`nError: $_"
        Write-Host "`nIf the problem persists, please:"
        Write-Host "1. Check your internet connection"
        Write-Host "2. Visit https://github.com/earth-seed/ListForge-Releases/releases for manual download"
        Write-Host "3. Contact support if needed"
        Write-Host "`nPress any key to exit..."
        $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
    }
    exit 1
}