#!/usr/bin/env pwsh

# 启动开发环境脚本
Write-Host "正在启动 Digital Embryo 开发环境..." -ForegroundColor Green

# 获取当前脚本所在目录
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path

# 前端目录路径
$FrontendDir = Join-Path $ScriptDir "embryo-frontend"
# 后端目录路径
$BackendDir = Join-Path $ScriptDir "embryo-backend"

# 检查目录是否存在
if (-not (Test-Path $FrontendDir)) {
    Write-Error "前端目录不存在: $FrontendDir"
    exit 1
}

if (-not (Test-Path $BackendDir)) {
    Write-Error "后端目录不存在: $BackendDir"
    exit 1
}

# 检查必要文件是否存在
$PackageJsonPath = Join-Path $FrontendDir "package.json"
$AppPyPath = Join-Path $BackendDir "app.py"

if (-not (Test-Path $PackageJsonPath)) {
    Write-Error "package.json 文件不存在: $PackageJsonPath"
    exit 1
}

if (-not (Test-Path $AppPyPath)) {
    Write-Error "app.py 文件不存在: $AppPyPath"
    exit 1
}

Write-Host "启动前端开发服务器..." -ForegroundColor Yellow
# 启动前端开发服务器
$FrontendJob = Start-Job -ScriptBlock {
    param($FrontendDir)
    Set-Location $FrontendDir
    npm run dev
} -ArgumentList $FrontendDir

Write-Host "启动后端API服务器..." -ForegroundColor Yellow
# 启动后端API服务器
$BackendJob = Start-Job -ScriptBlock {
    param($ScriptDir, $BackendDir)
    Set-Location $ScriptDir
    uv run $BackendDir/app.py
} -ArgumentList $ScriptDir, $BackendDir

Write-Host "两个服务都已启动!" -ForegroundColor Green
Write-Host "前端开发服务器通常运行在: http://localhost:5173" -ForegroundColor Cyan
Write-Host "后端API服务器通常运行在: http://localhost:5000" -ForegroundColor Cyan
Write-Host ""
Write-Host "按 Ctrl+C 停止所有服务" -ForegroundColor Red

# 等待任意作业完成或用户中断
try {
    # 持续监控作业状态
    while ($true) {
        $FrontendState = Get-Job -Id $FrontendJob.Id | Select-Object -ExpandProperty State
        $BackendState = Get-Job -Id $BackendJob.Id | Select-Object -ExpandProperty State

        # 检查是否有作业失败
        if ($FrontendState -eq "Failed") {
            Write-Error "前端服务启动失败"
            Receive-Job -Id $FrontendJob.Id
            break
        }

        if ($BackendState -eq "Failed") {
            Write-Error "后端服务启动失败"
            Receive-Job -Id $BackendJob.Id
            break
        }

        # 如果两个作业都完成了（正常或异常），退出循环
        if ($FrontendState -eq "Completed" -or $BackendState -eq "Completed") {
            break
        }

        Start-Sleep -Seconds 1
    }
}
catch {
    Write-Host "接收到中断信号，正在停止服务..." -ForegroundColor Yellow
}
finally {
    # 清理作业
    Write-Host "正在停止所有服务..." -ForegroundColor Yellow

    if ($FrontendJob) {
        Stop-Job -Id $FrontendJob.Id -ErrorAction SilentlyContinue
        Remove-Job -Id $FrontendJob.Id -Force -ErrorAction SilentlyContinue
    }

    if ($BackendJob) {
        Stop-Job -Id $BackendJob.Id -ErrorAction SilentlyContinue
        Remove-Job -Id $BackendJob.Id -Force -ErrorAction SilentlyContinue
    }

    Write-Host "所有服务已停止" -ForegroundColor Green
}