#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Script de control de la aplicación de registro
Ejecuta Node.js server desde Python
"""

import os
import sys
import subprocess
import platform
import time
import requests
from pathlib import Path

class RegistroApp:
    def __init__(self):
        self.app_dir = Path(__file__).parent
        self.port = 3000
        self.mongo_port = 27017
        self.process = None
        
    def check_mongo(self):
        """Verifica si MongoDB está ejecutándose"""
        print("🔍 Verificando MongoDB...")
        try:
            requests.get('mongodb+srv://examen1:mosarela@cluster0.ynvaey5.mongodb.net/?appName=Cluster0', timeout=2)
            print("✅ MongoDB está activo")
            return True
        except:
            print("❌ MongoDB NO está activo")
            print("\n📝 Para iniciar MongoDB:")
            if platform.system() == "Linux":
                print("   sudo systemctl start mongod")
            elif platform.system() == "Darwin":  # macOS
                print("   brew services start mongodb-community")
            elif platform.system() == "Windows":
                print("   net start MongoDB")
            return False
    
    def check_node(self):
        """Verifica si Node.js está instalado"""
        print("\n🔍 Verificando Node.js...")
        try:
            result = subprocess.run(['node', '--version'], 
                                  capture_output=True, 
                                  text=True,
                                  timeout=5)
            if result.returncode == 0:
                print(f"✅ Node.js {result.stdout.strip()} encontrado")
                return True
        except:
            pass
        
        print("❌ Node.js NO está instalado")
        print("\n📝 Instálalo desde: https://nodejs.org/")
        return False
    
    def check_npm_modules(self):
        """Verifica si están instalados los módulos npm"""
        print("\n🔍 Verificando módulos npm...")
        node_modules = self.app_dir / 'node_modules'
        
        if node_modules.exists():
            print("✅ Módulos npm instalados")
            return True
        
        print("❌ Módulos npm NO instalados")
        print("📝 Ejecutando: npm install")
        
        try:
            subprocess.run(['npm', 'install'], cwd=self.app_dir, check=True)
            print("✅ Módulos instalados correctamente")
            return True
        except subprocess.CalledProcessError:
            print("❌ Error al instalar módulos")
            return False
    
    def check_env(self):
        """Verifica el archivo .env"""
        print("\n🔍 Verificando configuración (.env)...")
        env_file = self.app_dir / '.env'
        
        if env_file.exists():
            print("✅ Archivo .env encontrado")
            with open(env_file) as f:
                print("   Contenido:")
                for line in f:
                    print(f"   {line.rstrip()}")
            return True
        
        print("❌ Archivo .env NO encontrado")
        return False
    
    def check_port(self):
        """Verifica si el puerto está disponible"""
        print(f"\n🔍 Verificando puerto {self.port}...")
        try:
            response = requests.get(f'http://localhost:{self.port}', timeout=1)
            print(f"⚠️  Puerto {self.port} ya está en uso")
            return False
        except:
            print(f"✅ Puerto {self.port} disponible")
            return True
    
    def perform_checks(self):
        """Realiza todas las verificaciones"""
        print("=" * 50)
        print("   VERIFICACIONES PREVIAS")
        print("=" * 50)
        
        checks = [
            ("Node.js", self.check_node()),
            ("MongoDB", self.check_mongo()),
            ("Módulos npm", self.check_npm_modules()),
            ("Configuración .env", self.check_env()),
            ("Puerto disponible", self.check_port()),
        ]
        
        print("\n" + "=" * 50)
        print("   RESUMEN")
        print("=" * 50)
        
        for name, result in checks:
            status = "✅" if result else "❌"
            print(f"{status} {name}")
        
        # Retornar True solo si todo está bien excepto MongoDB (se puede iniciar manual)
        node_ok = checks[0][1]
        npm_ok = checks[2][1]
        env_ok = checks[3][1]
        port_ok = checks[4][1]
        
        if not (node_ok and npm_ok and env_ok and port_ok):
            return False
        
        if not checks[1][1]:  # MongoDB
            response = input("\n⚠️  MongoDB no está activo. ¿Continuar de todas formas? (s/n): ")
            return response.lower() == 's'
        
        return True
    
    def start(self):
        """Inicia la aplicación"""
        print("\n" + "=" * 50)
        print("   INICIANDO APLICACIÓN")
        print("=" * 50)
        
        if not self.perform_checks():
            print("\n❌ Soluciona los problemas antes de continuar")
            return False
        
        print("\n🚀 Iniciando servidor...")
        print(f"📝 URL: http://localhost:{self.port}")
        print("⏹️  Presiona Ctrl+C para detener\n")
        
        try:
            self.process = subprocess.Popen(
                ['npm', 'run', 'dev'],
                cwd=self.app_dir,
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT,
                text=True,
                bufsize=1,
                universal_newlines=True
            )
            
            # Mostrar output en tiempo real
            for line in self.process.stdout:
                print(line, end='')
            
        except KeyboardInterrupt:
            print("\n\n⏹️  Deteniendo servidor...")
            self.stop()
        except Exception as e:
            print(f"❌ Error: {e}")
            return False
        
        return True
    
    def stop(self):
        """Detiene la aplicación"""
        if self.process:
            self.process.terminate()
            try:
                self.process.wait(timeout=5)
            except subprocess.TimeoutExpired:
                self.process.kill()
            print("✅ Servidor detenido")
    
    def run_simple(self):
        """Ejecución simple sin verificaciones"""
        print("🚀 Iniciando aplicación...")
        print(f"📝 URL: http://localhost:{self.port}")
        print("⏹️  Presiona Ctrl+C para detener\n")
        
        try:
            subprocess.run(
                ['npm', 'run', 'dev'],
                cwd=self.app_dir
            )
        except KeyboardInterrupt:
            print("\n✅ Aplicación detenida")


def main():
    """Función principal"""
    if len(sys.argv) > 1:
        comando = sys.argv[1].lower()
        
        if comando == '--verificar':
            app = RegistroApp()
            app.perform_checks()
        elif comando == '--simple':
            app = RegistroApp()
            app.run_simple()
        elif comando == '--help':
            print("""
Uso: python run.py [COMANDO]

Comandos:
  (sin comando)    Verificar e iniciar la aplicación
  --simple         Iniciar sin verificaciones
  --verificar      Sólo realizar verificaciones
  --help          Mostrar esta ayuda
            """)
        else:
            print(f"Comando desconocido: {comando}")
            print("Usa: python run.py --help")
    else:
        app = RegistroApp()
        app.start()


if __name__ == '__main__':
    main()
