# =============================================================================
# 本地开发 — 启动 Portal + 后端 (Windows PowerShell 版)
# =============================================================================

$ErrorActionPreference = "Stop"
$ProjectDir = Split-Path -Parent $PSScriptRoot

Write-Host "==========================================" -ForegroundColor Cyan
Write-Host "IT智能服务台 — 本地开发启动" -ForegroundColor Cyan
Write-Host "==========================================" -ForegroundColor Cyan

# 1. 初始化角色数据
Write-Host ""
Write-Host ">>> 初始化角色数据..." -ForegroundColor Yellow
Set-Location "$ProjectDir\backend"
python scripts/init_roles.py

# 2. 启动后端（后台）
Write-Host ""
Write-Host ">>> 启动后端服务..." -ForegroundColor Yellow
Set-Location "$ProjectDir\backend"
Start-Process -FilePath "uvicorn" -ArgumentList "app.main:app", "--reload", "--host", "0.0.0.0", "--port", "8000" -WorkingDirectory "$ProjectDir\backend" -PassThru | Tee-Object -Variable backendProc
Write-Host "后端 PID: $($backendProc.Id)"

# 3. 启动 Portal 前端
Write-Host ""
Write-Host ">>> 启动 Portal 前端..." -ForegroundColor Yellow
Set-Location "$ProjectDir\frontend-portal"
Start-Process -FilePath "npm" -ArgumentList "run", "dev" -WorkingDirectory "$ProjectDir\frontend-portal" -PassThru | Tee-Object -Variable portalProc
Write-Host "Portal PID: $($portalProc.Id)"

# 4. 启动 H5 前端
Write-Host ""
Write-Host ">>> 启动 H5 前端..." -ForegroundColor Yellow
Set-Location "$ProjectDir\frontend-h5"
Start-Process -FilePath "npm" -ArgumentList "run", "dev" -WorkingDirectory "$ProjectDir\frontend-h5" -PassThru | Tee-Object -Variable h5Proc
Write-Host "H5 PID: $($h5Proc.Id)"

# 5. 启动 Agent 前端
Write-Host ""
Write-Host ">>> 启动 Agent 前端..." -ForegroundColor Yellow
Set-Location "$ProjectDir\frontend-agent"
Start-Process -FilePath "npm" -ArgumentList "run", "dev" -WorkingDirectory "$ProjectDir\frontend-agent" -PassThru | Tee-Object -Variable agentProc
Write-Host "Agent PID: $($agentProc.Id)"

Write-Host ""
Write-Host "==========================================" -ForegroundColor Cyan
Write-Host "所有服务已启动！" -ForegroundColor Green
Write-Host "==========================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "访问地址："
Write-Host "  Portal: http://localhost:5176/itportal/" -ForegroundColor Yellow
Write-Host "  H5 用户端: http://localhost:5174/itdesk/" -ForegroundColor Yellow
Write-Host "  坐席工作台: http://localhost:5173/itagent/" -ForegroundColor Yellow
Write-Host "  后端 API: http://localhost:8000/docs" -ForegroundColor Yellow
Write-Host ""
Write-Host "停止所有服务: 关闭此窗口或按 Ctrl+C" -ForegroundColor Gray
Write-Host ""

# 等待用户按任意键退出
Read-Host "按 Enter 键停止所有服务"

# 停止所有进程
Stop-Process -Id $backendProc.Id, $portalProc.Id, $h5Proc.Id, $agentProc.Id -ErrorAction SilentlyContinue
Write-Host "已停止所有服务" -ForegroundColor Green
