# -*- coding: utf-8 -*-
"""
/***************************************************************************
 TempoSalvoTools
                                 A QGIS plugin
 Este Plugin facilita e cria diversos processos
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                             -------------------
        begin                : 2024-10-09
        copyright            : (C) 2024 by Leonardo Gomes
        email                : leogomes21@gmail.com
        git sha              : $Format:%H$
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
 This script initializes the plugin, making it known to QGIS.
"""


# -*- coding: utf-8 -*-


def classFactory(iface):
    """
    Entrada principal do plugin no QGIS.

    Se faltar dependência externa, retorna um plugin mínimo,
    evitando o erro bruto:
    ModuleNotFoundError: No module named ...
    """
    try:
        from .dependencias import missing_required_modules

        missing = missing_required_modules()

        if missing:
            return MissingDependenciesPlugin(iface, missing)

        from .tempo_salvo_tools import TempoSalvoTools
        return TempoSalvoTools(iface)

    except ModuleNotFoundError as e:
        # Rede de segurança para algum import que tenha escapado da lista.
        missing = [{
            "import_name": str(e.name),
            "pip_name": str(e.name),
            "friendly_name": str(e.name)
        }]
        return MissingDependenciesPlugin(iface, missing)


class MissingDependenciesPlugin:
    """
    Plugin mínimo carregável quando faltam dependências.

    Ele aparece no menu do QGIS e mostra uma mensagem clara
    sobre o que instalar.
    """

    def __init__(self, iface, missing_modules):
        self.iface = iface
        self.missing_modules = missing_modules
        self.action = None

    def initGui(self):
        try:
            from qgis.PyQt.QtGui import QAction
        except Exception:
            from qgis.PyQt.QtWidgets import QAction

        self.action = QAction(
            "Tempo Salvo Tools - dependências ausentes",
            self.iface.mainWindow())
        self.action.triggered.connect(self.show_message)

        try:
            self.iface.addPluginToMenu("&Tempo Salvo Tools", self.action)
        except Exception:
            pass  # nosec B110

        self.show_message()

    def unload(self):
        try:
            if self.action:
                self.iface.removePluginMenu("&Tempo Salvo Tools", self.action)
        except Exception:
            pass  # nosec B110

    def _missing_friendly_text(self):
        names = []

        for m in self.missing_modules:
            name = m.get("friendly_name") or m.get("pip_name") or m.get("import_name")
            if name and name not in names:
                names.append(name)

        return ", ".join(names)

    def _missing_pip_text(self):
        names = []

        for m in self.missing_modules:
            name = m.get("pip_name") or m.get("import_name")
            if name and name not in names:
                names.append(name)

        return " ".join(names)

    def show_message(self):
        import sys

        try:
            from qgis.core import Qgis
            from qgis.PyQt.QtWidgets import QMessageBox
        except Exception:
            return

        missing_txt = self._missing_friendly_text()
        pip_txt = self._missing_pip_text()

        install_cmd = f'"{sys.executable}" -m pip install {pip_txt}'

        msg = (
            "O plugin Tempo Salvo Tools não pôde ser iniciado porque faltam "
            "módulos Python obrigatórios no Python usado pelo QGIS.\n\n"
            f"Módulo(s) ausente(s):\n{missing_txt}\n\n"
            "Para corrigir, instale usando o Python do próprio QGIS:\n\n"
            f"{install_cmd}\n\n"
            "Depois reinicie o QGIS.")

        try:
            self.iface.messageBar().pushMessage(
                "Tempo Salvo Tools",
                f"Dependências ausentes: {missing_txt}",
                level=Qgis.MessageLevel.Critical,
                duration=10)
        except Exception:
            pass  # nosec B110

        QMessageBox.critical(
            self.iface.mainWindow(),
            "Tempo Salvo Tools - dependências ausentes",
            msg)