#!/usr/bin/env python3
#
# Copyright (c) 2025 Stormux
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.

"""Display Version plugin for Cthulhu."""

import logging
from cthulhu.plugin import Plugin, cthulhu_hookimpl
from cthulhu import cthulhuVersion

logger = logging.getLogger(__name__)

class DisplayVersion(Plugin):
    """Plugin that announces the current Cthulhu version."""
    
    def __init__(self, *args, **kwargs):
        """Initialize the plugin."""
        super().__init__(*args, **kwargs)
        logger.info("DisplayVersion plugin initialized")
        self._kb_binding = None
    
    @cthulhu_hookimpl
    def activate(self, plugin=None):
        """Activate the plugin."""
        # Skip if this activation call isn't for us
        if plugin is not None and plugin is not self:
            return
            
        try:
            logger.info("Activating DisplayVersion plugin")
            
            # Register keyboard shortcut
            self._kb_binding = self.registerGestureByString(
                self.speakText, 
                f'Cthulhu screen reader version {cthulhuVersion.version}-{cthulhuVersion.codeName}', 
                'kb:cthulhu+shift+v'
            )
        except Exception as e:
            logger.error(f"Error activating DisplayVersion plugin: {e}")
    
    @cthulhu_hookimpl
    def deactivate(self, plugin=None):
        """Deactivate the plugin."""
        # Skip if this deactivation call isn't for us
        if plugin is not None and plugin is not self:
            return
            
        logger.info("Deactivating DisplayVersion plugin")
    
    def speakText(self, script=None, inputEvent=None):
        """Speak the Cthulhu version when shortcut is pressed."""
        try:
            if self.app:
                state = self.app.getDynamicApiManager().getAPI('CthulhuState')
                if state.activeScript:
                    state.activeScript.presentMessage(
                        f'Cthulhu screen reader version {cthulhuVersion.version}-{cthulhuVersion.codeName}',
                        resetStyles=False
                    )
            return True
        except Exception as e:
            logger.error(f"Error in DisplayVersion speakText: {e}")
            return False