#!/usr/bin/env python3

from fenrirscreenreader.core.i18n import _


class command:
    def __init__(self):
        pass

    def initialize(self, environment):
        self.env = environment

    def shutdown(self):
        pass

    def get_description(self):
        return "Apply the last tested voice from safe voice browser"

    def run(self):
        try:
            # Check if we have a tested voice
            if (
                "commandBuffer" not in self.env
                or "lastTestedModule" not in self.env["commandBuffer"]
                or "lastTestedVoice" not in self.env["commandBuffer"]
            ):
                self.env["runtime"]["OutputManager"].present_text(
                    "No voice has been tested yet", interrupt=True
                )
                self.env["runtime"]["OutputManager"].present_text(
                    "Use voice browser first", interrupt=True
                )
                return

            module = self.env["commandBuffer"]["lastTestedModule"]
            voice = self.env["commandBuffer"]["lastTestedVoice"]

            self.env["runtime"]["OutputManager"].present_text(
                f"Applying {voice} from {module}", interrupt=True
            )

            # Apply to runtime settings only (temporary until saved)
            SettingsManager = self.env["runtime"]["SettingsManager"]

            # Store old values for safety
            old_driver = SettingsManager.get_setting("speech", "driver")
            old_module = SettingsManager.get_setting("speech", "module")
            old_voice = SettingsManager.get_setting("speech", "voice")

            try:
                # Apply new settings to runtime only (use set_setting to update
                # settingArgDict)
                SettingsManager.set_setting(
                    "speech", "driver", "speechdDriver"
                )
                SettingsManager.set_setting("speech", "module", module)
                SettingsManager.set_setting("speech", "voice", voice)

                # Apply to speech driver instance directly
                if "SpeechDriver" in self.env["runtime"]:
                    SpeechDriver = self.env["runtime"]["SpeechDriver"]

                    # Set the module and voice on the driver instance
                    SpeechDriver.set_module(module)
                    SpeechDriver.set_voice(voice)

                    self.env["runtime"]["OutputManager"].present_text(
                        "Voice applied successfully!", interrupt=True
                    )
                    self.env["runtime"]["OutputManager"].present_text(
                        "Use save settings to make permanent", interrupt=True
                    )
                    self.env["runtime"]["OutputManager"].play_sound("Accept")

            except Exception as e:
                # Revert on failure
                SettingsManager.set_setting("speech", "driver", old_driver)
                SettingsManager.set_setting("speech", "module", old_module)
                SettingsManager.set_setting("speech", "voice", old_voice)

                self.env["runtime"]["OutputManager"].present_text(
                    f"Failed to apply voice, reverted: {str(e)}",
                    interrupt=True,
                )
                self.env["runtime"]["OutputManager"].play_sound("Error")

        except Exception as e:
            self.env["runtime"]["OutputManager"].present_text(
                f"Apply voice error: {str(e)}", interrupt=True
            )
            self.env["runtime"]["OutputManager"].play_sound("Error")

    def set_callback(self, callback):
        pass
