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

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


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 "No description found"

    def run(self):
        if self.env["input"]["old_num_lock"] == self.env["input"]["new_num_lock"]:
            return

        # Only announce numlock changes if an actual numlock key was pressed
        # AND the LED state actually changed (some numpads send spurious NUMLOCK events)
        current_input = self.env["input"]["curr_input"]
        previous_input = self.env["input"]["prev_input"]
        relevant_input = current_input or previous_input

        # Check if this is a genuine numlock key press by verifying:
        # 1. KEY_NUMLOCK is in the current input sequence
        # 2. The LED state has actually changed
        # 3. This isn't just a side effect from a KP_ key (which some buggy numpads do)
        is_genuine_numlock = (
            relevant_input and
            "KEY_NUMLOCK" in relevant_input and
            not any(
                key.startswith("KEY_KP")
                for key in relevant_input
                if isinstance(key, str)
            )
        )

        if is_genuine_numlock:
            if self.env["input"]["new_num_lock"]:
                self.env["runtime"]["OutputManager"].present_text(
                    _("Numlock on"), interrupt=True
                )
            else:
                self.env["runtime"]["OutputManager"].present_text(
                    _("Numlock off"), interrupt=True
                )

    def set_callback(self, callback):
        pass
