#!/usr/bin/env python3
"""
test_dicom2pacs.py - Automatisierte Tests für dicom2pacs
"""

import os
import sys
import shutil
import tempfile
from pathlib import Path

# Füge Projektverzeichnis zum Python-Pfad hinzu
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

def test_imports():
    """Test ob alle Module importiert werden können"""
    print("Teste Imports...")
    try:
        import dicom_processing
        import file_management
        import network_utils
        import gui
        print("✓ Alle Module erfolgreich importiert")
        return True
    except ImportError as e:
        print(f"✗ Import-Fehler: {e}")
        return False

def test_dicom_file_detection():
    """Test DICOM-Datei-Erkennung"""
    print("\nTeste DICOM-Datei-Erkennung...")
    try:
        import dicom_processing
        
        # Suche nach Test-DICOM-Dateien
        test_dirs = [
            os.path.expanduser("~/Downloads/test_dicom"),
            "dist/dicom2pacs.app/Contents/Resources/lib/python3.13/pydicom/data/test_files",
            "venv/lib/python3.13/site-packages/pydicom/data/test_files"
        ]
        
        test_file = None
        for test_dir in test_dirs:
            if os.path.exists(test_dir):
                for file in os.listdir(test_dir):
                    if file.endswith('.dcm'):
                        test_file = os.path.join(test_dir, file)
                        break
                if test_file:
                    break
        
        if test_file and os.path.exists(test_file):
            is_dicom = dicom_processing.is_dicom_file(test_file)
            print(f"✓ DICOM-Datei erkannt: {os.path.basename(test_file)} -> {is_dicom}")
            return True
        else:
            print("⚠ Keine Test-DICOM-Datei gefunden")
            return False
    except Exception as e:
        print(f"✗ Fehler: {e}")
        return False

def test_file_management():
    """Test Dateiverwaltung"""
    print("\nTeste Dateiverwaltung...")
    try:
        import file_management
        
        test_dir = os.path.expanduser("~/Downloads/test_dicom")
        if os.path.exists(test_dir):
            result = file_management.find_dicom_files(test_dir)
            if result != 'non_found':
                files, count = result
                print(f"✓ {count} DICOM-Dateien gefunden")
                return True
            else:
                print("⚠ Keine DICOM-Dateien im Test-Ordner")
                return False
        else:
            print("⚠ Test-Ordner nicht gefunden")
            return False
    except Exception as e:
        print(f"✗ Fehler: {e}")
        return False

def test_config_loading():
    """Test Konfigurationsladen"""
    print("\nTeste Konfigurationsladen...")
    try:
        # Simuliere load_config
        config_path = os.path.expanduser("~/.dicom2pacs.conf")
        if os.path.exists(config_path):
            print("✓ Konfigurationsdatei gefunden")
            with open(config_path, 'r') as f:
                content = f.read()
                print(f"  Inhalt: {len(content)} Zeichen")
            return True
        else:
            print("⚠ Konfigurationsdatei nicht gefunden (wird beim ersten Start erstellt)")
            return True  # Nicht kritisch
    except Exception as e:
        print(f"✗ Fehler: {e}")
        return False

def test_patient_name_formatting():
    """Test Patientenname-Formatierung"""
    print("\nTeste Patientenname-Formatierung...")
    try:
        import file_management
        
        # Test verschiedene Formate
        test_cases = [
            ("MUSTERMANN^MAX", ("MUSTERMANN", "MAX")),
            ("Mustermann^Max", ("Mustermann", "Max")),
            ("SMITH", ("SMITH", "")),
        ]
        
        for input_name, expected in test_cases:
            result = file_management.format_patient_name(input_name)
            if result == expected:
                print(f"✓ '{input_name}' -> {result}")
            else:
                print(f"✗ '{input_name}' -> {result}, erwartet: {expected}")
                return False
        
        return True
    except Exception as e:
        print(f"✗ Fehler: {e}")
        return False

def test_birthdate_formatting():
    """Test Geburtsdatum-Formatierung"""
    print("\nTeste Geburtsdatum-Formatierung...")
    try:
        import file_management
        
        test_cases = [
            ("19800101", "01.01.1980"),
            ("20001225", "25.12.2000"),
        ]
        
        for input_date, expected in test_cases:
            result = file_management.format_birthdate(input_date)
            if result == expected:
                print(f"✓ '{input_date}' -> {result}")
            else:
                print(f"✗ '{input_date}' -> {result}, erwartet: {expected}")
                return False
        
        return True
    except Exception as e:
        print(f"✗ Fehler: {e}")
        return False

def main():
    """Hauptfunktion für alle Tests"""
    print("=== dicom2pacs Automatisierte Tests ===\n")
    
    tests = [
        ("Imports", test_imports),
        ("DICOM-Datei-Erkennung", test_dicom_file_detection),
        ("Dateiverwaltung", test_file_management),
        ("Konfiguration", test_config_loading),
        ("Patientenname-Formatierung", test_patient_name_formatting),
        ("Geburtsdatum-Formatierung", test_birthdate_formatting),
    ]
    
    results = []
    for test_name, test_func in tests:
        try:
            result = test_func()
            results.append((test_name, result))
        except Exception as e:
            print(f"✗ Unerwarteter Fehler in {test_name}: {e}")
            results.append((test_name, False))
    
    # Zusammenfassung
    print("\n" + "="*50)
    print("Test-Zusammenfassung:")
    print("="*50)
    
    passed = sum(1 for _, result in results if result)
    total = len(results)
    
    for test_name, result in results:
        status = "✓ PASS" if result else "✗ FAIL"
        print(f"{status}: {test_name}")
    
    print("="*50)
    print(f"Ergebnis: {passed}/{total} Tests bestanden")
    
    if passed == total:
        print("🎉 Alle Tests bestanden!")
        return 0
    else:
        print("⚠️  Einige Tests fehlgeschlagen")
        return 1

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