#!/usr/bin/env python3

import importlib.util
import os
import shutil

from fenrirscreenreader.core.i18n import _

# Load base configuration class
_base_path = os.path.join(os.path.dirname(__file__), "..", "config_base.py")
_spec = importlib.util.spec_from_file_location("config_base", _base_path)
_module = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(_module)
config_command = _module.config_command


class command(config_command):
    def __init__(self):
        super().__init__()

    def get_description(self):
        return "Reset configuration to default settings"

    def run(self):
        self.present_text("WARNING: This will reset all settings to defaults")
        self.present_text("Creating backup before reset...")

        # Create backup first
        backupSuccess, backupMessage = self.backup_config(announce=False)
        if not backupSuccess:
            self.present_text(
                "Failed to create backup. Reset cancelled for safety.",
                interrupt=False,
            )
            self.play_sound("Error")
            return

        # Find default configuration file
        default_config_path = self.find_default_config()

        if default_config_path and os.path.isfile(default_config_path):
            try:
                # Copy default configuration over current
                shutil.copy2(default_config_path, self.settings_file)

                # Reload the configuration
                self.reload_config()

                self.present_text(
                    "Configuration reset to defaults successfully",
                    interrupt=False,
                    flush=False,
                )
                self.present_text(
                    "Please restart Fenrir for all changes to take effect",
                    interrupt=False,
                    flush=False,
                )

            except Exception as e:
                self.present_text(
                    f"Failed to reset configuration: {str(e)}",
                    interrupt=False,
                    flush=False,
                )
        else:
            # Manually create basic default configuration
            self.create_basic_defaults()

    def find_default_config(self):
        """Find the default configuration file"""
        possible_paths = [
            "/usr/share/fenrirscreenreader/config/settings/settings.conf",
            "/etc/fenrirscreenreader/settings/settings.conf.default",
            os.path.join(
                os.path.dirname(self.settings_file), "settings.conf.default"
            ),
            # Development path
            os.path.join(
                os.path.dirname(__file__),
                "..",
                "..",
                "..",
                "..",
                "..",
                "..",
                "config",
                "settings",
                "settings.conf",
            ),
        ]

        for path in possible_paths:
            if os.path.isfile(path):
                return path

        return None

    def create_basic_defaults(self):
        """Create basic default configuration manually"""
        try:
            self.config.clear()

            # Basic speech defaults
            self.config["speech"] = {
                "enabled": "True",
                "driver": "speechdDriver",
                "rate": "0.5",
                "pitch": "0.5",
                "volume": "1.0",
                "auto_read_incoming": "True",
            }

            # Basic sound defaults
            self.config["sound"] = {
                "enabled": "True",
                "driver": "genericDriver",
                "theme": "default",
                "volume": "0.7",
            }

            # Basic keyboard defaults
            self.config["keyboard"] = {
                "driver": "evdevDriver",
                "device": "ALL",
                "keyboard_layout": "desktop",
                "char_echo_mode": "1",
                "word_echo": "False",
                "char_delete_echo": "True",
            }

            # Basic screen defaults
            self.config["screen"] = {
                "driver": "vcsaDriver",
                "encoding": "auto",
            }

            # Basic general defaults
            self.config["general"] = {
                "punctuation_level": "some",
                "debug_level": "0",
                "number_of_clipboards": "50",
            }

            # Write the configuration
            with open(self.settings_file, "w") as configfile:
                self.config.write(configfile)

            self.present_text(
                "Basic default configuration created",
                interrupt=False,
                flush=False,
            )
            self.present_text(
                "Please restart Fenrir for changes to take effect",
                interrupt=False,
                flush=False,
            )

        except Exception as e:
            self.present_text(
                f"Failed to create default configuration: {str(e)}",
                interrupt=False,
                flush=False,
            )
