# WACE 솔루션 - 전체 서비스 시작 (병렬 최적화) - PowerShell 버전
# 실행 방법: powershell -ExecutionPolicy Bypass -File .\scripts\dev\start-all-parallel.ps1

# UTF-8 출력 설정
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$OutputEncoding = [System.Text.Encoding]::UTF8

# 스크립트 위치에서 루트 디렉토리로 이동
$scriptPath = Split-Path -Parent $MyInvocation.MyCommand.Definition
Set-Location (Join-Path $scriptPath "..\..") 

# 시작 시간 기록
$startTime = Get-Date
$startTimeFormatted = $startTime.ToString("yyyy-MM-dd HH:mm:ss")

Write-Host ""
Write-Host "============================================" -ForegroundColor Cyan
Write-Host "WACE 솔루션 - 전체 서비스 시작 (병렬 최적화)" -ForegroundColor Cyan
Write-Host "============================================" -ForegroundColor Cyan
Write-Host "[시작 시간] $startTimeFormatted" -ForegroundColor Yellow
Write-Host ""

# Docker Desktop 실행 확인
Write-Host "[1/5] Docker Desktop 상태 확인 중..." -ForegroundColor White
$dockerCheck = docker --version 2>&1
if ($LASTEXITCODE -ne 0) {
    Write-Host "[ERROR] Docker Desktop이 실행되지 않았습니다!" -ForegroundColor Red
    Write-Host "        Docker Desktop을 먼저 실행해주세요." -ForegroundColor Red
    Read-Host "계속하려면 Enter를 누르세요"
    exit 1
}
Write-Host "[OK] Docker Desktop이 실행 중입니다." -ForegroundColor Green
Write-Host ""

# 기존 컨테이너 정리
Write-Host "[2/5] 기존 컨테이너 정리 중..." -ForegroundColor White
docker rm -f pms-backend-win pms-frontend-win 2>$null | Out-Null
docker network rm pms-network 2>$null | Out-Null
docker network create pms-network 2>$null | Out-Null
Write-Host "[OK] 컨테이너 정리 완료" -ForegroundColor Green
Write-Host ""

# 병렬 빌드 시작
$parallelStart = Get-Date
Write-Host "[3/5] 이미지 빌드 중... (백엔드 + 프론트엔드 병렬)" -ForegroundColor White
Write-Host "      이 작업은 시간이 걸릴 수 있습니다..." -ForegroundColor Gray
Write-Host ""

# 병렬 빌드 실행
$backendBuildJob = Start-Job -ScriptBlock {
    param($workDir)
    Set-Location $workDir
    $output = docker-compose -f docker-compose.backend.win.yml build 2>&1
    return @{
        Success = $LASTEXITCODE -eq 0
        Output = $output
    }
} -ArgumentList $PWD.Path

$frontendBuildJob = Start-Job -ScriptBlock {
    param($workDir)
    Set-Location $workDir
    $output = docker-compose -f docker-compose.frontend.win.yml build 2>&1
    return @{
        Success = $LASTEXITCODE -eq 0
        Output = $output
    }
} -ArgumentList $PWD.Path

Write-Host "      백엔드 빌드 진행 중..." -ForegroundColor Gray
Write-Host "      프론트엔드 빌드 진행 중..." -ForegroundColor Gray
Write-Host ""

# 빌드 완료 대기
$null = Wait-Job -Job $backendBuildJob, $frontendBuildJob

$backendResult = Receive-Job -Job $backendBuildJob
$frontendResult = Receive-Job -Job $frontendBuildJob

Remove-Job -Job $backendBuildJob, $frontendBuildJob -Force

# 빌드 결과 확인
$buildFailed = $false

if ($backendResult.Success) {
    Write-Host "[OK] 백엔드 빌드 완료" -ForegroundColor Green
} else {
    Write-Host "[ERROR] 백엔드 빌드 실패!" -ForegroundColor Red
    Write-Host $backendResult.Output -ForegroundColor Red
    $buildFailed = $true
}

if ($frontendResult.Success) {
    Write-Host "[OK] 프론트엔드 빌드 완료" -ForegroundColor Green
} else {
    Write-Host "[ERROR] 프론트엔드 빌드 실패!" -ForegroundColor Red
    Write-Host $frontendResult.Output -ForegroundColor Red
    $buildFailed = $true
}

if ($buildFailed) {
    Read-Host "빌드 실패. Enter를 누르면 종료됩니다"
    exit 1
}

$parallelEnd = Get-Date
$parallelDuration = ($parallelEnd - $parallelStart).TotalSeconds
Write-Host "[INFO] 빌드 소요 시간: $([math]::Round($parallelDuration))초" -ForegroundColor Yellow
Write-Host ""

# 서비스 시작
$serviceStart = Get-Date
Write-Host "[4/5] 서비스 시작 중..." -ForegroundColor White

# 기존 컨테이너 정리
docker-compose -f docker-compose.backend.win.yml down -v 2>$null | Out-Null
docker-compose -f docker-compose.frontend.win.yml down -v 2>$null | Out-Null

# 백엔드 시작
Write-Host "      백엔드 서비스 시작..." -ForegroundColor Gray
docker-compose -f docker-compose.backend.win.yml up -d 2>&1 | Out-Null
if ($LASTEXITCODE -ne 0) {
    Write-Host "[ERROR] 백엔드 시작 실패!" -ForegroundColor Red
    Read-Host "계속하려면 Enter를 누르세요"
    exit 1
}

# 프론트엔드 시작
Write-Host "      프론트엔드 서비스 시작..." -ForegroundColor Gray
docker-compose -f docker-compose.frontend.win.yml up -d 2>&1 | Out-Null
if ($LASTEXITCODE -ne 0) {
    Write-Host "[ERROR] 프론트엔드 시작 실패!" -ForegroundColor Red
    Read-Host "계속하려면 Enter를 누르세요"
    exit 1
}

Write-Host "[OK] 서비스 시작 완료" -ForegroundColor Green

$serviceEnd = Get-Date
$serviceDuration = ($serviceEnd - $serviceStart).TotalSeconds
Write-Host "[INFO] 서비스 시작 소요 시간: $([math]::Round($serviceDuration))초" -ForegroundColor Yellow
Write-Host ""

# 안정화 대기
Write-Host "[5/5] 서비스 안정화 대기 중... (10초)" -ForegroundColor White
Start-Sleep -Seconds 10
Write-Host ""

Write-Host "============================================" -ForegroundColor Cyan
Write-Host "[완료] 모든 서비스가 시작되었습니다!" -ForegroundColor Green
Write-Host "============================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "[DATABASE] PostgreSQL: http://39.117.244.52:11132" -ForegroundColor White
Write-Host "[BACKEND]  Node.js API: http://localhost:8080/api" -ForegroundColor White
Write-Host "[FRONTEND] Next.js:     http://localhost:9771" -ForegroundColor White
Write-Host ""
Write-Host "[서비스 상태 확인]" -ForegroundColor Yellow
Write-Host "  docker-compose -f docker-compose.backend.win.yml ps" -ForegroundColor Gray
Write-Host "  docker-compose -f docker-compose.frontend.win.yml ps" -ForegroundColor Gray
Write-Host ""
Write-Host "[로그 확인]" -ForegroundColor Yellow
Write-Host "  백엔드:   docker-compose -f docker-compose.backend.win.yml logs -f" -ForegroundColor Gray
Write-Host "  프론트엔드: docker-compose -f docker-compose.frontend.win.yml logs -f" -ForegroundColor Gray
Write-Host ""
Write-Host "[서비스 중지]" -ForegroundColor Yellow
Write-Host "  .\scripts\dev\stop-all.ps1" -ForegroundColor Gray
Write-Host ""

# 종료 시간 계산
$endTime = Get-Date
$endTimeFormatted = $endTime.ToString("yyyy-MM-dd HH:mm:ss")
$totalDuration = ($endTime - $startTime).TotalSeconds
$minutes = [math]::Floor($totalDuration / 60)
$seconds = [math]::Round($totalDuration % 60)

Write-Host "============================================" -ForegroundColor Cyan
Write-Host "[종료 시간] $endTimeFormatted" -ForegroundColor Yellow
Write-Host "[총 소요 시간] ${minutes}분 ${seconds}초" -ForegroundColor Yellow
Write-Host "  - 빌드: $([math]::Round($parallelDuration))초" -ForegroundColor Gray
Write-Host "  - 서비스 시작: $([math]::Round($serviceDuration))초" -ForegroundColor Gray
Write-Host "============================================" -ForegroundColor Cyan

Read-Host "계속하려면 Enter를 누르세요"
