#!/usr/bin/env python3
"""
Script de verificación para mejoras de la Fase 3
Verifica que todas las mejoras están correctamente implementadas
"""
import sys
import os
from pathlib import Path

def check_file_exists(filepath, description):
    """Verificar que un archivo existe"""
    if Path(filepath).exists():
        print(f"✅ {description}: {filepath}")
        return True
    else:
        print(f"❌ {description}: {filepath} NO ENCONTRADO")
        return False

def check_function_in_file(filepath, function_name, description):
    """Verificar que una función existe en un archivo"""
    try:
        with open(filepath, 'r') as f:
            content = f.read()
            if function_name in content:
                print(f"✅ {description}: Encontrado '{function_name}'")
                return True
            else:
                print(f"❌ {description}: NO encontrado '{function_name}'")
                return False
    except Exception as e:
        print(f"❌ Error leyendo {filepath}: {e}")
        return False

def check_class_in_file(filepath, class_name, description):
    """Verificar que una clase existe en un archivo"""
    return check_function_in_file(filepath, f"class {class_name}", description)

def main():
    print("=" * 70)
    print("🔍 VERIFICACIÓN DE MEJORAS FASE 3 - CBCFacil")
    print("=" * 70)
    print()
    
    results = []
    
    # 1. Verificar archivos modificados/creados
    print("📁 ARCHIVOS:")
    print("-" * 70)
    results.append(check_file_exists("main.py", "main.py modificado"))
    results.append(check_file_exists("config/settings.py", "config/settings.py modificado"))
    results.append(check_file_exists("core/health_check.py", "core/health_check.py creado"))
    results.append(check_file_exists("IMPROVEMENTS_LOG.md", "IMPROVEMENTS_LOG.md creado"))
    print()
    
    # 2. Verificar mejoras en main.py
    print("🔧 MEJORAS EN main.py:")
    print("-" * 70)
    results.append(check_function_in_file("main.py", "logger.exception", "logger.exception() implementado"))
    results.append(check_function_in_file("main.py", "class JSONFormatter", "JSONFormatter implementado"))
    results.append(check_function_in_file("main.py", "def validate_configuration", "validate_configuration() implementado"))
    results.append(check_function_in_file("main.py", "def check_service_health", "check_service_health() implementado"))
    results.append(check_function_in_file("main.py", "def send_error_notification", "send_error_notification() implementado"))
    results.append(check_function_in_file("main.py", "def setup_logging", "setup_logging() implementado"))
    print()
    
    # 3. Verificar mejoras en config/settings.py
    print("⚙️  MEJORAS EN config/settings.py:")
    print("-" * 70)
    results.append(check_function_in_file("config/settings.py", "class ConfigurationError", "ConfigurationError definido"))
    results.append(check_function_in_file("config/settings.py", "def nextcloud_url", "Propiedad nextcloud_url con validación"))
    results.append(check_function_in_file("config/settings.py", "def valid_webdav_config", "Propiedad valid_webdav_config"))
    results.append(check_function_in_file("config/settings.py", "def telegram_configured", "Propiedad telegram_configured"))
    results.append(check_function_in_file("config/settings.py", "def has_gpu_support", "Propiedad has_gpu_support"))
    results.append(check_function_in_file("config/settings.py", "def config_summary", "Propiedad config_summary"))
    print()
    
    # 4. Verificar core/health_check.py
    print("❤️  HEALTH CHECKS:")
    print("-" * 70)
    results.append(check_function_in_file("core/health_check.py", "class HealthChecker", "Clase HealthChecker"))
    results.append(check_function_in_file("core/health_check.py", "def check_webdav_connection", "check_webdav_connection()"))
    results.append(check_function_in_file("core/health_check.py", "def check_ai_providers", "check_ai_providers()"))
    results.append(check_function_in_file("core/health_check.py", "def check_vram_manager", "check_vram_manager()"))
    results.append(check_function_in_file("core/health_check.py", "def check_disk_space", "check_disk_space()"))
    results.append(check_function_in_file("core/health_check.py", "def run_full_health_check", "run_full_health_check()"))
    print()
    
    # Resumen
    print("=" * 70)
    print("📊 RESUMEN:")
    print("=" * 70)
    passed = sum(results)
    total = len(results)
    percentage = (passed / total) * 100
    
    print(f"Verificaciones pasadas: {passed}/{total} ({percentage:.1f}%)")
    print()
    
    if percentage == 100:
        print("🎉 ¡TODAS LAS MEJORAS ESTÁN CORRECTAMENTE IMPLEMENTADAS!")
        print()
        print("Puedes probar:")
        print("  python main.py health")
        print()
        return 0
    else:
        print("⚠️  Algunas verificaciones fallaron")
        print()
        return 1

if __name__ == "__main__":
    sys.exit(main())
