#!/usr/bin/env python3
"""
System-Verification — Testet das komplette Gesundheits-System.
"""

import os
import sys
import subprocess
from pathlib import Path

def test_imports():
    """Teste alle Importe."""
    libs = [
        'pandas', 'numpy', 'sqlalchemy', 'scipy', 'statsmodels',
        'matplotlib', 'seaborn', 'plotly', 'pdfplumber', 'watchdog',
        'fitz', 'camelot'
    ]
    missing = []
    for lib in libs:
        try:
            __import__(lib)
            print(f"  [OK] {lib}")
        except ImportError:
            missing.append(lib)
            print(f"  [MISSING] {lib}")
    
    if missing:
        print(f"\n[WARN] Fehlende Libraries: {', '.join(missing)}")
        return False
    return True

def test_database():
    """Teste Datenbank-Verbindung."""
    db_path = '/home/agent/.hermes/assets/Gesundheit/health_data.db'
    if not os.path.exists(db_path):
        print("[FAIL] Datenbank nicht gefunden")
        return False
    
    import sqlite3
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    
    # Prüfe Tabellen
    cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
    tables = [row[0] for row in cursor.fetchall()]
    print(f"  [OK] Datenbank: {len(tables)} Tabellen")
    
    # Prüfe Daten
    cursor.execute("SELECT COUNT(*) FROM laborwerte")
    count = cursor.fetchone()[0]
    print(f"  [OK] Laborwerte: {count}")
    
    conn.close()
    return True

def test_health_manager():
    """Teste HealthManager."""
    try:
        sys.path.insert(0, '/home/agent/.hermes/assets/Gesundheit/scripts')
        from health_manager import HealthManager
        hm = HealthManager()
        
        # Test CRP
        trend = hm.compute_crp_trend()
        if trend:
            print(f"  [OK] CRP-Trend: {trend['trend']}")
        else:
            print("  [WARN] Kein CRP-Trend")
        
        return True
    except Exception as e:
        print(f"  [FAIL] HealthManager: {e}")
        return False

def test_reports():
    """Teste Report-Generierung."""
    reports_dir = Path('/home/agent/.hermes/assets/Gesundheit/reports')
    if not reports_dir.exists():
        print("[WARN] Reports-Ordner nicht vorhanden")
        return False
    
    files = list(reports_dir.glob('*.png')) + list(reports_dir.glob('*.html'))
    print(f"  [OK] Reports: {len(files)} Dateien")
    for f in files:
        print(f"    - {f.name} ({f.stat().st_size} bytes)")
    return True

def main():
    print("=" * 60)
    print("GESUNDHEITS-SYSTEM VERIFICATION")
    print("=" * 60)
    
    print("\n1. Library-Imports:")
    imports_ok = test_imports()
    
    print("\n2. Datenbank:")
    db_ok = test_database()
    
    print("\n3. HealthManager:")
    hm_ok = test_health_manager()
    
    print("\n4. Reports:")
    reports_ok = test_reports()
    
    print("\n" + "=" * 60)
    if imports_ok and db_ok and hm_ok and reports_ok:
        print("STATUS: ALLE TESTS BESTANDEN ✅")
    else:
        print("STATUS: EINIGE TESTS FEHLGESCHLAGEN ⚠️")
    print("=" * 60)

if __name__ == '__main__':
    main()
