# Ralph Wiggum: Windows PowerShell Wrapper
# 
# Workaround for Windows where cursor-agent CLI is not available.
# This script uses Cursor's API/MCP to run Ralph iterations.
#
# Usage:
#   .\.cursor\ralph-scripts\ralph-windows.ps1
#   .\.cursor\ralph-scripts\ralph-windows.ps1 -Iterations 5 -Model "gpt-5.2-high"

param(
    [int]$Iterations = 1,
    [string]$Model = "opus-4.5-thinking",
    [string]$Workspace = ".",
    [switch]$SkipConfirm
)

$ErrorActionPreference = "Stop"

# Resolve workspace path
if ($Workspace -eq ".") {
    $Workspace = (Get-Location).Path
} else {
    $Workspace = (Resolve-Path $Workspace).Path
}

$RalphDir = Join-Path $Workspace ".ralph"
$TaskFile = Join-Path $Workspace "RALPH_TASK.md"

# Check prerequisites
if (-not (Test-Path $TaskFile)) {
    Write-Host "❌ RALPH_TASK.md not found in $Workspace" -ForegroundColor Red
    exit 1
}

# Initialize .ralph directory
if (-not (Test-Path $RalphDir)) {
    New-Item -ItemType Directory -Path $RalphDir -Force | Out-Null
}

Write-Host "═══════════════════════════════════════════════════════════════════" -ForegroundColor Cyan
Write-Host "🐛 Ralph Wiggum: Windows PowerShell Wrapper" -ForegroundColor Cyan
Write-Host "═══════════════════════════════════════════════════════════════════" -ForegroundColor Cyan
Write-Host ""
Write-Host "⚠️  Note: cursor-agent CLI is not available on Windows." -ForegroundColor Yellow
Write-Host "   This script will guide you to run Ralph manually via Cursor chat." -ForegroundColor Yellow
Write-Host ""
Write-Host "Workspace: $Workspace" -ForegroundColor Green
Write-Host "Iterations: $Iterations" -ForegroundColor Green
Write-Host "Model: $Model" -ForegroundColor Green
Write-Host ""

# Read task file
$TaskContent = Get-Content $TaskFile -Raw
Write-Host "📋 Task Summary:" -ForegroundColor Cyan
Write-Host "─────────────────────────────────────────────────────────────────" -ForegroundColor Gray
Get-Content $TaskFile -Head 30
Write-Host "─────────────────────────────────────────────────────────────────" -ForegroundColor Gray
Write-Host ""

# Count criteria
$TotalCriteria = ([regex]::Matches($TaskContent, '(?m)^\s*([-*]|\d+\.)\s+\[(x| )\]')).Count
$DoneCriteria = ([regex]::Matches($TaskContent, '(?m)^\s*([-*]|\d+\.)\s+\[x\]')).Count
$Remaining = $TotalCriteria - $DoneCriteria

Write-Host "Progress: $DoneCriteria / $TotalCriteria criteria complete ($Remaining remaining)" -ForegroundColor $(if ($Remaining -eq 0) { "Green" } else { "Yellow" })
Write-Host ""

if ($Remaining -eq 0 -and $TotalCriteria -gt 0) {
    Write-Host "🎉 Task already complete! All criteria are checked." -ForegroundColor Green
    exit 0
}

if (-not $SkipConfirm) {
    $Confirm = Read-Host "Run $Iterations iteration(s)? [Y/n]"
    if ($Confirm -match "^[Nn]$") {
        Write-Host "Aborted." -ForegroundColor Yellow
        exit 0
    }
}

Write-Host ""
Write-Host "═══════════════════════════════════════════════════════════════════" -ForegroundColor Cyan
Write-Host "📝 Manual Ralph Execution Guide" -ForegroundColor Cyan
Write-Host "═══════════════════════════════════════════════════════════════════" -ForegroundColor Cyan
Write-Host ""
Write-Host "Since cursor-agent CLI is not available on Windows, you need to:" -ForegroundColor Yellow
Write-Host ""
Write-Host "1. Open Cursor IDE" -ForegroundColor White
Write-Host "2. Open this workspace: $Workspace" -ForegroundColor White
Write-Host "3. In Cursor chat, use this command:" -ForegroundColor White
Write-Host ""
Write-Host "   /ralph-loop `"Refactor & tối ưu backend CuCu: kiến trúc FastAPI + agent clean, tách rõ layer, xoá dead code, tránh bottleneck (N+1 query, DB, cache, rate limit), đảm bảo 'cd backend && pytest' luôn xanh.`"" -ForegroundColor Cyan
Write-Host ""
Write-Host "4. The command will update RALPH_TASK.md and show you bash commands" -ForegroundColor White
Write-Host "5. Since bash commands won't work, you can:" -ForegroundColor White
Write-Host "   - Use Cursor's built-in agent features to work on the task" -ForegroundColor White
Write-Host "   - Or use WSL (Windows Subsystem for Linux) to run bash scripts" -ForegroundColor White
Write-Host ""
Write-Host "═══════════════════════════════════════════════════════════════════" -ForegroundColor Cyan
Write-Host ""

# Alternative: Try to use Cursor MCP if available
Write-Host "💡 Alternative: Using Cursor MCP Server (if configured)" -ForegroundColor Cyan
Write-Host ""
Write-Host "If you have Cursor MCP server configured, you can use it to run Ralph." -ForegroundColor Yellow
Write-Host "Check your MCP configuration in Cursor settings." -ForegroundColor Yellow
Write-Host ""

# Save iteration state
$IterationFile = Join-Path $RalphDir ".iteration"
$CurrentIteration = if (Test-Path $IterationFile) { [int](Get-Content $IterationFile) } else { 0 }
$NextIteration = $CurrentIteration + 1
$NextIteration | Out-File $IterationFile -NoNewline

Write-Host "✅ Iteration state saved: $NextIteration" -ForegroundColor Green
Write-Host ""
Write-Host "Next steps:" -ForegroundColor Cyan
Write-Host "  • Review RALPH_TASK.md" -ForegroundColor White
Write-Host "  • Use Cursor chat with /ralph-loop command" -ForegroundColor White
Write-Host "  • Or install WSL and run bash scripts there" -ForegroundColor White
Write-Host ""

