#!/usr/bin/env python3.11
"""
Debug-Skript für Admin-Dashboard-Probleme
"""

import sys
import traceback
from app import app
from models import User, get_cached_session
from flask import url_for
from flask_login import login_user

def test_admin_route():
    """Testet die Admin-Route mit verschiedenen Szenarien"""
    
    print("=== ADMIN ROUTE DEBUG ===")
    
    with app.app_context():
        try:
            # 1. Test ohne Login (sollte 302 redirect geben)
            print("\n1. Test ohne Login:")
            with app.test_client() as client:
                response = client.get('/admin/')
                print(f"   Status: {response.status_code}")
                print(f"   Location: {response.headers.get('Location', 'None')}")
            
            # 2. Admin-Benutzer finden
            print("\n2. Admin-Benutzer suchen:")
            with get_cached_session() as session:
                admin_users = session.query(User).filter(User.role == 'admin').all()
                print(f"   Gefundene Admin-Benutzer: {len(admin_users)}")
                
                if admin_users:
                    admin_user = admin_users[0]
                    print(f"   Admin: {admin_user.username} (ID: {admin_user.id})")
                    
                    # 3. Test mit korrektem Flask-Login
                    print("\n3. Test mit Flask-Login:")
                    with app.test_client() as client:
                        # Simuliere Login über POST-Request
                        login_data = {
                            'username': admin_user.username,
                            'password': 'admin123'  # Standard-Admin-Passwort
                        }
                        
                        # Erst einloggen
                        login_response = client.post('/auth/login', data=login_data, follow_redirects=False)
                        print(f"   Login Status: {login_response.status_code}")
                        
                        # Dann Admin-Dashboard aufrufen
                        response = client.get('/admin/', follow_redirects=False)
                        print(f"   Admin Dashboard Status: {response.status_code}")
                        
                        if response.status_code == 500:
                            print("   ERROR DATA:")
                            error_data = response.get_data(as_text=True)
                            print(f"   {error_data[:1000]}...")
                        elif response.status_code == 200:
                            print("   SUCCESS: Admin-Dashboard lädt korrekt!")
                        elif response.status_code == 302:
                            print(f"   Redirect zu: {response.headers.get('Location', 'Unknown')}")
                        else:
                            print(f"   Unerwarteter Status: {response.status_code}")
                            
                    # 4. Test der Admin-Dashboard-Funktion direkt
                    print("\n4. Test der Admin-Dashboard-Funktion direkt:")
                    try:
                        from blueprints.admin_unified import admin_dashboard
                        from flask import g
                        from flask_login import current_user
                        
                        # Simuliere Request-Context
                        with app.test_request_context('/admin/'):
                            # Simuliere eingeloggten Admin
                            login_user(admin_user)
                            
                            # Rufe Dashboard-Funktion direkt auf
                            result = admin_dashboard()
                            print(f"   Direkter Aufruf erfolgreich: {type(result)}")
                            
                    except Exception as e:
                        print(f"   Direkter Aufruf fehlgeschlagen: {e}")
                        traceback.print_exc()
                        
                else:
                    print("   FEHLER: Kein Admin-Benutzer gefunden!")
                    
                    # Admin-Benutzer erstellen
                    print("\n   Erstelle Admin-Benutzer...")
                    from models import create_initial_admin
                    success = create_initial_admin()
                    print(f"   Admin erstellt: {success}")
                    
        except Exception as e:
            print(f"\nFEHLER: {e}")
            traceback.print_exc()

def test_admin_decorator():
    """Testet den Admin-Decorator"""
    print("\n=== ADMIN DECORATOR TEST ===")
    
    try:
        from blueprints.admin_unified import admin_required
        print("✅ Admin-Decorator importiert")
        
        # Test-Funktion mit Decorator
        @admin_required
        def test_func():
            return "Success"
        
        print("✅ Decorator angewendet")
        
    except Exception as e:
        print(f"❌ Decorator-Fehler: {e}")
        traceback.print_exc()

def test_template():
    """Testet das Admin-Template"""
    print("\n=== TEMPLATE TEST ===")
    
    try:
        with app.app_context():
            with app.test_request_context('/admin/'):
                from flask import render_template
                
                # Test mit leeren Stats
                result = render_template('admin.html', stats={})
                print(f"✅ Template gerendert (Länge: {len(result)} Zeichen)")
            
    except Exception as e:
        print(f"❌ Template-Fehler: {e}")
        traceback.print_exc()

def check_admin_user_password():
    """Überprüft das Admin-Benutzer-Passwort"""
    print("\n=== ADMIN PASSWORD CHECK ===")
    
    try:
        with app.app_context():
            with get_cached_session() as session:
                admin_user = session.query(User).filter(User.role == 'admin').first()
                if admin_user:
                    # Teste verschiedene Standard-Passwörter
                    test_passwords = ['admin123', 'admin', 'password', 'test123']
                    
                    for pwd in test_passwords:
                        if admin_user.check_password(pwd):
                            print(f"✅ Admin-Passwort gefunden: {pwd}")
                            return pwd
                    
                    print("❌ Kein Standard-Passwort funktioniert")
                    
                    # Setze neues Passwort
                    print("   Setze neues Admin-Passwort: admin123")
                    admin_user.set_password('admin123')
                    session.commit()
                    print("✅ Neues Passwort gesetzt")
                    return 'admin123'
                else:
                    print("❌ Kein Admin-Benutzer gefunden")
                    return None
                    
    except Exception as e:
        print(f"❌ Passwort-Check-Fehler: {e}")
        return None

if __name__ == "__main__":
    test_admin_decorator()
    test_template()
    check_admin_user_password()
    test_admin_route() 