"""
API Routes - AutoBackups
Rutas de la API REST para operaciones AJAX
"""

from flask import request, jsonify


def register_api_routes(app, autobackups_instance):
    """Registrar rutas API de la aplicación"""

    @app.route("/api/config")
    def get_config():
        """Obtener configuración actual"""
        try:
            return jsonify(
                {
                    "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,
                }
            )
        except Exception as e:
            autobackups_instance.logger.error(f"Error getting config: {e}")
            return jsonify({"error": str(e)}), 500

    @app.route("/api/projects")
    def get_projects():
        """Obtener lista de proyectos"""
        try:
            projects = autobackups_instance.project_manager.get_all_projects()
            projects_dict = [project.to_dict() for project in projects]
            return jsonify({"projects": projects_dict})
        except Exception as e:
            autobackups_instance.logger.error(f"Error getting projects: {e}")
            return jsonify({"error": str(e)}), 500

    @app.route("/api/projects/<project_id>/backup", methods=["POST"])
    def manual_backup(project_id):
        """Ejecutar backup manual de un proyecto"""
        try:
            autobackups_instance.logger.info(
                f"Backup manual solicitado para: {project_id}"
            )

            # Obtener el proyecto
            project = autobackups_instance.project_manager.get_project(project_id)
            if not project:
                return jsonify({"error": f"Proyecto {project_id} no encontrado"}), 404

            # Ejecutar backup usando el servicio
            backup_result = autobackups_instance.backup_service.backup_project(project)

            if backup_result["success"]:
                # Actualizar información del proyecto si el backup fue exitoso
                if "backup_file" in backup_result:
                    project.update_backup_info(backup_result["backup_file"])
                    autobackups_instance.project_manager.save_projects()

                return jsonify(
                    {
                        "status": "success",
                        "message": backup_result["message"],
                        "backup_file": backup_result.get("backup_file"),
                        "file_size_mb": backup_result.get("file_size_mb"),
                    }
                )
            else:
                return jsonify({"error": backup_result["error"]}), 500

        except Exception as e:
            autobackups_instance.logger.error(f"Error in manual backup: {e}")
            return jsonify({"error": str(e)}), 500

    @app.route("/api/projects/<project_id>/config", methods=["PUT"])
    def update_project_config(project_id):
        """Actualizar configuración de un proyecto"""
        try:
            data = request.get_json()

            if not data:
                return jsonify({"error": "No data provided"}), 400

            # Usar el método real del ProjectManager
            success = autobackups_instance.project_manager.update_project_config(  # noqa: E501
                project_id, data
            )

            if success:
                autobackups_instance.logger.info(
                    f"Config actualizada para: {project_id}"
                )
                return jsonify({"status": "success"})
            else:
                error_msg = f"No se pudo actualizar el proyecto {project_id}"
                autobackups_instance.logger.error(error_msg)
                return jsonify({"error": error_msg}), 404

        except Exception as e:
            autobackups_instance.logger.error(f"Error updating project config: {e}")
            return jsonify({"error": str(e)}), 500

    @app.route("/api/scan", methods=["POST"])
    def scan_projects():
        """Escanear directorios en busca de nuevos proyectos"""
        try:
            projects_found = autobackups_instance.discover_projects()
            return jsonify({"status": "success", "projects_found": projects_found})
        except Exception as e:
            autobackups_instance.logger.error(f"Error scanning projects: {e}")
            return jsonify({"error": str(e)}), 500

    @app.route("/api/system/status")
    def system_status():
        """Obtener estado del sistema"""
        try:
            backup_dest = autobackups_instance.config.backup_destination
            total_mb, used_mb, free_mb = (
                autobackups_instance.disk_checker.get_disk_usage_info(backup_dest)
            )

            return jsonify(
                {
                    "disk_space": {
                        "total_mb": total_mb,
                        "used_mb": used_mb,
                        "free_mb": free_mb,
                    },
                    "projects": {
                        "total": len(
                            autobackups_instance.project_manager.get_all_projects()
                        ),
                        "enabled": len(
                            autobackups_instance.project_manager.get_enabled_projects()
                        ),
                    },
                    "everything_api": {
                        "available": hasattr(
                            autobackups_instance.backup_service, "everything_wrapper"
                        )
                    },
                }
            )
        except Exception as e:
            autobackups_instance.logger.error(f"Error getting system status: {e}")
            return jsonify({"error": str(e)}), 500

    @app.route("/api/backup/all", methods=["POST"])
    def backup_all_projects():
        """Ejecutar backup de todos los proyectos habilitados"""
        try:
            enabled_projects = (
                autobackups_instance.project_manager.get_enabled_projects()
            )

            if not enabled_projects:
                return jsonify(
                    {
                        "status": "warning",
                        "message": "No hay proyectos habilitados para backup",
                    }
                )

            # TODO: Implementar backup de todos los proyectos
            autobackups_instance.logger.info(
                f"Backup global iniciado para {len(enabled_projects)} proyectos"
            )

            return jsonify(
                {
                    "status": "success",
                    "message": f"Backup iniciado para {len(enabled_projects)} proyectos",
                    "projects_count": len(enabled_projects),
                }
            )
        except Exception as e:
            autobackups_instance.logger.error(f"Error in backup all: {e}")
            return jsonify({"error": str(e)}), 500

    @app.route("/api/logs")
    def get_logs():
        """Obtener logs recientes"""
        try:
            # TODO: Implementar lectura de logs
            logs = []
            return jsonify({"logs": logs})
        except Exception as e:
            autobackups_instance.logger.error(f"Error getting logs: {e}")
            return jsonify({"error": str(e)}), 500

    # Configuration update endpoints
    @app.route("/api/config/general", methods=["PUT"])
    def update_general_config():
        """Update general configuration settings"""
        try:
            data = request.get_json()

            # Update backup destination
            if "backup_destination" in data:
                autobackups_instance.config.update_config_value(
                    "backup_destination", data["backup_destination"]
                )

            # Update global settings
            if "global_settings" in data:
                for key, value in data["global_settings"].items():
                    autobackups_instance.config.update_config_value(
                        f"global_settings.{key}", value
                    )

            autobackups_instance.logger.info("General configuration updated")
            return jsonify({"success": True, "message": "Configuration updated"})

        except Exception as e:
            autobackups_instance.logger.error(f"Error updating general config: {e}")
            return jsonify({"error": str(e)}), 500

    @app.route("/api/config/backup_options", methods=["PUT"])
    def update_backup_options():
        """Update backup options configuration"""
        try:
            data = request.get_json()

            for key, value in data.items():
                autobackups_instance.config.update_config_value(
                    f"backup_options.{key}", value
                )

            autobackups_instance.logger.info("Backup options updated")
            return jsonify({"success": True, "message": "Backup options updated"})

        except Exception as e:
            autobackups_instance.logger.error(f"Error updating backup options: {e}")
            return jsonify({"error": str(e)}), 500

    @app.route("/api/config/everything_api", methods=["PUT"])
    def update_everything_api():
        """Update Everything API configuration"""
        try:
            data = request.get_json()

            for key, value in data.items():
                autobackups_instance.config.update_config_value(
                    f"everything_api.{key}", value
                )

            autobackups_instance.logger.info("Everything API configuration updated")
            return jsonify(
                {"success": True, "message": "Everything API config updated"}
            )

        except Exception as e:
            autobackups_instance.logger.error(f"Error updating Everything API: {e}")
            return jsonify({"error": str(e)}), 500

    @app.route("/api/config/web_interface", methods=["PUT"])
    def update_web_interface():
        """Update web interface configuration"""
        try:
            data = request.get_json()

            for key, value in data.items():
                autobackups_instance.config.update_config_value(
                    f"web_interface.{key}", value
                )

            autobackups_instance.logger.info("Web interface configuration updated")
            return jsonify({"success": True, "message": "Web interface config updated"})

        except Exception as e:
            autobackups_instance.logger.error(f"Error updating web interface: {e}")
            return jsonify({"error": str(e)}), 500

    @app.route("/api/config/logging", methods=["PUT"])
    def update_logging_config():
        """Update logging configuration"""
        try:
            data = request.get_json()

            for key, value in data.items():
                autobackups_instance.config.update_config_value(f"logging.{key}", value)

            autobackups_instance.logger.info("Logging configuration updated")
            return jsonify({"success": True, "message": "Logging config updated"})

        except Exception as e:
            autobackups_instance.logger.error(f"Error updating logging config: {e}")
            return jsonify({"error": str(e)}), 500

    @app.route("/api/config/directories", methods=["POST"])
    def add_observation_directory():
        """Add a new observation directory"""
        try:
            data = request.get_json()
            path = data.get("path", "").strip()
            dir_type = data.get("type", "").strip()
            description = data.get("description", "").strip()

            if not path or not dir_type:
                return jsonify({"error": "Path and type are required"}), 400

            autobackups_instance.config.add_observation_directory(
                path, dir_type, description
            )

            autobackups_instance.logger.info(f"Added observation directory: {path}")
            return jsonify({"success": True, "message": "Directory added"})

        except Exception as e:
            autobackups_instance.logger.error(f"Error adding directory: {e}")
            return jsonify({"error": str(e)}), 500

    @app.route("/api/config/directories/<int:index>", methods=["DELETE"])
    def remove_observation_directory(index):
        """Remove an observation directory"""
        try:
            directories = autobackups_instance.config.observation_directories

            if 0 <= index < len(directories):
                removed_dir = directories.pop(index)
                config = autobackups_instance.config
                config._config["observation_directories"] = directories
                config.save_config()

                autobackups_instance.logger.info(
                    f"Removed observation directory: " f"{removed_dir.get('path', '')}"
                )
                return jsonify({"success": True, "message": "Directory removed"})
            else:
                return jsonify({"error": "Invalid directory index"}), 400

        except Exception as e:
            autobackups_instance.logger.error(f"Error removing directory: {e}")
            return jsonify({"error": str(e)}), 500

    @app.route("/api/config/directories/<int:index>/toggle", methods=["PUT"])
    def toggle_observation_directory(index):
        """Toggle the enabled state of an observation directory"""
        try:
            data = request.get_json()
            enabled = data.get("enabled", True)

            directories = autobackups_instance.config.observation_directories

            if 0 <= index < len(directories):
                directories[index]["enabled"] = enabled
                config = autobackups_instance.config
                config._config["observation_directories"] = directories
                config.save_config()

                autobackups_instance.logger.info(
                    f"Directory {directories[index].get('path', '')} "
                    f"{'enabled' if enabled else 'disabled'}"
                )
                return jsonify({"success": True, "message": "Directory state updated"})
            else:
                return jsonify({"error": "Invalid directory index"}), 400

        except Exception as e:
            autobackups_instance.logger.error(f"Error toggling directory: {e}")
            return jsonify({"error": str(e)}), 500

    @app.route("/api/directories/select", methods=["POST"])
    def select_directory():
        """Abrir selector de directorio nativo usando tkinter"""
        try:
            import tkinter as tk
            from tkinter import filedialog
            import threading
            import queue

            # Obtener parámetros
            data = request.get_json()
            initial_dir = data.get("initial_dir", "")
            title = data.get("title", "Seleccionar Directorio")

            # Queue para comunicar entre threads
            result_queue = queue.Queue()

            def open_dialog():
                """Función para ejecutar el diálogo en un thread separado"""
                try:
                    # Crear ventana root invisible
                    root = tk.Tk()
                    root.withdraw()  # Ocultar ventana principal
                    root.attributes("-topmost", True)  # Mantener encima

                    # Abrir diálogo de selección de directorio
                    selected_path = filedialog.askdirectory(
                        title=title, initialdir=initial_dir if initial_dir else None
                    )

                    # Destruir ventana
                    root.destroy()

                    # Enviar resultado al queue
                    result_queue.put(selected_path)

                except Exception as e:
                    result_queue.put(f"ERROR: {str(e)}")

            # Ejecutar diálogo en thread separado
            dialog_thread = threading.Thread(target=open_dialog)
            dialog_thread.daemon = True
            dialog_thread.start()

            # Esperar resultado con timeout
            try:
                result = result_queue.get(timeout=30)  # 30 segundos timeout

                if result.startswith("ERROR:"):
                    error_msg = result[7:]  # Remover "ERROR: "
                    autobackups_instance.logger.error(
                        f"Error in directory dialog: {error_msg}"
                    )
                    return jsonify({"error": error_msg}), 500

                if result:  # Usuario seleccionó un directorio
                    autobackups_instance.logger.info(f"Directory selected: {result}")
                    return jsonify({"success": True, "selected_path": result})
                else:  # Usuario canceló
                    return jsonify(
                        {"success": False, "message": "Usuario canceló la selección"}
                    )

            except queue.Empty:
                return (
                    jsonify({"error": "Timeout esperando selección de directorio"}),
                    408,
                )

        except Exception as e:
            autobackups_instance.logger.error(f"Error opening directory selector: {e}")
            return jsonify({"error": f"Error abriendo selector: {str(e)}"}), 500
