<?php
header('Content-Type: text/plain');
header('X-Accel-Buffering: no'); 
ini_set('display_errors', 1);
error_reporting(E_ALL);

// Set execution time to 10 minutes (Next.js build can take time)
@set_time_limit(600);
@ini_set('max_execution_time', 600);

function runCommand($cmd) {
    echo "========================================\n";
    echo "Ejecutando: $cmd\n";
    echo "========================================\n";
    flush();
    ob_flush();
    
    if (function_exists('system')) {
        system($cmd . ' 2>&1');
    } elseif (function_exists('passthru')) {
        passthru($cmd . ' 2>&1');
    } elseif (function_exists('exec')) {
        $output = [];
        exec($cmd . ' 2>&1', $output);
        echo implode("\n", $output) . "\n";
    } elseif (function_exists('shell_exec')) {
        echo shell_exec($cmd . ' 2>&1');
    } else {
        echo "Error: Las funciones de ejecución de comandos (system, exec, passthru, shell_exec) están deshabilitadas en PHP por tu hosting.\n";
    }
    echo "\n";
    flush();
    ob_flush();
}

echo "=== INICIANDO INSTALACIÓN Y COMPILACIÓN (CAT TV) ===\n\n";
flush();

// Show current node and npm versions
runCommand('node -v');
runCommand('npm -v');

// Frontend Build
if (is_dir('frontend')) {
    echo "--- CONFIGURANDO FRONTEND ---\n";
    runCommand('cd frontend && npm install');
    runCommand('cd frontend && npm run build');
} else {
    echo "Error: No se encontró la carpeta 'frontend'.\n";
}

// Backend Build
if (is_dir('backend')) {
    echo "--- CONFIGURANDO BACKEND ---\n";
    runCommand('cd backend && npm install');
    runCommand('cd backend && npm run build');
} else {
    echo "Error: No se encontró la carpeta 'backend'.\n";
}

echo "=== PROCESO COMPLETADO ===\n";
flush();
?>
