#!/usr/bin/env python3
"""
Test finale per verificare che analisys_04.py sia pronto per AlmaLinux Tesla M60
"""

import os
import sys
import subprocess

def test_syntax_check():
    """Verifica sintassi Python"""
    print("🧪 TEST SINTASSI PYTHON")
    print("=" * 50)
    
    try:
        result = subprocess.run([sys.executable, '-m', 'py_compile', 'analisys_04.py'], 
                              capture_output=True, text=True)
        if result.returncode == 0:
            print("✅ Sintassi Python corretta")
            return True
        else:
            print(f"❌ Errore sintassi: {result.stderr}")
            return False
    except Exception as e:
        print(f"❌ Test sintassi fallito: {e}")
        return False

def test_import_critical_modules():
    """Test import moduli critici"""
    print("\n🧪 TEST IMPORT MODULI CRITICI")
    print("=" * 50)
    
    modules_to_test = [
        'pandas',
        'sklearn',
        'numpy', 
        'mysql.connector',
        'joblib'
    ]
    
    success = True
    for module in modules_to_test:
        try:
            __import__(module)
            print(f"✅ {module} importato")
        except ImportError as e:
            print(f"❌ {module} non disponibile: {e}")
            success = False
    
    return success

def test_tensorflow_config():
    """Test configurazione TensorFlow Tesla M60"""
    print("\n🧪 TEST CONFIGURAZIONE TENSORFLOW TESLA M60")
    print("=" * 50)
    
    try:
        # Applica configurazione Tesla M60 CC 5.2
        os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'
        os.environ['TF_GPU_ALLOCATOR'] = 'legacy'  # CRITICO per CC 5.2
        os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true'
        print("🔧 TF_GPU_ALLOCATOR=legacy configurato")
        print("🔧 TF_FORCE_GPU_ALLOW_GROWTH=true configurato")
        
        import tensorflow as tf
        print(f"✅ TensorFlow {tf.__version__} importato con configurazione Tesla M60")
        
        # Test configurazione mixed precision
        try:
            policy = tf.keras.mixed_precision.Policy('mixed_float16')
            tf.keras.mixed_precision.set_global_policy(policy)
            print("⚠️ Mixed precision FP16 abilitato (warning CC 5.2 normale)")
        except Exception as e:
            print(f"⚠️ Mixed precision error: {e}")
            # Fallback FP32
            policy = tf.keras.mixed_precision.Policy('float32')
            tf.keras.mixed_precision.set_global_policy(policy)
            print("✅ Fallback FP32 configurato")
        
        return True
    except Exception as e:
        print(f"❌ Configurazione TensorFlow fallita: {e}")
        return False

def test_almalinux_compatibility():
    """Test compatibilità AlmaLinux"""
    print("\n🧪 TEST COMPATIBILITÀ ALMALINUX")
    print("=" * 50)
    
    checks = []
    
    # Check 1: Verifica import analisys_04 principali
    try:
        # Test import senza eseguire main
        spec = None
        import importlib.util
        spec = importlib.util.spec_from_file_location("analisys_04", "analisys_04.py")
        if spec and spec.loader:
            print("✅ analisys_04.py può essere importato")
            checks.append(True)
        else:
            print("❌ analisys_04.py non può essere importato")
            checks.append(False)
    except Exception as e:
        print(f"❌ Import analisys_04 fallito: {e}")
        checks.append(False)
    
    # Check 2: Verifica presence config database
    try:
        if os.path.exists('config_database.py'):
            print("✅ config_database.py presente")
            checks.append(True)
        else:
            print("⚠️ config_database.py non presente (usa --demo)")
            checks.append(True)  # Non bloccante
    except Exception as e:
        print(f"⚠️ Check config database: {e}")
        checks.append(True)  # Non bloccante
    
    # Check 3: Verifica directory models
    try:
        if not os.path.exists('models_v04'):
            os.makedirs('models_v04', exist_ok=True)
        print("✅ Directory models_v04 presente/creata")
        checks.append(True)
    except Exception as e:
        print(f"❌ Errore directory models: {e}")
        checks.append(False)
    
    return all(checks)

def test_almalinux_commands():
    """Test comandi per AlmaLinux"""
    print("\n🧪 TEST COMANDI ALMALINUX")
    print("=" * 50)
    
    commands = [
        "python analisys_04.py --help",
        "python -c \"import analisys_04; print('Import OK')\"",
    ]
    
    success = True
    for cmd in commands:
        try:
            print(f"🧪 Test: {cmd}")
            result = subprocess.run(cmd.split(), capture_output=True, text=True, timeout=30)
            if result.returncode == 0:
                print(f"  ✅ Comando riuscito")
            else:
                print(f"  ⚠️ Comando con warning (normale): {result.stderr[:100]}...")
        except subprocess.TimeoutExpired:
            print(f"  ⚠️ Timeout (normale per alcuni import)")
        except Exception as e:
            print(f"  ❌ Errore comando: {e}")
            success = False
    
    return success

def main():
    """Test principale compatibilità AlmaLinux"""
    print("🐧 TEST COMPATIBILITÀ ALMALINUX + TESLA M60")
    print("=" * 70)
    print("Verifica che analisys_04.py sia pronto per AlmaLinux")
    print("=" * 70)
    
    tests = [
        ("Sintassi Python", test_syntax_check),
        ("Import Moduli Critici", test_import_critical_modules),
        ("Configurazione TensorFlow Tesla M60", test_tensorflow_config),
        ("Compatibilità AlmaLinux", test_almalinux_compatibility),
        ("Comandi AlmaLinux", test_almalinux_commands),
    ]
    
    results = []
    for test_name, test_func in tests:
        try:
            result = test_func()
            results.append((test_name, result))
        except Exception as e:
            print(f"❌ Test {test_name} fallito: {e}")
            results.append((test_name, False))
    
    # Riepilogo finale
    print("\n" + "=" * 70)
    print("📋 RIEPILOGO TEST ALMALINUX")
    print("=" * 70)
    
    passed = 0
    total = len(results)
    
    for test_name, result in results:
        status = "✅ PASS" if result else "❌ FAIL"
        print(f"{status:<8} {test_name}")
        if result:
            passed += 1
    
    print("=" * 70)
    success_rate = (passed / total) * 100
    print(f"📊 RISULTATO: {passed}/{total} test superati ({success_rate:.1f}%)")
    
    if passed == total:
        print("🎉 SISTEMA PRONTO PER ALMALINUX!")
        print("✅ analisys_04.py può essere eseguito su AlmaLinux + Tesla M60")
        print("\n💡 COMANDI SUGGERITI per AlmaLinux:")
        print("   python analisys_04.py --max-records 80000 --force-training")
        print("   python analisys_04.py --demo --max-records 50000")
        return True
    elif passed >= total * 0.8:  # 80% success rate
        print("⚠️ SISTEMA MOSTLY READY per AlmaLinux")
        print("⚠️ Alcuni test falliti ma dovrebbe funzionare")
        return True
    else:
        print("❌ SISTEMA NON PRONTO per AlmaLinux")
        print("❌ Troppi test falliti - verificare dipendenze")
        return False

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1) 