$ErrorActionPreference = "Stop" $repoRoot = Split-Path -Parent $PSScriptRoot $backendDir = Join-Path $repoRoot "backend" $python = Join-Path $backendDir ".venv\Scripts\python.exe" function Import-DotEnv { param([string]$Path) if (-not (Test-Path $Path)) { return } foreach ($line in Get-Content $Path) { if ($line -match '^\s*#' -or $line -match '^\s*$') { continue } if ($line -match '^\s*([^=]+)=(.*)$') { $name = $matches[1].Trim() $value = $matches[2].Trim() if ($value.Length -ge 2 -and (($value.StartsWith('"') -and $value.EndsWith('"')) -or ($value.StartsWith("'") -and $value.EndsWith("'")))) { $value = $value.Substring(1, $value.Length - 2) } Set-Item "env:$name" $value } } } function Stop-HxopsProcess { Get-CimInstance Win32_Process -Filter "Name='python.exe'" -ErrorAction SilentlyContinue | Where-Object { $_.CommandLine -and $_.CommandLine -match 'run\.py|worker_kb\.py|worker_shipping\.py|worker_shipping_notice\.py|worker_scheduler\.py' } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue } } function Stop-Port { param([int]$Port) Get-NetTCPConnection -LocalPort $Port -State Listen -ErrorAction SilentlyContinue | Select-Object -ExpandProperty OwningProcess -Unique | ForEach-Object { Stop-Process -Id $_ -Force -ErrorAction SilentlyContinue } } if (-not (Test-Path $python)) { throw "Backend virtualenv not found: $python" } Import-DotEnv (Join-Path $repoRoot ".env.shared") Import-DotEnv (Join-Path $repoRoot ".env.dev") Import-DotEnv (Join-Path $repoRoot ".env.local") Write-Host "[cleanup] stopping HXOPS processes and ports..." -ForegroundColor Yellow Stop-HxopsProcess Stop-Port 5052 Stop-Port 8881 Start-Sleep -Milliseconds 800 $env:FLASK_APP = "run.py" $env:FLASK_ENV = "development" $env:ENV_NAME = "dev" Push-Location $backendDir try { Write-Host "[db-migrate] running flask db upgrade..." -ForegroundColor Cyan & $python -m flask db upgrade if ($LASTEXITCODE -ne 0) { throw "Database migration failed with exit code $LASTEXITCODE" } } finally { Pop-Location } Write-Host "[prepare] completed" -ForegroundColor Green