$ErrorActionPreference = "Stop"

Write-Host "========================================================" -ForegroundColor Magenta
Write-Host "   CUCU NOTE AUTO-EVAL LOOP - INFINITE UNTIL DONE      " -ForegroundColor Magenta
Write-Host "   Phase 1: Backend API Test (curl/Invoke-RestMethod)   " -ForegroundColor Cyan
Write-Host "   Phase 2: Frontend UI Test (Playwright MCP via Gemini)" -ForegroundColor Cyan
Write-Host "   Loop: Vo han den khi ca 2 deu PASS                   " -ForegroundColor Cyan
Write-Host "========================================================" -ForegroundColor Magenta

# ==================== CAU HINH ====================
# Script chay tu thu muc plan/ nen path la tuong doi tu day
$PLAN_FILE   = "doing\2026-04-21-test-all-api-local.md"
$BE_URL      = "http://localhost:5005"
$FE_URL      = "http://localhost:3000"
$BACKEND_DIR = "D:\cnf\chatbot-canifa-feedback\miniapp\cuccu_note\backend"
$ITERATION   = 1

# ==================== DON DEP ====================
@("DONE.flag","be_result.txt","fe_result.txt","eval_be.txt","eval_fe.txt",
  "tmp_be_prompt.txt","tmp_fe_prompt.txt","tmp_fix_prompt.txt") | ForEach-Object {
    if (Test-Path $_) { Remove-Item $_ }
}

# ==================== KIEM TRA TRUOC ====================
Write-Host ""
Write-Host ">> PRE-CHECK: Kiem tra backend + frontend dang chay..." -ForegroundColor Yellow

try {
    Invoke-RestMethod -Uri "$BE_URL/health" -TimeoutSec 5 | Out-Null
    Write-Host "   [OK] Backend: $BE_URL" -ForegroundColor Green
} catch {
    Write-Host "   [WARN] Backend chua chay tai $BE_URL" -ForegroundColor Red
    Write-Host "   Hay chay: uvicorn server:app --reload --port 5000" -ForegroundColor Yellow
}

try {
    Invoke-WebRequest -Uri $FE_URL -TimeoutSec 5 -UseBasicParsing | Out-Null
    Write-Host "   [OK] Frontend: $FE_URL" -ForegroundColor Green
} catch {
    Write-Host "   [WARN] Frontend chua chay tai $FE_URL" -ForegroundColor Red
    Write-Host "   Hay chay: npm run dev (trong frontend/)" -ForegroundColor Yellow
}

# ==================== VONG LAP VO HAN ====================
while (!(Test-Path "DONE.flag")) {

    Write-Host ""
    Write-Host "========================================" -ForegroundColor Cyan
    Write-Host "   VONG LAP SO: $ITERATION              " -ForegroundColor Cyan
    Write-Host "========================================" -ForegroundColor Cyan

    # ──────────────────────────────────────────────────────
    # PHASE 1: BACKEND API TEST
    # ──────────────────────────────────────────────────────
    Write-Host ""
    Write-Host "=== PHASE 1: BACKEND API TEST ===" -ForegroundColor Yellow

    $beLines = @()

    $apis = @(
        @{ Name="health";      Url="$BE_URL/health";                   Method="GET";  Body=$null },
        @{ Name="auth/me";     Url="$BE_URL/api/v1/auth/me";           Method="GET";  Body=$null },
        @{ Name="memos/list";  Url="$BE_URL/api/v1/memos";             Method="GET";  Body=$null },
        @{ Name="memo/create"; Url="$BE_URL/api/v1/memos";             Method="POST"; Body='{"content":"[AutoTest] Ralph loop test memo","visibility":"PRIVATE"}' },
        @{ Name="search";      Url="$BE_URL/api/v1/search?q=test";     Method="GET";  Body=$null },
        @{ Name="teams/list";  Url="$BE_URL/api/v1/teams";             Method="GET";  Body=$null },
        @{ Name="deadlines";   Url="$BE_URL/api/v1/memos/deadlines";   Method="GET";  Body=$null },
        @{ Name="agent/chat";  Url="$BE_URL/api/agent/chat";           Method="POST"; Body='{"message":"xin chao"}' }
    )

    foreach ($api in $apis) {
        try {
            $params = @{ Uri=$api.Url; Method=$api.Method; TimeoutSec=15 }
            if ($api.Body) {
                $params.Body        = $api.Body
                $params.ContentType = "application/json"
            }
            Invoke-RestMethod @params | Out-Null
            $beLines += "BE $($api.Name): PASS"
            Write-Host "   [PASS] $($api.Name)" -ForegroundColor Green
        } catch {
            $err = $_.Exception.Message
            $beLines += "BE $($api.Name): FAIL - $err"
            Write-Host "   [FAIL] $($api.Name) - $err" -ForegroundColor Red
        }
    }

    $beLines | Out-File -Encoding utf8 be_result.txt

    # AI Judge Backend
    Write-Host ""
    Write-Host ">> AI Judge cham diem Backend..." -ForegroundColor Yellow

    $beJudge = "Doc file be_result.txt. DISABLE_AUTH=true nen tat ca API phai tra 200. Neu TAT CA PASS thi in: PASS_EVAL. Neu co FAIL thi in chi tiet loi va file Python can sua."
    $beJudge | Out-File -Encoding utf8 tmp_be_prompt.txt

    gemini --yolo -p "@tmp_be_prompt.txt @be_result.txt" | Out-File -Encoding utf8 eval_be.txt

    $bePass = Select-String -Path "eval_be.txt" -Pattern "PASS_EVAL" -Quiet

    if ($bePass) {
        Write-Host "   [RESULT] BACKEND: PASS" -ForegroundColor Green
    } else {
        Write-Host "   [RESULT] BACKEND: FAIL - Dang sua..." -ForegroundColor Red
        Get-Content eval_be.txt

        $fixPrompt = "Doc loi backend trong eval_be.txt. Backend nam tai: $BACKEND_DIR. Sua dung file Python bi loi. Chi sua code."
        $fixPrompt | Out-File -Encoding utf8 tmp_fix_prompt.txt
        Push-Location "D:\cnf\chatbot-canifa-feedback\miniapp\cuccu_note"
        gemini --yolo -p "@plan\tmp_fix_prompt.txt @plan\eval_be.txt"
        Pop-Location

        # Cho uvicorn hot-reload sau khi Gemini sua code
        Write-Host ">> Cho 8s de uvicorn hot-reload..." -ForegroundColor Gray
        Start-Sleep -Seconds 8

        # Health-check: neu server chet (Gemini sua code bi syntax error) -> tu restart
        $serverAlive = $false
        try {
            Invoke-RestMethod -Uri "$BE_URL/health" -TimeoutSec 4 | Out-Null
            $serverAlive = $true
            Write-Host "   [OK] Uvicorn van dang chay sau khi reload" -ForegroundColor Green
        } catch {
            Write-Host "   [DEAD] Server chet sau khi Gemini sua code! Dang tu restart..." -ForegroundColor Red
        }

        if (-not $serverAlive) {
            # Kill het process python dang chay tren port 5005
            $portPid = netstat -ano | Select-String ":5005 " | ForEach-Object {
                ($_ -split '\s+')[-1]
            } | Select-Object -First 1
            if ($portPid -and $portPid -match '^\d+$') {
                try { Stop-Process -Id $portPid -Force -ErrorAction SilentlyContinue } catch {}
                Write-Host "   [KILL] Da kill PID $portPid" -ForegroundColor Gray
            }
            Start-Sleep -Seconds 2

            # Restart uvicorn background
            Write-Host "   [RESTART] Khoi dong lai uvicorn port 5005..." -ForegroundColor Yellow
            Start-Process -FilePath "powershell" -ArgumentList @(
                "-NoProfile", "-Command",
                "Set-Location '$BACKEND_DIR'; .venv\Scripts\uvicorn server:app --reload --port 5005"
            ) -WindowStyle Hidden

            # Cho uvicorn len xong
            $maxWait = 20
            $waited = 0
            while ($waited -lt $maxWait) {
                Start-Sleep -Seconds 2
                $waited += 2
                try {
                    Invoke-RestMethod -Uri "$BE_URL/health" -TimeoutSec 3 | Out-Null
                    Write-Host "   [OK] Uvicorn da restart thanh cong sau ${waited}s" -ForegroundColor Green
                    break
                } catch {
                    Write-Host "   [WAIT] Cho uvicorn... ($waited/$maxWait s)" -ForegroundColor Gray
                }
            }
        }

        try {
            Add-Content $PLAN_FILE "### BE Fail - Vong $ITERATION ($(Get-Date -Format 'HH:mm'))"
            Get-Content eval_be.txt | Add-Content $PLAN_FILE
        } catch {
            Write-Host "   [WARN] Khong ghi duoc plan file: $_" -ForegroundColor Gray
        }

        $ITERATION++
        continue
    }

    # ──────────────────────────────────────────────────────
    # PHASE 2: FRONTEND UI TEST (PLAYWRIGHT via Gemini MCP)
    # ──────────────────────────────────────────────────────
    Write-Host ""
    Write-Host "=== PHASE 2: FRONTEND UI TEST (Playwright) ===" -ForegroundColor Yellow

    $fePromptLines = @(
        "May la AI QA Engineer. Hay dung Playwright MCP de test frontend CuCu Note tai: $FE_URL",
        "",
        "KICH BAN TEST (chay theo thu tu):",
        "1. Mo trang chu $FE_URL - Kiem tra page load khong loi",
        "2. Kiem tra danh sach memo hien thi duoc",
        "3. Kiem tra Navigation sidebar hien thi dung (Home, Explore, Deadlines)",
        "4. Mo trang /explore - Kiem tra hien thi memo public",
        "5. Click vao 1 memo - Kiem tra mo MemoDetail duoc",
        "6. Kiem tra nut menu 3 cham tren memo - dropdown hien ra",
        "7. Mo trang /deadlines - Kiem tra hien thi deadline sections",
        "",
        "Sau khi test xong, ghi ket qua theo format:",
        "FE [ten_test]: PASS",
        "FE [ten_test]: FAIL - <ly do>",
        "",
        "Neu TAT CA test PASS => in them dong cuoi: PASS_EVAL",
        "Neu co FAIL => in chi tiet va goi y fix."
    )
    $fePromptLines -join "`n" | Out-File -Encoding utf8 tmp_fe_prompt.txt

    Push-Location "D:\cnf\chatbot-canifa-feedback\miniapp\cuccu_note"
    gemini --yolo -p "@plan\tmp_fe_prompt.txt" | Tee-Object -FilePath "plan\fe_result.txt"
    Pop-Location

    $fePass = Select-String -Path "fe_result.txt" -Pattern "PASS_EVAL" -Quiet

    if ($fePass) {
        Write-Host "   [RESULT] FRONTEND: PASS" -ForegroundColor Green
    } else {
        Write-Host "   [RESULT] FRONTEND: FAIL" -ForegroundColor Red
        Get-Content fe_result.txt

        try {
            Add-Content $PLAN_FILE "### FE Fail - Vong $ITERATION ($(Get-Date -Format 'HH:mm'))"
            Get-Content fe_result.txt | Add-Content $PLAN_FILE
        } catch {
            Write-Host "   [WARN] Khong ghi duoc plan file: $_" -ForegroundColor Gray
        }

        $ITERATION++
        continue
    }

    # ──────────────────────────────────────────────────────
    # CA 2 PASS => XONG
    # ──────────────────────────────────────────────────────
    Write-Host ""
    Write-Host "========================================" -ForegroundColor Green
    Write-Host "   [DONE] CA BACKEND + FRONTEND PASS!  " -ForegroundColor Green
    Write-Host "   Hoan thanh sau $ITERATION vong lap   " -ForegroundColor Green
    Write-Host "========================================" -ForegroundColor Green

    New-Item -Path "DONE.flag" -ItemType File | Out-Null

    try {
        Add-Content $PLAN_FILE "---"
        Add-Content $PLAN_FILE "## Auto-Eval PASS - $(Get-Date -Format 'yyyy-MM-dd HH:mm')"
        Add-Content $PLAN_FILE "- Vong lap: $ITERATION"
        Add-Content $PLAN_FILE "- Backend: PASS"
        Add-Content $PLAN_FILE "- Frontend: PASS (Playwright)"
        Add-Content $PLAN_FILE "### Backend Results:"
        Get-Content be_result.txt | Add-Content $PLAN_FILE
        Add-Content $PLAN_FILE "### Frontend Results:"
        Get-Content fe_result.txt | Add-Content $PLAN_FILE
    } catch {
        Write-Host "   [WARN] Khong ghi plan file: $_" -ForegroundColor Gray
    }
}

@("tmp_be_prompt.txt","tmp_fe_prompt.txt","tmp_fix_prompt.txt") | ForEach-Object {
    if (Test-Path $_) { Remove-Item $_ }
}

Write-Host ""
Write-Host "Xem ket qua: plan\doing\2026-04-21-test-all-api-local.md" -ForegroundColor Green
