$ErrorActionPreference = 'Stop'
$Root = Split-Path -Parent $PSScriptRoot
$VenvPython = Join-Path $Root '.venv\Scripts\python.exe'

function Get-Python312 {
  $Candidates = @(
    @{Exe = 'py'; Args = @('-3.12') },
    @{Exe = 'python'; Args = @() },
    @{Exe = 'python3'; Args = @() },
    @{Exe = 'py'; Args = @('-3') }
  )

  foreach ($Candidate in $Candidates) {
    $Command = Get-Command $Candidate.Exe -ErrorAction SilentlyContinue
    if (!$Command) {
      continue
    }

    $VersionArgs = @()
    $VersionArgs += $Candidate.Args
    $VersionArgs += @('-c', 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")')

    try {
      $Version = & $Command.Source @VersionArgs
      if ($LASTEXITCODE -ne 0 -or !$Version) {
        continue
      }
      $Parts = [string]$Version -split '\.'
      if ([int]$Parts[0] -eq 3 -and [int]$Parts[1] -ge 12) {
        return [pscustomobject]@{
          Exe = $Command.Source
          Args = $Candidate.Args
        }
      }
    }
    catch {
      continue
    }
  }

  return $null
}

function Install-Python312 {
  $Winget = Get-Command winget -ErrorAction SilentlyContinue
  if (!$Winget) {
    Write-Error 'Python 3.12 is missing and winget is unavailable. Install Python 3.12 from python.org, then rerun this script.'
  }

  winget install --id Python.Python.3.12 --accept-package-agreements --accept-source-agreements
  $MachinePath = [Environment]::GetEnvironmentVariable('Path', 'Machine')
  $UserPath = [Environment]::GetEnvironmentVariable('Path', 'User')
  $env:Path = "$MachinePath;$UserPath;$env:Path"
}

$Python = Get-Python312
if (!$Python) {
  Install-Python312
  $Python = Get-Python312
}

if (!$Python) {
  Write-Error 'Python 3.12 is still unavailable. Restart PowerShell or install Python 3.12 manually, then rerun this script.'
}

if (!(Test-Path $VenvPython)) {
  $VenvArgs = @()
  $VenvArgs += $Python.Args
  $VenvArgs += @('-m', 'venv', (Join-Path $Root '.venv'))
  & $Python.Exe @VenvArgs
}
& $VenvPython -m pip install --upgrade pip
& $VenvPython -m pip install -r (Join-Path $Root 'backend\requirements.txt')
& $VenvPython -m pip install -e (Join-Path $Root 'backend')
