#!/usr/bin/env python3
"""
Test-Skript zur Verifizierung aller Blueprint-Routes
Prüft ob alle Routes korrekt registriert sind und erreichbar sind
"""

import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from app import app
from flask import url_for
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def test_all_routes():
    """Test alle registrierten Routes"""
    
    print("=== Blueprint Route Test ===\n")
    
    # Sammle alle Routes
    routes_by_blueprint = {}
    
    with app.test_request_context():
        for rule in app.url_map.iter_rules():
            # Skip static files
            if rule.endpoint == 'static':
                continue
                
            # Blueprint name is before the dot
            parts = rule.endpoint.split('.')
            if len(parts) == 2:
                blueprint_name = parts[0]
                function_name = parts[1]
            else:
                blueprint_name = 'app'
                function_name = rule.endpoint
            
            if blueprint_name not in routes_by_blueprint:
                routes_by_blueprint[blueprint_name] = []
            
            routes_by_blueprint[blueprint_name].append({
                'rule': str(rule),
                'endpoint': rule.endpoint,
                'methods': sorted(rule.methods - {'HEAD', 'OPTIONS'}),
                'function': function_name
            })
    
    # Sortiere und zeige Routes nach Blueprint
    for blueprint_name in sorted(routes_by_blueprint.keys()):
        routes = routes_by_blueprint[blueprint_name]
        print(f"\n📦 Blueprint: {blueprint_name}")
        print(f"   Anzahl Routes: {len(routes)}")
        print("   " + "-" * 50)
        
        for route in sorted(routes, key=lambda x: x['rule']):
            methods = ', '.join(route['methods'])
            print(f"   {route['rule']:<40} [{methods:<15}] -> {route['function']}")
    
    # Zusammenfassung
    print("\n=== Zusammenfassung ===")
    total_routes = sum(len(routes) for routes in routes_by_blueprint.values())
    print(f"Gesamt Blueprints: {len(routes_by_blueprint)}")
    print(f"Gesamt Routes: {total_routes}")
    
    # Erwartete Blueprints prüfen
    expected_blueprints = ['auth', 'admin', 'license', 'customer', 'resource', 
                          'session', 'batch', 'api', 'export']
    
    print("\n=== Blueprint Status ===")
    for bp in expected_blueprints:
        if bp in routes_by_blueprint:
            print(f"✅ {bp:<10} - {len(routes_by_blueprint[bp])} routes")
        else:
            print(f"❌ {bp:<10} - FEHLT!")
    
    # Prüfe ob noch Routes direkt in app.py sind
    if 'app' in routes_by_blueprint:
        print(f"\n⚠️  WARNUNG: {len(routes_by_blueprint['app'])} Routes sind noch direkt in app.py!")
        for route in routes_by_blueprint['app']:
            print(f"   - {route['rule']}")

def test_route_accessibility():
    """Test ob wichtige Routes erreichbar sind"""
    print("\n\n=== Route Erreichbarkeits-Test ===\n")
    
    test_client = app.test_client()
    
    # Wichtige Routes zum Testen (ohne Login)
    public_routes = [
        ('GET', '/login', 'Login-Seite'),
        ('GET', '/heartbeat', 'Session Heartbeat'),
    ]
    
    for method, route, description in public_routes:
        try:
            if method == 'GET':
                response = test_client.get(route)
            elif method == 'POST':
                response = test_client.post(route)
            
            status = "✅" if response.status_code in [200, 302, 401] else "❌"
            print(f"{status} {method:<6} {route:<30} - Status: {response.status_code} ({description})")
            
            # Bei Fehler mehr Details
            if response.status_code >= 400 and response.status_code != 401:
                print(f"   ⚠️  Fehler-Details: {response.data[:200]}")
                
        except Exception as e:
            print(f"❌ {method:<6} {route:<30} - FEHLER: {str(e)}")

def check_duplicate_routes():
    """Prüfe ob es doppelte Route-Definitionen gibt"""
    print("\n\n=== Doppelte Routes Check ===\n")
    
    route_paths = {}
    duplicates_found = False
    
    for rule in app.url_map.iter_rules():
        if rule.endpoint == 'static':
            continue
            
        path = str(rule)
        if path in route_paths:
            print(f"⚠️  DUPLIKAT gefunden:")
            print(f"   Route: {path}")
            print(f"   1. Endpoint: {route_paths[path]}")
            print(f"   2. Endpoint: {rule.endpoint}")
            duplicates_found = True
        else:
            route_paths[path] = rule.endpoint
    
    if not duplicates_found:
        print("✅ Keine doppelten Routes gefunden!")

def check_template_references():
    """Prüfe ob Template-Dateien für die Routes existieren"""
    print("\n\n=== Template Verfügbarkeits-Check ===\n")
    
    template_dir = os.path.join(os.path.dirname(__file__), 'templates')
    
    # Sammle alle verfügbaren Templates
    available_templates = []
    if os.path.exists(template_dir):
        for root, dirs, files in os.walk(template_dir):
            for file in files:
                if file.endswith(('.html', '.jinja2')):
                    rel_path = os.path.relpath(os.path.join(root, file), template_dir)
                    available_templates.append(rel_path.replace('\\', '/'))
    
    print(f"Gefundene Templates: {len(available_templates)}")
    
    # Wichtige Templates prüfen
    required_templates = [
        'login.html',
        'index.html',
        'profile.html',
        'licenses.html',
        'customers.html',
        'resources.html',
        'sessions.html',
        'audit.html',
        'backups.html'
    ]
    
    for template in required_templates:
        if template in available_templates:
            print(f"✅ {template}")
        else:
            print(f"❌ {template} - FEHLT!")

if __name__ == "__main__":
    print("🔍 Starte Blueprint-Verifizierung...\n")
    
    try:
        test_all_routes()
        test_route_accessibility()
        check_duplicate_routes()
        check_template_references()
        
        print("\n\n✅ Test abgeschlossen!")
        
    except Exception as e:
        print(f"\n\n❌ Fehler beim Test: {str(e)}")
        import traceback
        traceback.print_exc()