# Silent Update Checker for List Forge
$ErrorActionPreference = "Stop"

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

Write-Log "Starting silent update check"

# Create output object
$result = @{
    status = "error"
    message = ""
    currentVersion = ""
    latestVersion = ""
    updateAvailable = $false
}

try {
    if (-not (Test-Path "version.txt")) {
        Write-Log "ERROR: version.txt not found"
        $result.message = "Version file not found"
        ConvertTo-Json $result
        exit 0
    }

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

    # Configuration
    $updateCheckUrl = "https://raw.githubusercontent.com/earth-seed/ListForge-Releases/main/latest-version.txt"
    
    # 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 1
            }
        }
    }
    
    if ($latestVersion -eq $null) {
        Write-Log "ERROR: Failed to check for updates after $maxRetries attempts"
        $result.message = "Failed to check for updates after $maxRetries attempts"
        ConvertTo-Json $result
        exit 0
    }
    
    $result.latestVersion = $latestVersion
    
    # Convert version strings to Version objects for proper comparison
    try {
        $currentVersionObj = [Version]$result.currentVersion
        $latestVersionObj = [Version]$result.latestVersion
        
        if ($latestVersionObj -gt $currentVersionObj) {
            Write-Log "Update available: $($result.currentVersion) -> $($result.latestVersion)"
            $result.status = "update_available"
            $result.updateAvailable = $true
            $result.message = "New version available"
        } else {
            Write-Log "Already up to date (version: $($result.currentVersion))"
            $result.status = "up_to_date"
            $result.message = "Up to date"
        }
    } catch {
        Write-Log "ERROR: Version comparison failed: $($_.Exception.Message)"
        $result.message = "Version comparison failed: $($_.Exception.Message)"
    }
} catch {
    Write-Log "ERROR: $($_.Exception.Message)"
    Write-Log "Stack trace: $($_.ScriptStackTrace)"
    $result.message = $_.Exception.Message
}

# Output JSON result
ConvertTo-Json $result 