$ErrorActionPreference = "Stop"

$root = Split-Path -Parent $MyInvocation.MyCommand.Path | Split-Path -Parent
Set-Location $root

Write-Host "=== RagGo Python gRPC Service ===" -ForegroundColor Cyan
Write-Host ""

# Check if venv exists
if (-not (Test-Path ".venv")) {
    Write-Host "[!] Virtual environment not found. Please run setup first." -ForegroundColor Red
    Write-Host "    Run: start-raggo.bat" -ForegroundColor Yellow
    pause
    exit 1
}

# Activate virtual environment
Write-Host "[*] Activating virtual environment..." -ForegroundColor Yellow
& ".venv\Scripts\Activate.ps1"

# Check if dependencies are installed
Write-Host "[*] Checking dependencies..." -ForegroundColor Yellow
$pipList = python -m pip list 2>&1
if ($pipList -notmatch "grpcio") {
    Write-Host "[!] Dependencies not installed. Installing now..." -ForegroundColor Yellow
    python -m pip install -r python_service\requirements.txt
    if ($LASTEXITCODE -ne 0) {
        Write-Host "[!] Failed to install dependencies" -ForegroundColor Red
        pause
        exit 1
    }
}

# Start Python service
Write-Host "[*] Starting gRPC service on port 50051..." -ForegroundColor Green
Write-Host ""
python python_service\raggo_service.py

# If we get here, service stopped
Write-Host ""
Write-Host "[*] Python service stopped" -ForegroundColor Yellow
pause
