"""
Georeferencer Plugin - QGIS Menu & Toolbar Action Integration.
"""

import os
import sys
import importlib
from qgis.PyQt.QtCore import QCoreApplication
from qgis.PyQt.QtWidgets import QAction, QMenu
from qgis.PyQt.QtGui import QIcon

class SmartGeoreferencerPlugin:
    """
    Main QGIS plugin integration wrapper.
    """

    def __init__(self, iface):
        self.iface = iface
        self.plugin_dir = os.path.dirname(__file__)
        self.action = None
        self.main_window = None
        self.ineffable_menu = None

    def initGui(self):
        icon_path = os.path.join(self.plugin_dir, 'icon.png')
        if not os.path.exists(icon_path):
            icon = QIcon(":/images/themes/default/mActionGeoreferencer.svg")
        else:
            icon = QIcon(icon_path)

        self.action = QAction(
            icon,
            QCoreApplication.translate('SmartGeoreferencer', 'Smart Georeferencer'),
            self.iface.mainWindow()
        )
        self.action.setObjectName("smartGeoreferencerAction")
        self.action.setStatusTip("Open Smart Georeferencer")
        self.action.triggered.connect(self.run)

        # Add to toolbar
        self.iface.addToolBarIcon(self.action)

        # Find or create 'Ineffable Tools' top-level menu bar item
        menu_bar = self.iface.mainWindow().menuBar()
        menu_title = 'Ineffable Tools'

        for act in menu_bar.actions():
            if act.text().replace('&', '').strip() == menu_title:
                self.ineffable_menu = act.menu()
                break

        if not self.ineffable_menu:
            self.ineffable_menu = QMenu(menu_title, menu_bar)
            help_act = None
            for act in menu_bar.actions():
                if 'help' in act.text().lower():
                    help_act = act
                    break
            if help_act:
                menu_bar.insertMenu(help_act, self.ineffable_menu)
            else:
                menu_bar.addMenu(self.ineffable_menu)

        self.ineffable_menu.addAction(self.action)

    def unload(self):
        if self.action:
            if self.ineffable_menu:
                self.ineffable_menu.removeAction(self.action)
            self.iface.removeToolBarIcon(self.action)
            del self.action

        if self.main_window:
            try:
                self.main_window.close()
                self.main_window.deleteLater()
            except (AttributeError, RuntimeError) as err:
                from qgis.core import QgsLogger
                QgsLogger.warning(f"Error closing main window: {err}")
            self.main_window = None

    def run(self):
        """
        Open Smart Georeferencer in a separate standalone window.
        """
        if self.main_window:
            try:
                self.main_window.close()
                self.main_window.deleteLater()
            except (AttributeError, RuntimeError) as err:
                from qgis.core import QgsLogger
                QgsLogger.warning(f"Error closing previous main window: {err}")
            self.main_window = None

        for mod in list(sys.modules.keys()):
            if mod.startswith("Georeferencer."):
                del sys.modules[mod]

        from . import core
        importlib.reload(core)

        self.main_window = core.SmartGeoreferencerWindow(self.iface, self.iface.mainWindow())
        self.main_window.show()
        self.main_window.raise_()
        self.main_window.activateWindow()
