"""
Test script for the configuration interface
Minimal Flask app to test the configuration features
"""

import sys
from pathlib import Path
from flask import Flask, render_template, request, jsonify

# Add the src directory to the path
sys.path.append(str(Path(__file__).parent / "src"))

from models.config_model import Config

app = Flask(
    __name__,
    template_folder=str(Path(__file__).parent / "templates"),
    static_folder=str(Path(__file__).parent / "static"),
)


# Mock autobackups instance for testing
class MockAutoBackups:
    def __init__(self):
        self.config = Config()
        print(
            f"Configuration loaded with {len(self.config.observation_directories)} directories"
        )


# Initialize mock instance
autobackups_instance = MockAutoBackups()


@app.route("/")
def dashboard():
    """Simple dashboard for testing"""
    return render_template("base.html")


@app.route("/config")
def config_page():
    """Configuration page"""
    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:
        return f"Error loading configuration: {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
                )

        print("General configuration updated")
        return jsonify({"success": True, "message": "Configuration updated"})

    except Exception as e:
        print(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
            )

        print("Backup options updated")
        return jsonify({"success": True, "message": "Backup options updated"})

    except Exception as e:
        print(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
            )

        print("Everything API configuration updated")
        return jsonify({"success": True, "message": "Everything API config updated"})

    except Exception as e:
        print(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
            )

        print("Web interface configuration updated")
        return jsonify({"success": True, "message": "Web interface config updated"})

    except Exception as e:
        print(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)

        print("Logging configuration updated")
        return jsonify({"success": True, "message": "Logging config updated"})

    except Exception as e:
        print(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
        )

        print(f"Added observation directory: {path}")
        return jsonify({"success": True, "message": "Directory added"})

    except Exception as e:
        print(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()

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

    except Exception as e:
        print(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()

            print(
                f"Directory {directories[index].get('path', '')} {'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:
        print(f"Error toggling directory: {e}")
        return jsonify({"error": str(e)}), 500


if __name__ == "__main__":
    print("Starting AutoBackups Configuration Test Server...")
    print("Access the configuration interface at: http://localhost:5120/config")
    app.run(host="127.0.0.1", port=5120, debug=True)
