# -*- coding: utf-8 -*-
"""
AI Vectorizer for Archaeology - Main Plugin Class

Copyright (C) 2026 nuri9
GNU General Public License v2
"""

import os
from qgis.PyQt.QtCore import QCoreApplication, Qt
from qgis.PyQt.QtGui import QIcon
try:
    from qgis.PyQt.QtGui import QAction
except ImportError:  # PyQt5
    from qgis.PyQt.QtWidgets import QAction

from .ui.main_dialog import AIVectorizerDialog
from .config import PLUGIN_MENU, PLUGIN_NAME, PLUGIN_TOOLBAR_OBJECT_NAME


def _left_dock_area():
    legacy = getattr(Qt, "LeftDockWidgetArea", None)
    if legacy is not None:
        return legacy
    return Qt.DockWidgetArea.LeftDockWidgetArea


class AIVectorizer:
    """Main QGIS Plugin class for AI Vectorizer."""

    def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance for QGIS.
        :type iface: QgsInterface
        """
        self.iface = iface
        self.plugin_dir = os.path.dirname(__file__)
        self.actions = []
        self.menu = PLUGIN_MENU
        self.toolbar = None
        self.dialog = None

    def tr(self, message):
        """Get the translation for a string."""
        return QCoreApplication.translate(PLUGIN_NAME, message)

    @staticmethod
    def _log_cleanup_warning(context, exc):
        print(f"{context}: {exc}")

    def add_action(
        self,
        icon_path,
        text,
        callback,
        enabled_flag=True,
        add_to_menu=True,
        add_to_toolbar=True,
        status_tip=None,
        whats_this=None,
        parent=None
    ):
        """Add a toolbar icon / menu item."""
        icon = QIcon(icon_path)
        action = QAction(icon, text, parent)
        action.triggered.connect(callback)
        action.setEnabled(enabled_flag)

        if status_tip is not None:
            action.setStatusTip(status_tip)

        if whats_this is not None:
            action.setWhatsThis(whats_this)

        if add_to_toolbar:
            if self.toolbar is None:
                self.toolbar = self.iface.addToolBar(PLUGIN_NAME)
                self.toolbar.setObjectName(PLUGIN_TOOLBAR_OBJECT_NAME)
            self.toolbar.addAction(action)

        if add_to_menu:
            self.iface.addPluginToVectorMenu(self.menu, action)

        self.actions.append(action)
        return action

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""
        icon_path = os.path.join(self.plugin_dir, 'icon.png')

        # Main dialog action
        self.add_action(
            icon_path,
            text=self.tr(PLUGIN_NAME),
            callback=self.run,
            parent=self.iface.mainWindow(),
            status_tip=self.tr(f'Open {PLUGIN_NAME} dialog')
        )

    def unload(self):
        """Remove the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginVectorMenu(self.menu, action)
            if self.toolbar is not None:
                self.toolbar.removeAction(action)
            self.iface.removeToolBarIcon(action)
            try:
                action.triggered.disconnect()
            except (RuntimeError, TypeError):
                pass
            action.deleteLater()
        self.actions.clear()

        if self.dialog is not None:
            try:
                self.dialog.cleanup(permanent=True)
            except Exception as exc:
                self._log_cleanup_warning("Dialog cleanup failed", exc)

            removed = False
            try:
                self.iface.removeDockWidget(self.dialog)
                removed = True
            except Exception as exc:
                self._log_cleanup_warning("Dock widget removal via iface failed", exc)

            if not removed:
                try:
                    self.iface.mainWindow().removeDockWidget(self.dialog)
                except Exception as exc:
                    self._log_cleanup_warning(
                        "Dock widget removal via main window failed",
                        exc,
                    )
            self.dialog.close()
            self.dialog.deleteLater()
            self.dialog = None

        if self.toolbar is not None:
            try:
                self.iface.mainWindow().removeToolBar(self.toolbar)
            except Exception as exc:
                self._log_cleanup_warning("Toolbar removal failed", exc)
            self.toolbar.deleteLater()
            self.toolbar = None

    def run(self):
        """Open the main plugin as a docked panel on the left."""
        if self.dialog is None:
            self.dialog = AIVectorizerDialog(self.iface, parent=self.iface.mainWindow())
            # Add as dock widget to left side
            self.iface.addDockWidget(_left_dock_area(), self.dialog)

        self.dialog.show()
        self.dialog.raise_()
