# dev start - clean env then mysql/redis + migrate + workers + next dev
# Usage:
#   npm run dev:start
#   npm run dev:start -- -SkipClean
#   npm run dev:start -- -DeepClean
#   npm run dev:start -- -NoWorkers

param(
    [switch]$SkipClean,
    [switch]$DeepClean,
    [switch]$NoWorkers,
    [ValidateSet("auto", "docker", "native")]
    [string]$InfraMode = "auto"
)

$ErrorActionPreference = "Stop"
. (Join-Path $PSScriptRoot "lib.ps1")

$root = $script:DevConfig.ProjectRoot
$port = $script:DevConfig.NextPort
$bindHost = $script:DevConfig.NextBindHost
$lanHost = Resolve-DevLanHost -Configured $script:DevConfig.LanHost

Write-DevLog "=== chajia dev start (clean) ===" "Info"

if ($DeepClean) {
    & (Join-Path $PSScriptRoot "clean.ps1") -Deep
}
elseif (-not $SkipClean) {
    # Redis flush 延后到 Ensure-DevInfra 之后，避免 WSL 未就绪时长时间阻塞
    & (Join-Path $PSScriptRoot "clean.ps1") -SkipRedis
}
else {
    Stop-AllDevProcesses
}

if (-not (Test-Path (Join-Path $root ".env"))) {
    Copy-Item (Join-Path $root ".env.example") (Join-Path $root ".env")
    Write-DevLog "created .env from .env.example" "Warn"
}

Push-Location $root
try {
    $infra = Ensure-DevInfra -Root $root -Mode $InfraMode
    Apply-DevInfraEnv -Root $root
    Write-DevLog "infra backend: $infra (db host resolved)" "Ok"

    Write-DevLog "prisma generate + migrate..."
    Invoke-PrismaGenerateSafe -Root $root

    Invoke-NpmScript -ScriptName "db:deploy" -FailMessage "db:deploy failed"

    Write-DevLog "db seed..."
    Invoke-NpmScript -ScriptName "db:seed" -FailMessage "db:seed failed"

    Write-DevLog "smoke connect..."
    Invoke-NpmScript -ScriptName "smoke:connect" -FailMessage "smoke:connect failed"

    Invoke-FlushRedis -Root $root
}
finally {
    Pop-Location
}

if (-not $NoWorkers) {
    Start-DevBackgroundProcess -Name "worker-rpa" -Command "npm run worker:rpa" -Root $root
    Assert-DevWorkerHealthy -Name "worker-rpa"
    Start-Sleep -Seconds 1
    Start-DevBackgroundProcess -Name "worker-scheduler" -Command "npm run worker:scheduler" -Root $root
    Start-Sleep -Seconds 1
}

Ensure-DevLanFirewall

Start-DevBackgroundProcess -Name "next-dev" -Command "npx next dev -H $bindHost -p $port" -Root $root

Write-DevLog "wait next.js (max $($script:DevConfig.HttpTimeoutSec)s)..."
Wait-HttpOk -Url "http://localhost:$port" -TimeoutSec $script:DevConfig.HttpTimeoutSec
if ($lanHost) {
    $lanUrl = "http://${lanHost}:$port"
    if (Wait-HttpOk -Url $lanUrl -TimeoutSec 15) {
        Write-DevLog "LAN $lanUrl OK (share this with colleagues, not 172.x WSL IP)" "Ok"
    }
    else {
        Write-DevLog "LAN $lanUrl not reachable (check firewall or Wi-Fi AP isolation)" "Warn"
    }
}
else {
    Write-DevLog "LAN host not detected; colleagues cannot reach this PC" "Warn"
}

Write-Host ""
Write-DevLog "=== ready ===" "Ok"
$lanBase = if ($lanHost) { "http://${lanHost}:$port" } else { "http://localhost:$port" }
Write-Host "  -- local --"
Write-Host "  home          http://localhost:$port"
Write-Host "  embed demo    http://localhost:$port/embed-demo"
Write-Host "  admin login   http://localhost:$port/login  (admin_demo / Demo@123)"
Write-Host ""
Write-Host "  -- LAN (share with colleagues) --"
Write-Host "  home          $lanBase"
Write-Host "  embed demo    $lanBase/embed-demo"
Write-Host "  admin login   $lanBase/login  (admin_demo / Demo@123)"
Write-Host ""
Write-Host "  logs          $($script:DevConfig.LogDir)"
Write-Host "  stop/clean    npm run dev:stop | npm run dev:clean"
Write-Host ""
