Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"

$root = Split-Path -Parent $PSScriptRoot
Set-Location $root

function Get-CompatiblePythonCommand {
    $pyLauncher = Get-Command py -ErrorAction SilentlyContinue
    if ($pyLauncher) {
        foreach ($version in @("3.12", "3.11")) {
            try {
                & py "-$version" --version *> $null
                if ($LASTEXITCODE -eq 0) {
                    return @("py", "-$version")
                }
            } catch {
            }
        }
    }

    $pythonCommand = Get-Command python -ErrorAction SilentlyContinue
    if ($pythonCommand) {
        try {
            $pythonVersion = (& python -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')" 2>$null).Trim()
            if ($pythonVersion -in @("3.12", "3.11")) {
                return @("python")
            }
        } catch {
        }
    }

    return $null
}

function Invoke-Python {
    param(
        [string[]]$PythonCommand,
        [string[]]$Arguments
    )

    $exe = $PythonCommand[0]
    $prefix = @()
    if ($PythonCommand.Length -gt 1) {
        $prefix = $PythonCommand[1..($PythonCommand.Length - 1)]
    }

    & $exe @prefix @Arguments
}

$pythonCmd = Get-CompatiblePythonCommand
if (-not $pythonCmd) {
    Write-Host ""
    Write-Host "No compatible Python version was found."
    Write-Host "Desktop mode requires Python 3.12 or 3.11 for pywebview on Windows."
    Write-Host "Only Python 3.14 was detected, which will fail when installing pythonnet."
    Write-Host ""
    Write-Host "Install Python 3.12 first, then run:"
    Write-Host "  .\desktop\run_desktop_dev.ps1"
    exit 1
}

Write-Host "Using Python: $($pythonCmd -join ' ')"
Write-Host "Ensuring desktop dependencies..."
Invoke-Python -PythonCommand $pythonCmd -Arguments @("-m", "pip", "install", "-r", ".\desktop\requirements.txt")

Write-Host "Starting desktop app..."
Invoke-Python -PythonCommand $pythonCmd -Arguments @("-m", "desktop.app", "--mode", "dev", "--frontend-url", "http://127.0.0.1:5173", "--backend-url", "http://127.0.0.1:18080")
