"""
Blueprints Package
==================

Central registration of all Flask blueprints.
"""

import logging

logger = logging.getLogger(__name__)


def register_blueprints(app):
    """
    Register all blueprints with the Flask application.

    Args:
        app: Flask application instance
    """
    # Phase 1: Low-risk modules

    # Reports blueprint
    try:
        from blueprints.reports import bp as reports_bp
        app.register_blueprint(reports_bp)
        logger.info("Registered blueprint: reports")
    except ImportError as e:
        logger.debug(f"Blueprint reports not yet available: {e}")

    # Community blueprints - register directly (not nested)
    # to preserve endpoint names like 'calendar_index' instead of 'community.calendar.calendar_index'
    try:
        from blueprints.community.contacts import bp as contacts_bp
        app.register_blueprint(contacts_bp)
        logger.info("Registered blueprint: contacts")
    except ImportError as e:
        logger.debug(f"Blueprint contacts not yet available: {e}")

    try:
        from blueprints.community.classifieds import bp as classifieds_bp
        app.register_blueprint(classifieds_bp)
        logger.info("Registered blueprint: classifieds")
    except ImportError as e:
        logger.debug(f"Blueprint classifieds not yet available: {e}")

    try:
        from blueprints.community.calendar import bp as calendar_bp
        app.register_blueprint(calendar_bp)
        logger.info("Registered blueprint: calendar")
    except ImportError as e:
        logger.debug(f"Blueprint calendar not yet available: {e}")

    # Education blueprint
    try:
        from blueprints.education import bp as education_bp
        app.register_blueprint(education_bp)
        logger.info("Registered blueprint: education")
    except ImportError as e:
        logger.debug(f"Blueprint education not yet available: {e}")

    # Phase 2: Auth + Public blueprints (with backward-compatible aliases)
    try:
        from blueprints.auth import bp as auth_bp
        app.register_blueprint(auth_bp)
        logger.info("Registered blueprint: auth")

        # Create aliases for backward compatibility
        # Old url_for('login') will still work alongside url_for('auth.login')
        _create_endpoint_aliases(app, auth_bp, {
            'register': 'auth.register',
            'login': 'auth.login',
            'logout': 'auth.logout',
            'verify_2fa': 'auth.verify_2fa',
            'settings_2fa': 'auth.settings_2fa',
            'settings_privacy': 'auth.settings_privacy',
            'settings_blocks': 'auth.settings_blocks',
            'settings_blocks_add': 'auth.settings_blocks_add',
            'settings_blocks_remove': 'auth.settings_blocks_remove',
            'forgot_password': 'auth.forgot_password',
            'reset_password': 'auth.reset_password',
            'verify_email': 'auth.verify_email',
            'resend_verification': 'auth.resend_verification',
            # Account routes (konto)
            'konto_dane': 'auth.konto_dane',
            'konto_dane_save': 'auth.konto_dane_post',
            'konto_prywatnosc': 'auth.konto_prywatnosc',
            'konto_bezpieczenstwo': 'auth.konto_bezpieczenstwo',
            'konto_blokady': 'auth.konto_blokady',
            'konto_blokady_dodaj': 'auth.konto_blokady_dodaj',
            'konto_blokady_usun': 'auth.konto_blokady_usun',
        })
        logger.info("Created auth endpoint aliases")
    except ImportError as e:
        logger.debug(f"Blueprint auth not yet available: {e}")
    except Exception as e:
        logger.error(f"Error registering auth blueprint: {e}")

    try:
        from blueprints.public import bp as public_bp
        app.register_blueprint(public_bp)
        logger.info("Registered blueprint: public")

        # Create aliases for backward compatibility
        _create_endpoint_aliases(app, public_bp, {
            'index': 'public.index',
            'company_detail': 'public.company_detail',
            'company_detail_by_slug': 'public.company_detail_by_slug',
            'person_detail': 'public.person_detail',
            'company_recommend': 'public.company_recommend',
            'search': 'public.search',
            'events': 'public.events',
            'new_members': 'public.new_members',
            'connections_map': 'public.connections_map',
            'dashboard': 'public.dashboard',
            'release_notes': 'public.release_notes',
        })
        logger.info("Created public endpoint aliases")
    except ImportError as e:
        logger.debug(f"Blueprint public not yet available: {e}")
    except Exception as e:
        logger.error(f"Error registering public blueprint: {e}")

    # Phase 3-10: Future blueprints will be added here


def _create_endpoint_aliases(app, blueprint, aliases):
    """
    Create backward-compatible endpoint aliases.

    This allows old code using url_for('login') to work alongside
    new code using url_for('auth.login').

    Args:
        app: Flask application instance
        blueprint: The blueprint that was just registered
        aliases: Dict mapping old_name -> new_name (blueprint.endpoint)
    """
    for old_name, new_name in aliases.items():
        if new_name in app.view_functions:
            # Find the URL rule for the new endpoint
            for rule in app.url_map.iter_rules():
                if rule.endpoint == new_name:
                    try:
                        # Register the same view function under the old name
                        app.add_url_rule(
                            rule.rule,
                            old_name,
                            app.view_functions[new_name],
                            methods=list(rule.methods - {'OPTIONS', 'HEAD'})
                        )
                        logger.debug(f"Created alias: {old_name} -> {new_name}")
                    except AssertionError:
                        # Endpoint already exists (e.g., still in app.py)
                        logger.debug(f"Alias {old_name} already exists, skipping")
                    break
