# Script para compilar web-console completamente
# Autor: Generado automaticamente
# Descripcion: Compila el frontend React, ejecuta statik y compila el servidor Go

$ErrorActionPreference = "Stop"

Write-Host "========================================" -ForegroundColor Cyan
Write-Host "  Script de Compilacion de Web-Console  " -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""

# Variables
$ROOT_DIR = Split-Path -Parent $MyInvocation.MyCommand.Path
$WEB_DIR = Join-Path $ROOT_DIR "web"
$ENV_FILE = Join-Path $WEB_DIR ".env.local"

Write-Host "[1/5] Verificando directorios..." -ForegroundColor Yellow
if (-not (Test-Path $WEB_DIR)) {
    Write-Host "ERROR: Directorio web no encontrado: $WEB_DIR" -ForegroundColor Red
    exit 1
}

# Verificar o crear .env.local
Write-Host "[2/5] Configurando variables de entorno..." -ForegroundColor Yellow
if (-not (Test-Path $ENV_FILE)) {
    Write-Host "  Creando archivo .env.local..." -ForegroundColor Gray
    $clusterUrl = Read-Host "  Ingresa REACT_APP_CLUSTER_URL (ej: localhost o http://localhost:8080) [default: localhost]"
    if ([string]::IsNullOrWhiteSpace($clusterUrl)) {
        $clusterUrl = "localhost"
    }
    Set-Content -Path $ENV_FILE -Value "REACT_APP_CLUSTER_URL=$clusterUrl"
    Write-Host "  OK: Archivo .env.local creado con REACT_APP_CLUSTER_URL=$clusterUrl" -ForegroundColor Green
} else {
    Write-Host "  OK: Archivo .env.local ya existe" -ForegroundColor Green
    $envContent = Get-Content $ENV_FILE -Raw
    if ($envContent -match "REACT_APP_CLUSTER_URL") {
        Write-Host "  OK: REACT_APP_CLUSTER_URL esta configurado" -ForegroundColor Green
        Write-Host "  Contenido actual:" -ForegroundColor Gray
        Get-Content $ENV_FILE | ForEach-Object { Write-Host "    $_" -ForegroundColor Gray }
    } else {
        Write-Host "  ADVERTENCIA: REACT_APP_CLUSTER_URL no encontrado en .env.local" -ForegroundColor Yellow
        $clusterUrl = Read-Host "  Ingresa REACT_APP_CLUSTER_URL (ej: localhost o http://localhost:8080) [default: localhost]"
        if ([string]::IsNullOrWhiteSpace($clusterUrl)) {
            $clusterUrl = "localhost"
        }
        Add-Content -Path $ENV_FILE -Value "`nREACT_APP_CLUSTER_URL=$clusterUrl"
        Write-Host "  OK: REACT_APP_CLUSTER_URL agregado: $clusterUrl" -ForegroundColor Green
    }
}

# Verificar Node.js y yarn
Write-Host "[3/5] Verificando dependencias..." -ForegroundColor Yellow
try {
    $nodeVersion = node --version 2>&1
    Write-Host "  OK: Node.js instalado: $nodeVersion" -ForegroundColor Green
} catch {
    Write-Host "  ERROR: Node.js no encontrado. Por favor instalalo primero." -ForegroundColor Red
    exit 1
}

try {
    $yarnVersion = yarn --version 2>&1
    Write-Host "  OK: Yarn instalado: v$yarnVersion" -ForegroundColor Green
} catch {
    Write-Host "  ERROR: Yarn no encontrado. Instalando yarn..." -ForegroundColor Yellow
    npm install -g yarn
    if ($LASTEXITCODE -ne 0) {
        Write-Host "  ERROR: Error al instalar yarn" -ForegroundColor Red
        exit 1
    }
    Write-Host "  OK: Yarn instalado" -ForegroundColor Green
}

try {
    $goVersion = go version 2>&1
    Write-Host "  OK: Go instalado: $goVersion" -ForegroundColor Green
} catch {
    Write-Host "  ERROR: Go no encontrado. Por favor instalalo primero." -ForegroundColor Red
    exit 1
}

# Compilar frontend React
Write-Host "[4/5] Compilando frontend React..." -ForegroundColor Yellow
Push-Location $WEB_DIR
try {
    Write-Host "  Instalando dependencias de Node.js (si es necesario)..." -ForegroundColor Gray
    yarn install --silent 2>&1 | Out-Null
    if ($LASTEXITCODE -ne 0) {
        Write-Host "  ADVERTENCIA: Algunas advertencias durante yarn install (continuando...)" -ForegroundColor Yellow
    }
    
    Write-Host "  Compilando con yarn build..." -ForegroundColor Gray
    yarn build 2>&1 | ForEach-Object {
        if ($_ -match "Compiled|error|Error|Failed|failed") {
            $color = if ($_ -match "error|Error|Failed|failed") { "Red" } else { "Gray" }
            Write-Host "    $_" -ForegroundColor $color
        }
    }
    
    if ($LASTEXITCODE -eq 0) {
        Write-Host "  OK: Frontend compilado exitosamente" -ForegroundColor Green
    } else {
        Write-Host "  ERROR: Error al compilar el frontend" -ForegroundColor Red
        Pop-Location
        exit 1
    }
} catch {
    Write-Host "  ERROR: Error durante la compilacion del frontend: $_" -ForegroundColor Red
    Pop-Location
    exit 1
}
Pop-Location

# Verificar que web/build existe
$BUILD_DIR = Join-Path $WEB_DIR "build"
if (-not (Test-Path $BUILD_DIR)) {
    Write-Host "  ERROR: Directorio web/build no encontrado despues de la compilacion" -ForegroundColor Red
    exit 1
}

Write-Host "  OK: Directorio web/build verificado" -ForegroundColor Green

# Instalar statik si no esta instalado
Write-Host "[5/5] Preparando statik..." -ForegroundColor Yellow
Push-Location $ROOT_DIR
try {
    Write-Host "  Verificando si statik esta instalado..." -ForegroundColor Gray
    $statikInstalled = Get-Command statik -ErrorAction SilentlyContinue
    if (-not $statikInstalled) {
        Write-Host "  Instalando statik..." -ForegroundColor Gray
        go get github.com/rakyll/statik 2>&1 | Out-Null
        if ($LASTEXITCODE -eq 0) {
            Write-Host "  OK: Statik instalado" -ForegroundColor Green
        } else {
            Write-Host "  ADVERTENCIA: No se pudo instalar statik automaticamente" -ForegroundColor Yellow
            Write-Host "  Intenta manualmente: go get github.com/rakyll/statik" -ForegroundColor Yellow
        }
    } else {
        Write-Host "  OK: Statik ya esta instalado" -ForegroundColor Green
    }
    
    Write-Host "  Ejecutando statik --src=web/build..." -ForegroundColor Gray
    statik --src=web/build 2>&1 | Out-Null
    if ($LASTEXITCODE -eq 0) {
        Write-Host "  OK: Statik ejecutado exitosamente" -ForegroundColor Green
    } else {
        Write-Host "  ERROR: Error al ejecutar statik" -ForegroundColor Red
        Write-Host "  Verifica que el directorio web/build exista y tenga contenido" -ForegroundColor Yellow
        Pop-Location
        exit 1
    }
    
    Write-Host "  Compilando servidor Go..." -ForegroundColor Gray
    go build -o ssh-web-console.exe 2>&1 | ForEach-Object {
        if ($_ -match "error|Error") {
            Write-Host "    $_" -ForegroundColor Red
        }
    }
    
    if ($LASTEXITCODE -eq 0) {
        Write-Host "  OK: Servidor Go compilado exitosamente" -ForegroundColor Green
        $exePath = Join-Path $ROOT_DIR "ssh-web-console.exe"
        if (Test-Path $exePath) {
            Write-Host "  OK: Ejecutable creado: $exePath" -ForegroundColor Green
        }
    } else {
        Write-Host "  ERROR: Error al compilar el servidor Go" -ForegroundColor Red
        Pop-Location
        exit 1
    }
} catch {
    Write-Host "  ERROR: Error durante la compilacion: $_" -ForegroundColor Red
    Pop-Location
    exit 1
}
Pop-Location

Write-Host ""
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "  OK: Compilacion completada exitosamente  " -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "Para ejecutar web-console:" -ForegroundColor Yellow
Write-Host "  cd C:\wamp64\www\web-console" -ForegroundColor Gray
Write-Host "  .\ssh-web-console.exe" -ForegroundColor Gray
Write-Host ""
Write-Host "El servidor escuchara en: http://localhost:2222" -ForegroundColor Gray
Write-Host ""
