# 幼儿阅读教学服务平台 - 一键启动并预览
# 用法：在项目根目录执行 .\start.ps1 或在资源管理器中双击（若已关联 PowerShell）

$ErrorActionPreference = "Stop"
$Root = $PSScriptRoot

Write-Host "`n========================================" -ForegroundColor Cyan
Write-Host "  幼儿阅读教学服务平台 - 一键启动" -ForegroundColor Cyan
Write-Host "========================================`n" -ForegroundColor Cyan

# 启动后端（新窗口）
Write-Host "[1/3] 启动后端服务..." -ForegroundColor Blue
Start-Process powershell -ArgumentList "-NoExit", "-Command", "cd '$Root\reading-platform-backend'; npm run start:dev" -WindowStyle Normal

# 等待后端开始编译
Start-Sleep -Seconds 3

# 启动前端（新窗口）
Write-Host "[2/3] 启动前端服务..." -ForegroundColor Green
Start-Process powershell -ArgumentList "-NoExit", "-Command", "cd '$Root\reading-platform-frontend'; npm run dev" -WindowStyle Normal

# 等待前端就绪（Vite 默认 5173）
Write-Host "[3/3] 等待服务就绪并打开浏览器..." -ForegroundColor Gray
$url = "http://localhost:5173"
$maxWait = 45
$step = 2
$waited = 0
while ($waited -lt $maxWait) {
    try {
        $r = Invoke-WebRequest -Uri $url -UseBasicParsing -TimeoutSec 2 -ErrorAction SilentlyContinue
        if ($r.StatusCode -eq 200) { break }
    } catch {}
    Start-Sleep -Seconds $step
    $waited += $step
    Write-Host "  等待中... ${waited}s" -ForegroundColor DarkGray
}

Start-Process $url
Write-Host "`n已打开浏览器: $url" -ForegroundColor Green
Write-Host "后端: http://localhost:3000 | 前端: http://localhost:5173`n" -ForegroundColor Cyan
