$ErrorActionPreference = "Continue" # Tranh bi dung dot ngot khi python in ra stderr
$env:PYTHONPATH = (Join-Path $PSScriptRoot "..")
$BACKEND_DIR = (Join-Path $PSScriptRoot "..")
$env:PYTHONIOENCODING="utf8"

Write-Host "========================================================" -ForegroundColor Magenta
Write-Host "   LEAD BOT AUTO-EVAL LOOP (EVALUATOR-OPTIMIZER)       " -ForegroundColor Magenta
Write-Host "========================================================" -ForegroundColor Magenta

# ==================== KHOI DONG BACKEND ====================
$PYTHON_EXEC = Join-Path $BACKEND_DIR ".venv\Scripts\python.exe"

Write-Host ""
Write-Host ">> DANG KHOI DONG UVICORN BACKEND (PORT 5000)..." -ForegroundColor Yellow
$backendProc = Start-Process -FilePath $PYTHON_EXEC -ArgumentList "-m uvicorn server:app --port 5000 --reload" -WorkingDirectory $BACKEND_DIR -PassThru -WindowStyle Normal

Write-Host ">> Cho 8s de server Uvicorn khoi dong hoan toan..." -ForegroundColor Gray
Start-Sleep -Seconds 8

# ==================== CLEAN UP ====================
@("DONE_LEAD.flag","tmp_eval_results.txt","tmp_claude_prompt.txt", "tmp_eval_errors.txt") | ForEach-Object {
    if (Test-Path $_) { Remove-Item $_ }
}

$ITERATION = 1
$EVAL_SCRIPT = Join-Path $PSScriptRoot "..\scripts\lead_test\run_eval.py"

# ==================== INFINITE LOOP ====================
try {
    while (!(Test-Path "DONE_LEAD.flag")) {

        Write-Host ""
        Write-Host "========================================" -ForegroundColor Cyan
        Write-Host "   ITERATION NUM: $ITERATION              " -ForegroundColor Cyan
        Write-Host "========================================" -ForegroundColor Cyan

        # ──────────────────────────────────────────────────────
        # PHASE 1: EVALUATOR SUB-AGENT (PYTHON SCRIPT RUN TEST)
        # ──────────────────────────────────────────────────────
        Write-Host ""
        Write-Host "=== PHASE 1: EVALUATOR CHAM BAI ===" -ForegroundColor Yellow
        
        # Chay python thong qua Start-Process de luu log an toan, khong lam crash Powershell script
        $evalParams = @{
            FilePath = $PYTHON_EXEC
            ArgumentList = """$EVAL_SCRIPT"""
            NoNewWindow = $true
            Wait = $true
            RedirectStandardOutput = "tmp_eval_results.txt"
            RedirectStandardError = "tmp_eval_errors.txt"
        }
        Start-Process @evalParams

        # Kiem tra ket qua file output
        if (Test-Path "tmp_eval_results.txt") {
            Get-Content "tmp_eval_results.txt" -Tail 15 | Write-Host -ForegroundColor DarkGray
            
            $rawLog = Get-Content "tmp_eval_results.txt" -Raw
            
            if ($rawLog -match "Server khong" -or $rawLog -match "Server khÃ´ng") {
                Write-Host "   [WARN] Server uvicorn chua san sang hoac bi ngat. Xin cho..." -ForegroundColor Red
                $ITERATION++
                Start-Sleep -Seconds 3
                continue
            }

            $failedCount = Select-String -Path "tmp_eval_results.txt" -Pattern "FAIL|PARTIAL" -AllMatches
            $isAllPass = ($failedCount -eq $null -or $failedCount.Count -eq 0) -and ($rawLog -match "ROUND \d+ DONE|LOOP HOÀN THÀNH|LOOP HOAN THANH")

            if ($isAllPass) {
                Write-Host "   [RESULT] 100% TEST PASS!" -ForegroundColor Green
                New-Item -Path "DONE_LEAD.flag" -ItemType File | Out-Null
                break
            } else {
                Write-Host "   [RESULT] CON LOI (Fail/Partial: $($failedCount.Count)). Chuyen cho Optimizer..." -ForegroundColor Red
            }
        } else {
            Write-Host "   [WARN] Khong tim thay file ket qua evaluatator. Tra thu file errors.txt:" -ForegroundColor Red
            if (Test-Path "tmp_eval_errors.txt") {
                Get-Content "tmp_eval_errors.txt" | Write-Host -ForegroundColor Red
            }
            $ITERATION++
            Start-Sleep -Seconds 3
            continue
        }

        # ──────────────────────────────────────────────────────
        # PHASE 2: OPTIMIZER SUB-AGENT (CLAUDE CODE CLI)
        # ──────────────────────────────────────────────────────
        Write-Host ""
        Write-Host "=== PHASE 2: OPTIMIZER (CLAUDE CODE CLI) ===" -ForegroundColor Yellow
        Write-Host ">> Goi Claude Code CLI doc loi va sua file..." -ForegroundColor Gray
        
        $evalOutput = Get-Content "tmp_eval_results.txt" -Raw
        
        $claudePrompt = @"
Hay dong vai mot AI Optimizer (Prompt Engineer & Backend Dev) bac thay. 
Duoi day la Bao Cao Danh Gia Loi tu Evaluator Sub-agent cho cuc Lead Bot cua chung ta tren cong 5000:

===== ERROR REPORT =====
$evalOutput
========================

NHIEM VU CUA BAN (La 1 con Sub-agent sua code):
Phan tich nguyen nhan cot loi khien cac case test bi FAIL/PARTIAL o tren. Dua vao nguyen nhan:
1. Tu dong sua file `$BACKEND_DIR/agent/lead_stage_agent/prompts.py` de va System Prompt hoac xu ly loi.
2. Hoac sua thuat toan `$BACKEND_DIR/agent/lead_stage_agent/lead_search_tool.py` (Vi du: kiem tra loi filter).
3. Nghiem cam KHONG DUOC sua file Script Evaluator `run_eval.py` hay de thi `test_cases.json`.
4. Khong can xin phep, hay tu dong sua file. Sau khi sua xong, giai thich ngan gon 1 dong roi dung.
"@

        $claudePrompt | Out-File -Encoding utf8 "tmp_claude_prompt.txt"

        try {
            $promptStr = Get-Content "tmp_claude_prompt.txt" -Raw
            Write-Host "[Gemini] Dang phan tich loi va va lo hong... Xin cho..." -ForegroundColor Cyan
            
            # Goi Gemini bang cmd de thuc thi yolo khong can hoi.
            $geminiParams = @{
                FilePath = "cmd.exe"
                ArgumentList = "/c", "cd /d D:\cnf\chatbot-canifa-feedback && gemini --yolo -p ""@backend\plan\tmp_claude_prompt.txt"""
                NoNewWindow = $true
                Wait = $true
            }
            Start-Process @geminiParams
            Write-Host ">> Gemini Optimizer da thuc thi hoan tat." -ForegroundColor Green
        } catch {
            Write-Host "   [ERROR] Khong the goi toi Gemini CLI." -ForegroundColor Red
        }

        Write-Host ">> Cho 5s de uvicorn 5000 hot-reload code moi..." -ForegroundColor Gray
        Start-Sleep -Seconds 5

        $ITERATION++
    }
} finally {
    # Don dep
    Write-Host ""
    Write-Host ">> TAT CON SERVER UVICORN PORT 5000..." -ForegroundColor Yellow
    if ($backendProc -and !$backendProc.HasExited) {
        Stop-Process -Id $backendProc.Id -Force
    }
}

# ==================== DONE THÀNH CÔNG ====================
Write-Host ""
Write-Host "========================================" -ForegroundColor Green
Write-Host "   [DONE] HOAN TAT AUTO-TRAIN LOOP!     " -ForegroundColor Green
Write-Host "   Tong so vong lap da chay: $ITERATION  " -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Green

@("tmp_eval_results.txt","tmp_claude_prompt.txt", "tmp_eval_errors.txt") | ForEach-Object {
    if (Test-Path $_) { Remove-Item $_ }
}
