# -*- coding: utf-8 -*-
"""
QGIS Plugin: Cave Levels (Cave-PY)
"""

import os
from qgis.core import QgsProcessingProvider, QgsApplication
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QAction

from .calculate_cave_levels import CalculateCaveLevelsAlgorithm


class CavePyProvider(QgsProcessingProvider):
    def loadAlgorithms(self):
        self.addAlgorithm(CalculateCaveLevelsAlgorithm())

    def id(self):
        return "cavepy"

    def name(self):
        return "Cave-PY"

    def longName(self):
        return "Cave-PY Cave Analysis"


class CavePyPlugin:
    def __init__(self, iface):
        self.iface = iface
        self.provider = None
        self.action = None

    # ---------------------------
    # QGIS plugin entry points
    # ---------------------------
    def initGui(self):
        # 1) Register the Processing provider (existing behavior)
        self.provider = CavePyProvider()
        QgsApplication.processingRegistry().addProvider(self.provider)

        # 2) Create QAction with icon
        icon = self._load_icon()
        self.action = QAction(icon, "Cave-PY: Calculate Cave Levels", self.iface.mainWindow())
        self.action.setObjectName("CavePY_RunAction")
        self.action.triggered.connect(self.run_main)

        # 3) Add button to the **Plugins toolbar**
        self.iface.addToolBarIcon(self.action)

        # 4) Also add to Plugins menu
        self.iface.addPluginToMenu("&Cave-PY", self.action)

    def unload(self):
        # Remove Processing provider
        if self.provider:
            QgsApplication.processingRegistry().removeProvider(self.provider)
            self.provider = None

        # Remove UI elements
        if self.action:
            try:
                self.iface.removePluginMenu("&Cave-PY", self.action)
            except Exception:
                pass
            try:
                self.iface.removeToolBarIcon(self.action)
            except Exception:
                pass
            self.action = None

    # ---------------------------
    # Helpers / actions
    # ---------------------------
    def _load_icon(self) -> QIcon:
        """Load icon.png (or icon.svg) from the plugin root; fall back to empty icon if missing."""
        base = os.path.dirname(__file__)
        for name in ("icon.png", "icon.svg"):
            p = os.path.join(base, name)
            if os.path.exists(p):
                return QIcon(p)
        try:
            from qgis.core import QgsMessageLog
            QgsMessageLog.logMessage(
                "Cave-PY: icon.png/svg not found in plugin root — Plugins toolbar will show text only.",
                tag="Cave-PY",
            )
        except Exception:
            pass
        return QIcon()

    def run_main(self):
        """Open the Calculate Cave Levels algorithm dialog directly."""
        try:
            from qgis import processing
            processing.execAlgorithmDialog("cavepy:calculatecavelevels")
        except Exception as e:
            try:
                self.iface.messageBar().pushWarning("Cave-PY", f"Could not launch algorithm: {e}")
            except Exception:
                pass
            try:
                self.iface.showProcessingToolbox()
            except Exception:
                pass
