#!/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 "Adjust speech rate (temporary - use save to make permanent)"

    def run(self):
        try:
            # Get current rate from runtime settings (may be temporary)
            SettingsManager = self.env["runtime"]["SettingsManager"]
            current_rate = float(SettingsManager.get_setting("speech", "rate"))
        except Exception as e:
            current_rate = 0.5

        # Present current rate
        rate_percent = int(current_rate * 100)
        self.env["runtime"]["OutputManager"].present_text(
            f"Current speech rate: {rate_percent} percent", interrupt=True
        )

        # Increase by 10%, wrap around if at max
        new_rate = current_rate + 0.1
        if new_rate > 1.0:
            new_rate = 0.1  # Wrap to minimum

        # Apply ONLY to runtime - this is temporary until saved
        SettingsManager = self.env["runtime"]["SettingsManager"]
        SettingsManager.settings["speech"]["rate"] = str(new_rate)

        # Apply to speech system immediately for this session
        if "SpeechDriver" in self.env["runtime"]:
            try:
                self.env["runtime"]["SpeechDriver"].set_rate(new_rate)
            except Exception as e:
                print(
                    f"adjust_speech_rate set_rate: Error setting speech rate: {str(e)}"
                )

        new_percent = int(new_rate * 100)
        self.env["runtime"]["OutputManager"].present_text(
            f"Speech rate temporarily set to {new_percent} percent",
            interrupt=False,
            flush=False,
        )
        self.env["runtime"]["OutputManager"].present_text(
            "Use save command to make permanent", interrupt=False, flush=False
        )

    def set_callback(self, callback):
        pass
