#!/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
import os

import gi
gi.require_version("Atspi", "2.0")
from gi.repository import Atspi

from cthulhu.plugin import Plugin, cthulhu_hookimpl
from cthulhu import cthulhuVersion
from cthulhu import cthulhu_platform
from cthulhu import debug

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)
        debug.printMessage(debug.LEVEL_INFO, "DisplayVersion: Plugin initialized", True)
        self._kb_binding = None
        self._activated = False

    def _get_version_string(self):
        """Generate the full version string with AT-SPI and session information."""
        version_suffix = f'-{cthulhuVersion.codeName}' if cthulhuVersion.codeName else ''
        msg = f'Cthulhu screen reader version {cthulhuVersion.version}{version_suffix}'
        if cthulhu_platform.revision:
            msg += f' revision {cthulhu_platform.revision}'

        atspi_version = Atspi.get_version()
        msg += f', AT-SPI2 version {atspi_version[0]}.{atspi_version[1]}.{atspi_version[2]}'

        session_type = os.environ.get('XDG_SESSION_TYPE') or ''
        session_desktop = os.environ.get('XDG_SESSION_DESKTOP') or ''
        session = f'{session_type} {session_desktop}'.strip()
        if session:
            msg += f', Session {session}'

        return msg
    
    @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
            
        # Prevent duplicate activation
        if self._activated:
            debug.printMessage(debug.LEVEL_INFO, "DisplayVersion: Already activated, skipping", True)
            return
            
        try:
            # Use debug.printMessage to ensure it goes to the main debug log
            debug.printMessage(debug.LEVEL_INFO, "DisplayVersion: Plugin activation starting", True)
            debug.printMessage(debug.LEVEL_INFO, f"DisplayVersion: Plugin name: {self.name}", True)
            
            # Check if we have access to the API helper
            if not self.app:
                debug.printMessage(debug.LEVEL_INFO, "DisplayVersion: ERROR - No app reference available!", True)
                return
                
            # Register keyboard shortcut
            gesture_string = 'kb:cthulhu+shift+v'
            debug.printMessage(debug.LEVEL_INFO, f"DisplayVersion: Registering gesture: {gesture_string}", True)

            version_message = self._get_version_string()
            self._kb_binding = self.registerGestureByString(
                self.speakText,
                version_message,
                gesture_string
            )
            
            if self._kb_binding:
                debug.printMessage(debug.LEVEL_INFO, f"DisplayVersion: Keybinding registered successfully", True)
            else:
                debug.printMessage(debug.LEVEL_INFO, "DisplayVersion: ERROR - Failed to create keybinding!", True)
                
            self._activated = True
            debug.printMessage(debug.LEVEL_INFO, "DisplayVersion: Plugin activation completed", True)
        except Exception as e:
            debug.printMessage(debug.LEVEL_INFO, f"DisplayVersion: ERROR activating plugin: {e}", True)
            import traceback
            debug.printMessage(debug.LEVEL_INFO, f"DisplayVersion: {traceback.format_exc()}", True)
    
    @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
            
        self._activated = False
        debug.printMessage(debug.LEVEL_INFO, "DisplayVersion: Plugin deactivated", True)
    
    def speakText(self, script=None, inputEvent=None):
        """Speak the Cthulhu version when shortcut is pressed."""
        try:
            debug.printMessage(debug.LEVEL_INFO, "DisplayVersion: speakText called", True)
            if self.app:
                state = self.app.getDynamicApiManager().getAPI('CthulhuState')
                if state.activeScript:
                    version_message = self._get_version_string()
                    state.activeScript.presentMessage(
                        version_message,
                        resetStyles=False
                    )
            return True
        except Exception as e:
            debug.printMessage(debug.LEVEL_INFO, f"DisplayVersion: ERROR in speakText: {e}", True)
            return False
