# V3Q.AI Windows Server Installation Script
# Run as Administrator in PowerShell
#
# Usage:
#   cd C:\V3Q\middleware
#   .\scripts\install_windows.ps1

Write-Host "============================================" -ForegroundColor Cyan
Write-Host "  V3Q.AI Installation - Windows Server" -ForegroundColor Cyan
Write-Host "============================================" -ForegroundColor Cyan
Write-Host ""

# [1/9] Check prerequisites
Write-Host "[1/9] Checking prerequisites..." -ForegroundColor Yellow

# Python
$python = Get-Command python -ErrorAction SilentlyContinue
if (-not $python) {
    Write-Host "  FAIL: Python not found. Install Python 3.12+ from https://python.org" -ForegroundColor Red
    Write-Host "        During install, check 'Add python.exe to PATH'" -ForegroundColor Yellow
    exit 1
}
$pyVersion = python --version 2>&1
$pyMajMin = [regex]::Match($pyVersion, '(\d+)\.(\d+)')
if ($pyMajMin.Groups[1].Value -lt 3 -or ($pyMajMin.Groups[1].Value -eq 3 -and $pyMajMin.Groups[2].Value -lt 12)) {
    Write-Host "  FAIL: Python 3.12+ required, found $pyVersion" -ForegroundColor Red
    exit 1
}
Write-Host "  OK: $pyVersion" -ForegroundColor Green

# Node.js
$node = Get-Command node -ErrorAction SilentlyContinue
if (-not $node) {
    Write-Host "  FAIL: Node.js not found. Install from https://nodejs.org (LTS)" -ForegroundColor Red
    exit 1
}
$nodeVersion = node --version 2>&1
$nodeMajor = [int]($nodeVersion -replace 'v(\d+).*', '$1')
if ($nodeMajor -lt 18) {
    Write-Host "  FAIL: Node.js 18+ required, found $nodeVersion" -ForegroundColor Red
    exit 1
}
Write-Host "  OK: Node.js $nodeVersion" -ForegroundColor Green

# Docker
$docker = Get-Command docker -ErrorAction SilentlyContinue
$hasDocker = $false
if ($docker) {
    try {
        docker info 2>&1 | Out-Null
        Write-Host "  OK: Docker available" -ForegroundColor Green
        $hasDocker = $true
    } catch {
        Write-Host "  WARN: Docker installed but not running. Start Docker Desktop." -ForegroundColor Yellow
    }
} else {
    Write-Host "  INFO: Docker not found (optional — install for managed PostgreSQL)" -ForegroundColor Yellow
}

# [2/9] Environment
Write-Host ""
Write-Host "[2/9] Setting up environment..." -ForegroundColor Yellow

if (-not (Test-Path "config\.env")) {
    if (Test-Path "config\.env.example") {
        Copy-Item "config\.env.example" "config\.env"
        Write-Host "  OK: Created config\.env from template" -ForegroundColor Green
        Write-Host "  ACTION NEEDED: Edit config\.env and set ANTHROPIC_API_KEY" -ForegroundColor Yellow
    } else {
        Write-Host "  FAIL: config\.env.example not found" -ForegroundColor Red
    }
} else {
    Write-Host "  OK: config\.env already exists" -ForegroundColor Green
}

# [3/9] PostgreSQL
Write-Host ""
Write-Host "[3/9] Starting PostgreSQL..." -ForegroundColor Yellow

$pgReachable = $false

# Check if PostgreSQL is already running
try {
    $testConn = Test-NetConnection -ComputerName localhost -Port 5432 -WarningAction SilentlyContinue
    if ($testConn.TcpTestSucceeded) {
        Write-Host "  OK: PostgreSQL already running on port 5432" -ForegroundColor Green
        $pgReachable = $true
    }
} catch {}

if (-not $pgReachable -and $hasDocker) {
    Write-Host "  Starting PostgreSQL via Docker Compose..." -ForegroundColor Yellow
    docker compose up -d postgres 2>&1 | ForEach-Object { Write-Host "    $_" }

    # Wait for healthy
    for ($i = 1; $i -le 30; $i++) {
        Start-Sleep -Seconds 1
        try {
            $testConn = Test-NetConnection -ComputerName localhost -Port 5432 -WarningAction SilentlyContinue
            if ($testConn.TcpTestSucceeded) {
                $pgReachable = $true
                Write-Host "  OK: PostgreSQL started (took ${i}s)" -ForegroundColor Green
                break
            }
        } catch {}
    }
    if (-not $pgReachable) {
        Write-Host "  FAIL: PostgreSQL did not start. Check: docker compose logs postgres" -ForegroundColor Red
    }
} elseif (-not $pgReachable) {
    Write-Host "  FAIL: PostgreSQL not running and no Docker available" -ForegroundColor Red
    Write-Host "        Install PostgreSQL 16 or Docker Desktop" -ForegroundColor Yellow
}

# [4/9] Database Schema
Write-Host ""
Write-Host "[4/9] Setting up database schema..." -ForegroundColor Yellow

if ($pgReachable -and $hasDocker) {
    docker compose exec -T postgres psql -U v3q_admin -d v3q -f /docker-entrypoint-initdb.d/01_setup.sql 2>&1 | Out-Null
    Write-Host "  OK: Database schema up to date" -ForegroundColor Green
} elseif ($pgReachable) {
    Write-Host "  INFO: Run manually: psql -U <user> -d v3q -f scripts\setup_postgresql.sql" -ForegroundColor Yellow
}

# [5/9] Python backend
Write-Host ""
Write-Host "[5/9] Installing Python backend..." -ForegroundColor Yellow

Push-Location backend

if (-not (Test-Path ".venv")) {
    python -m venv .venv
    Write-Host "  Created Python venv" -ForegroundColor Green
} else {
    Write-Host "  OK: Python venv already exists" -ForegroundColor Green
}

.\.venv\Scripts\Activate.ps1
pip install -r requirements.txt --quiet 2>&1 | Out-Null
Write-Host "  OK: Backend dependencies installed" -ForegroundColor Green
Pop-Location

# [6/9] Frontend
Write-Host ""
Write-Host "[6/9] Installing frontend..." -ForegroundColor Yellow

Push-Location frontend
npm install --loglevel=warn 2>&1 | Out-Null
Write-Host "  OK: Frontend dependencies installed" -ForegroundColor Green

npx vite build 2>&1 | Out-Null
Write-Host "  OK: Frontend built" -ForegroundColor Green
Pop-Location

# [7/9] Directories
Write-Host ""
Write-Host "[7/9] Creating data directories..." -ForegroundColor Yellow

New-Item -ItemType Directory -Force -Path "data\results" | Out-Null
New-Item -ItemType Directory -Force -Path "logs" | Out-Null
Write-Host "  OK: Directories created" -ForegroundColor Green

# [8/9] Ollama
Write-Host ""
Write-Host "[8/9] Checking Ollama..." -ForegroundColor Yellow

$ollama = Get-Command ollama -ErrorAction SilentlyContinue
if ($ollama) {
    try {
        $tags = Invoke-RestMethod -Uri "http://localhost:11434/api/tags" -TimeoutSec 3
        Write-Host "  OK: Ollama is running" -ForegroundColor Green
    } catch {
        Write-Host "  WARN: Ollama installed but not running. Start with: ollama serve" -ForegroundColor Yellow
    }
} else {
    Write-Host "  WARN: Ollama not found. Install from https://ollama.com" -ForegroundColor Yellow
    Write-Host "        Then: ollama serve && ollama pull qwen2.5:32b" -ForegroundColor Yellow
}

# [9/9] Preflight
Write-Host ""
Write-Host "[9/9] Running preflight checks..." -ForegroundColor Yellow

Push-Location backend
.\.venv\Scripts\Activate.ps1
python -c @"
import asyncio
from preflight import run_preflight

async def check():
    result = await run_preflight()
    result.print_report()

asyncio.run(check())
"@
Pop-Location

# Summary
Write-Host ""
Write-Host "============================================" -ForegroundColor Cyan
Write-Host "  Installation Complete!" -ForegroundColor Cyan
Write-Host "============================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "To start V3Q.AI:" -ForegroundColor Green
Write-Host "  1. Edit config\.env and set ANTHROPIC_API_KEY" -ForegroundColor White
Write-Host "  2. Start Ollama: ollama serve" -ForegroundColor White
Write-Host "  3. Start backend:" -ForegroundColor White
Write-Host "       cd backend" -ForegroundColor White
Write-Host "       .\.venv\Scripts\Activate.ps1" -ForegroundColor White
Write-Host "       python main.py" -ForegroundColor White
Write-Host "  4. Open browser: http://localhost:8001" -ForegroundColor White
Write-Host ""
Write-Host "For development (with hot reload):" -ForegroundColor Green
Write-Host "  Terminal 1: cd backend && .\.venv\Scripts\Activate.ps1 && python main.py" -ForegroundColor White
Write-Host "  Terminal 2: cd frontend && npm run dev" -ForegroundColor White
Write-Host "  Open: http://localhost:5173" -ForegroundColor White
Write-Host ""
