"""
Web Routes - AutoBackups
Rutas principales de la interfaz web
"""

from flask import render_template, redirect, url_for


def register_web_routes(app, autobackups_instance):
    """Registrar rutas web de la aplicación"""

    @app.route("/")
    def dashboard():
        """Dashboard principal"""
        try:
            print("=== DEBUG: Iniciando dashboard ===")
            projects = autobackups_instance.project_manager.get_all_projects()
            print(f"DEBUG: Proyectos obtenidos: {len(projects)}")

            # Verificar el tipo de los proyectos
            for i, project in enumerate(projects):
                print(f"DEBUG: Proyecto {i}: tipo = {type(project)}")
                print(f"DEBUG: Proyecto {i}: atributos = {dir(project)}")
                if i == 0:  # Solo el primero para no hacer spam
                    break

            enabled_projects = (
                autobackups_instance.project_manager.get_enabled_projects()
            )
            print(f"DEBUG: Proyectos habilitados: {len(enabled_projects)}")

            # Información de sistema
            backup_dest = autobackups_instance.config.backup_destination
            total_mb, used_mb, free_mb = (
                autobackups_instance.disk_checker.get_disk_usage_info(backup_dest)
            )

            stats = {
                "total_projects": len(projects),
                "enabled_projects": len(enabled_projects),
                "total_space_mb": total_mb,
                "used_space_mb": used_mb,
                "free_space_mb": free_mb,
            }

            print("DEBUG: Llamando render_template...")
            return render_template("dashboard.html", projects=projects, stats=stats)

        except Exception as e:
            print(f"DEBUG: Error completo: {e}")
            import traceback

            traceback.print_exc()
            autobackups_instance.logger.error(f"Error en dashboard: {e}")
            return render_template("error.html", error=str(e))

    @app.route("/projects")
    def projects_page():
        """Página de gestión de proyectos"""
        try:
            projects = autobackups_instance.project_manager.get_all_projects()
            return render_template("projects.html", projects=projects)
        except Exception as e:
            autobackups_instance.logger.error(f"Error en página de proyectos: {e}")
            return render_template("error.html", error=str(e))

    @app.route("/config")
    def config_page():
        """Página de configuración"""
        try:
            config_data = {
                "observation_directories": autobackups_instance.config.observation_directories,
                "backup_destination": autobackups_instance.config.backup_destination,
                "global_settings": autobackups_instance.config.global_settings,
                "web_interface": autobackups_instance.config.web_interface,
                "everything_api": autobackups_instance.config.everything_api,
                "logging": autobackups_instance.config.logging_config,
                "backup_options": autobackups_instance.config.backup_options,
            }
            return render_template("config.html", config=config_data)
        except Exception as e:
            autobackups_instance.logger.error(f"Error en página de configuración: {e}")
            return render_template("error.html", error=str(e))

    @app.route("/logs")
    def logs_page():
        """Página de visualización de logs"""
        try:
            # TODO: Implementar lectura de logs
            logs = []
            return render_template("logs.html", logs=logs)
        except Exception as e:
            autobackups_instance.logger.error(f"Error en página de logs: {e}")
            return render_template("error.html", error=str(e))

    @app.errorhandler(404)
    def not_found(error):
        """Manejo de error 404"""
        return render_template("error.html", error="Página no encontrada"), 404

    @app.errorhandler(500)
    def internal_error(error):
        """Manejo de error 500"""
        return (
            render_template("error.html", error="Error interno del servidor"),
            500,
        )
