#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Fenrir TTY screen reader
# By Chrys, Storm Dragon, and contributors.

import configparser
import os
import shutil
import tempfile
from datetime import datetime

from fenrirscreenreader.core.i18n import _


class config_command:
    """Base class for configuration management commands"""

    def __init__(self):
        self.env = None
        self.settings_file = None
        self.config = None

    def initialize(self, environment):
        self.env = environment
        self.settings_file = self.env["runtime"][
            "SettingsManager"
        ].settings_file
        self.config = self.env["runtime"]["SettingsManager"].settings

    def shutdown(self):
        pass

    def set_callback(self, callback):
        pass

    def present_text(self, text, interrupt=True, flush=True):
        """Present text to user with proper speech handling"""
        self.env["runtime"]["OutputManager"].present_text(
            text, interrupt=interrupt, flush=flush
        )

    def play_sound(self, soundName):
        """Play system sound"""
        sound_icon = ""
        if soundName == "Accept":
            sound_icon = "Accept"
        elif soundName == "Error":
            sound_icon = "ErrorSound"
        elif soundName == "Cancel":
            sound_icon = "Cancel"

        if sound_icon:
            self.env["runtime"]["OutputManager"].present_text(
                "", sound_icon=sound_icon, interrupt=False
            )

    def backup_config(self, announce=True):
        """Create backup of current configuration file"""
        try:
            if not os.path.exists(self.settings_file):
                message = "Configuration file not found"
                if announce:
                    self.present_text(message)
                return False, message

            # Create backup with timestamp
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            backup_path = f"{self.settings_file}.backup_{timestamp}"

            shutil.copy2(self.settings_file, backup_path)

            message = f"Configuration backed up to {backup_path}"
            if announce:
                self.present_text("Configuration backup created successfully")
            return True, message

        except Exception as e:
            message = f"Failed to backup configuration: {str(e)}"
            if announce:
                self.present_text(message)
            return False, message

    def reload_config(self):
        """Reload configuration from file"""
        try:
            # Force settings manager to reload from file
            self.env["runtime"]["SettingsManager"].load_settings()
            self.config = self.env["runtime"]["SettingsManager"].settings
            return True

        except Exception as e:
            self.present_text(f"Failed to reload configuration: {str(e)}")
            return False

    def find_default_config(self):
        """Find default configuration file path"""
        # Look for default config in multiple locations
        default_paths = [
            "/etc/fenrir/settings/settings.conf.default",
            "/usr/share/fenrir/settings/settings.conf",
            os.path.join(
                os.path.dirname(self.settings_file), "settings.conf.default"
            ),
            os.path.join(
                os.path.dirname(os.path.dirname(self.settings_file)),
                "settings",
                "settings.conf.default",
            ),
        ]

        for path in default_paths:
            if os.path.exists(path):
                return path

        return None

    def create_basic_defaults(self):
        """Create basic default configuration manually"""
        try:
            # Create a new config with basic defaults
            self.config = configparser.ConfigParser()

            # Add basic sections and settings
            self.config.add_section("speech")
            self.config.set("speech", "driver", "speechdDriver")
            self.config.set("speech", "rate", "0.75")
            self.config.set("speech", "pitch", "0.5")
            self.config.set("speech", "volume", "1.0")

            self.config.add_section("sound")
            self.config.set("sound", "driver", "genericDriver")
            self.config.set("sound", "volume", "0.7")

            self.config.add_section("keyboard")
            self.config.set("keyboard", "driver", "evdevDriver")
            self.config.set("keyboard", "keyboardLayout", "desktop")

            self.config.add_section("screen")
            self.config.set("screen", "driver", "vcsaDriver")

            self.config.add_section("general")
            self.config.set("general", "debug_mode", "Off")

            return True

        except Exception as e:
            self.present_text(f"Failed to create basic defaults: {str(e)}")
            return False

    def get_setting(self, section, setting, default=None):
        """Get setting value from settings manager"""
        try:
            return self.env["runtime"]["SettingsManager"].get_setting(section, setting)
        except Exception:
            return default

    def set_setting(self, section, setting, value):
        """Set setting value via settings manager"""
        try:
            self.env["runtime"]["SettingsManager"].set_setting(section, setting, value)
            return True
        except Exception:
            return False
