$ErrorActionPreference = "Stop"

Write-Host "--------------------------------------------------------"
Write-Host ">>> GEMINI AUTO-EVAL LOOP: AI JUDGE & BUILDER <<<"
Write-Host "--------------------------------------------------------"

$PLAN_FILE = "plan\doing\ai_stylist_plan.md"
$ITERATION = 1

if (Test-Path "DONE.flag") {
    Remove-Item "DONE.flag"
}

while (!(Test-Path "DONE.flag")) {

    Write-Host ">>> VONG LAP SO $ITERATION <<<" -ForegroundColor Cyan

    Write-Host ">> 1. GOI GEMINI BUILDER SUA CODE..." -ForegroundColor Yellow
    gemini --yolo -p "@${PLAN_FILE} @worker\stylist_engine.py Dao dien yeu cau doc loi ti vong truoc va tien hanh sua lai code trong worker\stylist_engine.py"

    Write-Host ">> 2. DANG DUMP KET QUA CAU HINH..." -ForegroundColor Yellow
    $env:PYTHONPATH = "C:\canifa-idea\chatbot-canifa-feedback\backend"
    .venv\Scripts\python.exe dump_matches.py | Out-File -Encoding utf8 fashion_output.txt

    Write-Host ">> 3. GOI GEMINI JUDGE CHAM DIEM..." -ForegroundColor Yellow
    $judgeLines = @(
        "@fashion_output.txt May la AI Judge Thoi Trang cap cao. Can than soi xem ket qua in ra trong file kia co bi 2 loi sau khong:",
        "1. Do bi tron sai nhom tuoi: Ao quan cua Nguoi lon DANG ket hop nham voi mot mon nao do co chu 'be' hoac 'kid'.",
        "2. Sai dip mac: Quan ao ngu/mac nha dua di choi... (Hoac mat tieu occasion).",
        "Neu ket qua 100% SACH SE, khong dinh loi, hay in ra duy nhat mot dong: PASS_EVAL.",
        "Nguoc lai, neu phat hien mon do nao sai trai, hay in ra chi tiet mon do de bao loi."
    )
    
    $judgeLines -join "`n" | Out-File -Encoding utf8 temp_judge_prompt.txt
    gemini --yolo -p "`@temp_judge_prompt.txt `@fashion_output.txt" | Out-File -Encoding utf8 eval_feedback.txt

    $hasPass = Select-String -Path "eval_feedback.txt" -Pattern "PASS_EVAL" -Quiet
    if ($hasPass) {
        Write-Host ">>> AI JUDGE PHAN QUYET: PASS !!!" -ForegroundColor Green
        New-Item -Path "DONE.flag" -ItemType File | Out-Null
        break
    } else {
        Write-Host ">>> AI JUDGE DANH FAIL. TRICH LOI:" -ForegroundColor Red
        Get-Content eval_feedback.txt
        Write-Host ">>> Chuan bi bat Gemini Builder sua tiep..." -ForegroundColor Yellow
        Start-Sleep -Seconds 3

        Add-Content -Path $PLAN_FILE -Value "`n--- LOI TU VONG $ITERATION ---"
        Get-Content eval_feedback.txt | Add-Content -Path $PLAN_FILE
    }

    $ITERATION++
}

Write-Host ">>> SELF-EVAL LOOP THANH CONG! <<<" -ForegroundColor Green
