# Phase 2 자동화 실행 스크립트 (PowerShell)
# 날짜: 2026-11-01 예정
# 용도: Phase 1 데이터 검증 → Phase 3 Go/No-Go 판단

param(
    [string]$DataFile = "",
    [switch]$DryRun = $false
)

# 색상 정의
$Green = "Green"
$Yellow = "Yellow"
$Red = "Red"

Write-Host "`n════════════════════════════════════" -ForegroundColor $Green
Write-Host "Phase 2 자동화 검증 도구" -ForegroundColor $Green
Write-Host "════════════════════════════════════`n" -ForegroundColor $Green

# 1. 환경 설정
Write-Host "[Step 1] 환경 설정" -ForegroundColor $Yellow
$ProjectDir = (Get-Item -Path $PSScriptRoot).Parent.FullName
$ToolsDir = Join-Path $ProjectDir "tools"
$ReportsDir = Join-Path $ProjectDir "docs\Phase2Reports"
$LogDir = Join-Path $ProjectDir "logs"
$DataDir = Join-Path $ProjectDir "data\phase1"

# 디렉토리 생성
@($LogDir, $DataDir, $ReportsDir) | ForEach-Object {
    if (-not (Test-Path $_)) {
        New-Item -ItemType Directory -Path $_ -Force | Out-Null
    }
}

$Timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
$LogFile = Join-Path $LogDir "phase2_execution_${Timestamp}.log"

Write-Host "Project Dir:   $ProjectDir"
Write-Host "Reports Dir:   $ReportsDir"
Write-Host "Log File:      $LogFile"
Write-Host "✅ 환경 준비 완료`n" -ForegroundColor $Green

# 2. 데이터 준비
Write-Host "[Step 2] 데이터 준비" -ForegroundColor $Yellow

if ([string]::IsNullOrEmpty($DataFile)) {
    # sample_phase1_data.csv 사용
    $DataFile = Join-Path $ToolsDir "sample_phase1_data.csv"
    Write-Host "샘플 데이터 사용: $DataFile"
} else {
    if (-not (Test-Path $DataFile)) {
        Write-Host "❌ 데이터 파일을 찾을 수 없습니다: $DataFile" -ForegroundColor $Red
        exit 1
    }
    Write-Host "사용자 데이터: $DataFile"
}

Write-Host "✅ 데이터 준비 완료`n" -ForegroundColor $Green

# 3. 검증 스크립트 실행
Write-Host "[Step 3] Phase 2 검증 실행" -ForegroundColor $Yellow
Write-Host "PBO, DSR, OOS 검증 중...`n"

Set-Location $ProjectDir

if ($DryRun) {
    Write-Host "🔄 DRY-RUN 모드: 실제 실행하지 않습니다"
    Write-Host "실행 명령어: python tools/phase2_verification_scripts.py $DataFile"
} else {
    # 실제 검증 실행
    python tools/phase2_verification_scripts.py $DataFile 2>&1 | Tee-Object -FilePath $LogFile
}

$VerificationResult = Join-Path $ProjectDir "phase2_results.json"

if (Test-Path $VerificationResult) {
    Write-Host "`n✅ 검증 완료: $VerificationResult`n" -ForegroundColor $Green
} else {
    Write-Host "`n❌ 검증 결과 파일 없음`n" -ForegroundColor $Red
    exit 1
}

# 4. 결과 분석
Write-Host "[Step 4] 결과 분석" -ForegroundColor $Yellow

$Results = Get-Content $VerificationResult | ConvertFrom-Json

$PboPass = $Results.pbo.passed
$DsrPass = $Results.dsr.passed
$OosPass = $Results.oos.passed

Write-Host "`n📊 Phase 2 검증 결과:" -ForegroundColor $Green
Write-Host "=" * 50
Write-Host "  PBO < 20%:  $(if ($PboPass) {'✅ PASS'} else {'❌ FAIL'}) ($($Results.pbo.pbo_pct)%)"
Write-Host "  DSR > 0.5:  $(if ($DsrPass) {'✅ PASS'} else {'❌ FAIL'}) ($($Results.dsr.dsr))"
Write-Host "  OOS < 2.5%: $(if ($OosPass) {'✅ PASS'} else {'❌ FAIL'}) ($($Results.oos.drift_pct)%)"
Write-Host "=" * 50

# Go/No-Go 판단
$AllPass = $PboPass -and $DsrPass -and $OosPass
$Decision = if ($AllPass) { "GO PHASE 3 🚀" } else { "RE-EVALUATE ⚠️" }

Write-Host "`n🎯 FINAL DECISION: $Decision`n" -ForegroundColor $(if ($AllPass) { $Green } else { $Yellow })

if ($AllPass) {
    Write-Host "✅ Phase 3 진행 승인" -ForegroundColor $Green
} else {
    Write-Host "❌ Phase 3 진행 불가 - 재검토 필요" -ForegroundColor $Yellow
}

# 5. 최종 리포트 생성
Write-Host "`n[Step 5] 최종 리포트 생성" -ForegroundColor $Yellow

$ReportContent = @"
# Phase 2 자동화 실행 리포트

**실행 날짜:** $Timestamp
**결과:** $Decision

## 검증 결과

| 메트릭 | 값 | 기준 | 상태 |
|--------|-----|------|------|
| PBO | $($Results.pbo.pbo_pct)% | < 20% | $(if ($PboPass) {'✅ PASS'} else {'❌ FAIL'}) |
| DSR | $($Results.dsr.dsr) | > 0.5 | $(if ($DsrPass) {'✅ PASS'} else {'❌ FAIL'}) |
| OOS | $($Results.oos.drift_pct)% | < 2.5% | $(if ($OosPass) {'✅ PASS'} else {'❌ FAIL'}) |

## 의사결정

**최종 판단:** $Decision

## 다음 단계

1. CTO 승인 확인
2. CFO 최종 검토
3. Phase 3 배포 준비 시작

---

**Report Generated:** $(Get-Date -Format "yyyy-MM-dd HH:mm:ss")
"@

$ReportFile = Join-Path $ReportsDir "PHASE_2_EXECUTION_SUMMARY_${Timestamp}.md"
$ReportContent | Out-File -FilePath $ReportFile -Encoding UTF8

Write-Host "✅ 리포트 생성 완료`n" -ForegroundColor $Green

# 6. 요약
Write-Host "`n════════════════════════════════════" -ForegroundColor $Green
Write-Host "Phase 2 자동화 완료" -ForegroundColor $Green
Write-Host "════════════════════════════════════`n" -ForegroundColor $Green

Write-Host "📋 생성된 파일:" -ForegroundColor $Green
Write-Host "  • 검증 결과:   $VerificationResult"
Write-Host "  • 실행 로그:   $LogFile"
Write-Host "  • 최종 리포트: $ReportFile"
Write-Host ""
Write-Host "📧 알림: 결과를 검토하고 팀과 공유하세요" -ForegroundColor $Yellow
Write-Host ""

# 종료 코드
if ($AllPass) {
    exit 0
} else {
    exit 1
}
