import logging
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
from flask import Blueprint, request, send_file

import config
from auth.decorators import login_required
from utils.export import create_excel_export, prepare_audit_export_data
from db import get_connection

# Create Blueprint
export_bp = Blueprint('export', __name__, url_prefix='/export')


@export_bp.route("/licenses")
@login_required
def export_licenses():
    """Exportiert Lizenzen als Excel-Datei"""
    conn = get_connection()
    cur = conn.cursor()
    
    try:
        # Filter aus Request
        show_test = request.args.get('show_test', 'false') == 'true'
        
        # SQL Query mit optionalem Test-Filter
        if show_test:
            query = """
                SELECT 
                    l.id,
                    l.license_key,
                    c.name as customer_name,
                    c.email as customer_email,
                    l.license_type,
                    l.valid_from,
                    l.valid_until,
                    l.active,
                    l.device_limit,
                    l.created_at,
                    l.is_test,
                    CASE 
                        WHEN l.valid_until < CURRENT_DATE THEN 'Abgelaufen'
                        WHEN l.active = false THEN 'Deaktiviert'
                        ELSE 'Aktiv'
                    END as status,
                    (SELECT COUNT(*) FROM sessions s WHERE s.license_key = l.license_key AND s.active = true) as active_sessions,
                    (SELECT COUNT(DISTINCT device_id) FROM sessions s WHERE s.license_key = l.license_key) as registered_devices
                FROM licenses l
                LEFT JOIN customers c ON l.customer_id = c.id
                ORDER BY l.created_at DESC
            """
        else:
            query = """
                SELECT 
                    l.id,
                    l.license_key,
                    c.name as customer_name,
                    c.email as customer_email,
                    l.license_type,
                    l.valid_from,
                    l.valid_until,
                    l.active,
                    l.device_limit,
                    l.created_at,
                    l.is_test,
                    CASE 
                        WHEN l.valid_until < CURRENT_DATE THEN 'Abgelaufen'
                        WHEN l.active = false THEN 'Deaktiviert'
                        ELSE 'Aktiv'
                    END as status,
                    (SELECT COUNT(*) FROM sessions s WHERE s.license_key = l.license_key AND s.active = true) as active_sessions,
                    (SELECT COUNT(DISTINCT device_id) FROM sessions s WHERE s.license_key = l.license_key) as registered_devices
                FROM licenses l
                LEFT JOIN customers c ON l.customer_id = c.id
                WHERE l.is_test = false
                ORDER BY l.created_at DESC
            """
        
        cur.execute(query)
        
        # Daten für Export vorbereiten
        data = []
        columns = ['ID', 'Lizenzschlüssel', 'Kunde', 'E-Mail', 'Typ', 'Gültig von', 
                  'Gültig bis', 'Aktiv', 'Gerätelimit', 'Erstellt am', 'Test-Lizenz', 
                  'Status', 'Aktive Sessions', 'Registrierte Geräte']
        
        for row in cur.fetchall():
            data.append(list(row))
        
        # Excel-Datei erstellen
        excel_file = create_excel_export(data, columns, 'Lizenzen')
        
        # Datei senden
        filename = f"lizenzen_export_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
        return send_file(
            excel_file,
            mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            as_attachment=True,
            download_name=filename
        )
        
    except Exception as e:
        logging.error(f"Fehler beim Export: {str(e)}")
        return "Fehler beim Exportieren der Lizenzen", 500
    finally:
        cur.close()
        conn.close()


@export_bp.route("/audit")
@login_required
def export_audit():
    """Exportiert Audit-Logs als Excel-Datei"""
    conn = get_connection()
    cur = conn.cursor()
    
    try:
        # Filter aus Request
        days = int(request.args.get('days', 30))
        action_filter = request.args.get('action', '')
        entity_type_filter = request.args.get('entity_type', '')
        
        # Daten für Export vorbereiten
        data = prepare_audit_export_data(days, action_filter, entity_type_filter)
        
        # Excel-Datei erstellen
        columns = ['Zeitstempel', 'Benutzer', 'Aktion', 'Entität', 'Entität ID', 
                  'IP-Adresse', 'Alte Werte', 'Neue Werte', 'Zusatzinfo']
        
        excel_file = create_excel_export(data, columns, 'Audit-Log')
        
        # Datei senden
        filename = f"audit_log_export_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
        return send_file(
            excel_file,
            mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            as_attachment=True,
            download_name=filename
        )
        
    except Exception as e:
        logging.error(f"Fehler beim Export: {str(e)}")
        return "Fehler beim Exportieren der Audit-Logs", 500
    finally:
        cur.close()
        conn.close()


@export_bp.route("/customers")
@login_required
def export_customers():
    """Exportiert Kunden als Excel-Datei"""
    conn = get_connection()
    cur = conn.cursor()
    
    try:
        # SQL Query
        cur.execute("""
            SELECT 
                c.id,
                c.name,
                c.email,
                c.phone,
                c.address,
                c.created_at,
                c.is_test,
                COUNT(l.id) as license_count,
                COUNT(CASE WHEN l.active = true THEN 1 END) as active_licenses,
                COUNT(CASE WHEN l.valid_until < CURRENT_DATE THEN 1 END) as expired_licenses
            FROM customers c
            LEFT JOIN licenses l ON c.id = l.customer_id
            GROUP BY c.id, c.name, c.email, c.phone, c.address, c.created_at, c.is_test
            ORDER BY c.name
        """)
        
        # Daten für Export vorbereiten
        data = []
        columns = ['ID', 'Name', 'E-Mail', 'Telefon', 'Adresse', 'Erstellt am', 
                  'Test-Kunde', 'Anzahl Lizenzen', 'Aktive Lizenzen', 'Abgelaufene Lizenzen']
        
        for row in cur.fetchall():
            data.append(list(row))
        
        # Excel-Datei erstellen
        excel_file = create_excel_export(data, columns, 'Kunden')
        
        # Datei senden
        filename = f"kunden_export_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
        return send_file(
            excel_file,
            mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            as_attachment=True,
            download_name=filename
        )
        
    except Exception as e:
        logging.error(f"Fehler beim Export: {str(e)}")
        return "Fehler beim Exportieren der Kunden", 500
    finally:
        cur.close()
        conn.close()


@export_bp.route("/sessions")
@login_required
def export_sessions():
    """Exportiert Sessions als Excel-Datei"""
    conn = get_connection()
    cur = conn.cursor()
    
    try:
        # Filter aus Request
        days = int(request.args.get('days', 7))
        active_only = request.args.get('active_only', 'false') == 'true'
        
        # SQL Query
        if active_only:
            query = """
                SELECT 
                    s.id,
                    s.license_key,
                    l.customer_name,
                    s.username,
                    s.device_id,
                    s.login_time,
                    s.logout_time,
                    s.last_activity,
                    s.active,
                    l.license_type,
                    l.is_test
                FROM sessions s
                LEFT JOIN licenses l ON s.license_key = l.license_key
                WHERE s.active = true
                ORDER BY s.login_time DESC
            """
            cur.execute(query)
        else:
            query = """
                SELECT 
                    s.id,
                    s.license_key,
                    l.customer_name,
                    s.username,
                    s.device_id,
                    s.login_time,
                    s.logout_time,
                    s.last_activity,
                    s.active,
                    l.license_type,
                    l.is_test
                FROM sessions s
                LEFT JOIN licenses l ON s.license_key = l.license_key
                WHERE s.login_time >= CURRENT_TIMESTAMP - INTERVAL '%s days'
                ORDER BY s.login_time DESC
            """
            cur.execute(query, (days,))
        
        # Daten für Export vorbereiten
        data = []
        columns = ['ID', 'Lizenzschlüssel', 'Kunde', 'Benutzer', 'Geräte-ID', 
                  'Login-Zeit', 'Logout-Zeit', 'Letzte Aktivität', 'Aktiv', 
                  'Lizenztyp', 'Test-Lizenz']
        
        for row in cur.fetchall():
            data.append(list(row))
        
        # Excel-Datei erstellen
        excel_file = create_excel_export(data, columns, 'Sessions')
        
        # Datei senden
        filename = f"sessions_export_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
        return send_file(
            excel_file,
            mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            as_attachment=True,
            download_name=filename
        )
        
    except Exception as e:
        logging.error(f"Fehler beim Export: {str(e)}")
        return "Fehler beim Exportieren der Sessions", 500
    finally:
        cur.close()
        conn.close()


@export_bp.route("/resources")
@login_required
def export_resources():
    """Exportiert Ressourcen als Excel-Datei"""
    conn = get_connection()
    cur = conn.cursor()
    
    try:
        # Filter aus Request
        resource_type = request.args.get('type', 'all')
        status_filter = request.args.get('status', 'all')
        show_test = request.args.get('show_test', 'false') == 'true'
        
        # SQL Query aufbauen
        query = """
            SELECT 
                rp.id,
                rp.resource_type,
                rp.resource_value,
                rp.status,
                rp.is_test,
                l.license_key,
                c.name as customer_name,
                rp.created_at,
                rp.created_by,
                rp.status_changed_at,
                rp.status_changed_by,
                rp.quarantine_reason
            FROM resource_pools rp
            LEFT JOIN licenses l ON rp.allocated_to_license = l.id
            LEFT JOIN customers c ON l.customer_id = c.id
            WHERE 1=1
        """
        
        params = []
        
        if resource_type != 'all':
            query += " AND rp.resource_type = %s"
            params.append(resource_type)
        
        if status_filter != 'all':
            query += " AND rp.status = %s"
            params.append(status_filter)
        
        if not show_test:
            query += " AND rp.is_test = false"
        
        query += " ORDER BY rp.resource_type, rp.resource_value"
        
        cur.execute(query, params)
        
        # Daten für Export vorbereiten
        data = []
        columns = ['ID', 'Typ', 'Wert', 'Status', 'Test-Ressource', 'Lizenzschlüssel', 
                  'Kunde', 'Erstellt am', 'Erstellt von', 'Status geändert am', 
                  'Status geändert von', 'Quarantäne-Grund']
        
        for row in cur.fetchall():
            data.append(list(row))
        
        # Excel-Datei erstellen
        excel_file = create_excel_export(data, columns, 'Ressourcen')
        
        # Datei senden
        filename = f"ressourcen_export_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
        return send_file(
            excel_file,
            mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            as_attachment=True,
            download_name=filename
        )
        
    except Exception as e:
        logging.error(f"Fehler beim Export: {str(e)}")
        return "Fehler beim Exportieren der Ressourcen", 500
    finally:
        cur.close()
        conn.close()