import os
import json
from datetime import timedelta, datetime

# Hardcodierte Konfiguration
SECRET_KEY = "7445630171969DFAC92C53CEC92E67A9CB2E00B3CB2F"
DATABASE_PATH = "database/myp.db"
TAPO_USERNAME = "till.tomczak@mercedes-benz.com"
TAPO_PASSWORD = "744563017196A"

# Drucker-Konfiguration
PRINTERS = {
    "Printer 1": {"ip": "192.168.0.100"},
    "Printer 2": {"ip": "192.168.0.101"},
    "Printer 3": {"ip": "192.168.0.102"},
    "Printer 4": {"ip": "192.168.0.103"},
    "Printer 5": {"ip": "192.168.0.104"},
    "Printer 6": {"ip": "192.168.0.106"}
}

# Logging-Konfiguration
LOG_DIR = "logs"
LOG_SUBDIRS = ["app", "scheduler", "auth", "jobs", "printers", "errors"]
LOG_LEVEL = "INFO"
LOG_FORMAT = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
LOG_DATE_FORMAT = "%Y-%m-%d %H:%M:%S"

# Flask-Konfiguration
FLASK_HOST = "0.0.0.0"
FLASK_PORT = 443
FLASK_FALLBACK_PORT = 80
FLASK_DEBUG = True
SESSION_LIFETIME = timedelta(days=7)

# SSL-Konfiguration
SSL_ENABLED = True
SSL_CERT_PATH = "instance/ssl/myp.crt"
SSL_KEY_PATH = "instance/ssl/myp.key"
SSL_HOSTNAME = "raspberrypi"

# Scheduler-Konfiguration
SCHEDULER_INTERVAL = 60  # Sekunden
SCHEDULER_ENABLED = True

# Datenbank-Konfiguration
DB_ENGINE = f"sqlite:///{DATABASE_PATH}"

def get_log_file(category: str) -> str:
    """
    Gibt den Pfad zur Log-Datei für eine bestimmte Kategorie zurück.
    
    Args:
        category: Log-Kategorie (app, scheduler, auth, jobs, printers, errors)
        
    Returns:
        str: Pfad zur Log-Datei
    """
    if category not in LOG_SUBDIRS:
        category = "app"
    
    return os.path.join(LOG_DIR, category, f"{category}.log")

def ensure_log_directories():
    """Erstellt alle erforderlichen Log-Verzeichnisse."""
    os.makedirs(LOG_DIR, exist_ok=True)
    for subdir in LOG_SUBDIRS:
        os.makedirs(os.path.join(LOG_DIR, subdir), exist_ok=True)

def ensure_database_directory():
    """Erstellt das Datenbank-Verzeichnis."""
    db_dir = os.path.dirname(DATABASE_PATH)
    if db_dir:
        os.makedirs(db_dir, exist_ok=True)

def ensure_ssl_directory():
    """Erstellt das SSL-Verzeichnis, falls es nicht existiert."""
    ssl_dir = os.path.dirname(SSL_CERT_PATH)
    if ssl_dir and not os.path.exists(ssl_dir):
        os.makedirs(ssl_dir, exist_ok=True)

def get_ssl_context():
    """
    Gibt den SSL-Kontext für Flask zurück, wenn SSL aktiviert ist.
    
    Returns:
        tuple oder None: Tuple mit Zertifikat- und Schlüsselpfad, wenn SSL aktiviert ist, sonst None
    """
    if not SSL_ENABLED:
        return None
    
    # Wenn Zertifikate nicht existieren, diese automatisch erstellen
    if not os.path.exists(SSL_CERT_PATH) or not os.path.exists(SSL_KEY_PATH):
        ensure_ssl_directory()
               
        # Prüfen, ob wir uns im Entwicklungsmodus befinden
        if FLASK_DEBUG:
            print("SSL-Zertifikate nicht gefunden. Erstelle selbstsignierte Zertifikate...")
            
            # SSL-Zertifikate direkt mit Python erstellen
            try:
                from cryptography import x509
                from cryptography.x509.oid import NameOID
                from cryptography.hazmat.primitives import hashes
                from cryptography.hazmat.primitives.asymmetric import rsa
                from cryptography.hazmat.primitives import serialization
                import ipaddress
                
                # Private Key generieren
                private_key = rsa.generate_private_key(
                    public_exponent=65537,
                    key_size=2048,
                )
                
                # Subject und Issuer für Mercedes-Benz Werk Berlin 040
                subject = issuer = x509.Name([
                    x509.NameAttribute(NameOID.COUNTRY_NAME, "DE"),
                    x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, "Berlin"),
                    x509.NameAttribute(NameOID.LOCALITY_NAME, "Berlin"),
                    x509.NameAttribute(NameOID.ORGANIZATION_NAME, "Mercedes-Benz AG"),
                    x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, "Werk Berlin 040"),
                    x509.NameAttribute(NameOID.COMMON_NAME, "raspberrypi"),
                ])
                
                # Zertifikat erstellen
                cert = x509.CertificateBuilder().subject_name(
                    subject
                ).issuer_name(
                    issuer
                ).public_key(
                    private_key.public_key()
                ).serial_number(
                    x509.random_serial_number()
                ).not_valid_before(
                    datetime.utcnow()
                ).not_valid_after(
                    datetime.utcnow() + timedelta(days=365)
                ).add_extension(
                    x509.SubjectAlternativeName([
                        x509.DNSName("raspberrypi"),
                        x509.DNSName("localhost"),
                        x509.IPAddress(ipaddress.IPv4Address("192.168.0.105")),
                        x509.IPAddress(ipaddress.IPv4Address("127.0.0.1")),
                    ]),
                    critical=False,
                ).sign(private_key, hashes.SHA256())
                
                # Zertifikat speichern
                with open(SSL_CERT_PATH, "wb") as f:
                    f.write(cert.public_bytes(serialization.Encoding.PEM))
                
                # Private Key speichern
                with open(SSL_KEY_PATH, "wb") as f:
                    f.write(private_key.private_bytes(
                        encoding=serialization.Encoding.PEM,
                        format=serialization.PrivateFormat.PKCS8,
                        encryption_algorithm=serialization.NoEncryption()
                    ))
                
                print(f"✅ SSL-Zertifikate erfolgreich erstellt für Mercedes-Benz Werk Berlin 040")
                print(f"   Hostname: raspberrypi")
                print(f"   IP: 192.168.0.105")
                
            except ImportError:
                print("FEHLER: cryptography-Bibliothek nicht installiert. Installiere mit: pip install cryptography")
                return None
            except Exception as e:
                print(f"FEHLER beim Erstellen der SSL-Zertifikate: {e}")
                return None
        else:
            print("WARNUNG: SSL-Zertifikate nicht gefunden und Nicht-Debug-Modus. SSL wird deaktiviert.")
            return None
    
    return (SSL_CERT_PATH, SSL_KEY_PATH) 