# Start WSL mysql/redis (no Docker). Run before worker:rpa if ports closed.
$ErrorActionPreference = "Stop"
. (Join-Path $PSScriptRoot "lib.ps1")
. (Join-Path $PSScriptRoot "ensure-infra.ps1")

$root = $script:DevConfig.ProjectRoot
$wslPath = Get-WslInfraScriptPath -Root $root
$distro = Ensure-DevWslDistro

Write-DevLog "starting wsl infra ($distro)..." "Info"
$code = Invoke-DevWsl -BashCommand "export MYSQL_HOST_PORT=3307 MYSQL_ROOT_PASSWORD=changeme; bash '$wslPath' start"
if ($code -ne 0) {
    throw "wsl infra start failed"
}

$ep = Get-EnvDbEndpoints -Root $root
$infraHost = Resolve-InfraHost -Root $root -MysqlPort $ep.MysqlPort -RedisPort $ep.RedisPort
$redisUrl = "redis://${infraHost}:$($ep.RedisPort)"
if (-not (Wait-InfraReadyFromWindows -HostName $infraHost -MysqlPort $ep.MysqlPort -RedisPort $ep.RedisPort -RedisUrl $redisUrl)) {
    throw "infra ports not ready from Windows (host=$infraHost)"
}

$ports = Test-NativeInfraPorts -Root $root
if (-not $ports.Ok) {
    throw "ports not ready (host=$($ports.Host) mysql=$($ports.Mysql) redis=$($ports.Redis))"
}

Apply-DevInfraEnv -Root $root
Start-WslKeepAlive -Distro $distro
Write-DevLog "mysql:3307 + redis:6379 ready (host=$($ports.Host))" "Ok"
