#!/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.

"""Bye Cthulhu plugin for Cthulhu."""

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

logger = logging.getLogger(__name__)

class ByeCthulhu(Plugin):
    """Plugin that speaks a goodbye message when Cthulhu is shutting down."""

    def __init__(self, *args, **kwargs):
        """Initialize the plugin."""
        super().__init__(*args, **kwargs)
        logger.info("ByeCthulhu plugin initialized")
        self._signal_handler_id = None
        self._is_connected = False

    @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

        logger.info("Activating ByeCthulhu plugin")
        try:
            if not self._is_connected:
                signal_manager = self.app.getSignalManager()
                self._signal_handler_id = signal_manager.connectSignal(
                    "stop-application-completed", 
                    self.process,
                    "default"  # Add profile parameter
                )
                self._is_connected = True
        except Exception as e:
            logger.error(f"Error activating ByeCthulhu 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 ByeCthulhu plugin")
        try:
            if self._is_connected and self._signal_handler_id is not None:
                signal_manager = self.app.getSignalManager()
                # Use disconnectSignalByFunction instead since disconnectSignal doesn't exist
                signal_manager.disconnectSignalByFunction(
                    self.process
                )
                self._signal_handler_id = None
                self._is_connected = False
        except Exception as e:
            logger.error(f"Error deactivating ByeCthulhu plugin: {e}")

    def process(self, app):
        """Process the stop-application-completed signal."""
        try:
            messages = app.getDynamicApiManager().getAPI('Messages')
            state = app.getDynamicApiManager().getAPI('CthulhuState')
            if state.activeScript:
                state.activeScript.presentationInterrupt()
                state.activeScript.presentMessage(messages.STOP_CTHULHU, resetStyles=False)
        except Exception as e:
            logger.error(f"Error in ByeCthulhu process: {e}")
