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

# QDraw: plugin that makes drawing easier
# Author: Jérémy Kalsron
#         jeremy.kalsron@gmail.com
#
# 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 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program.  If not, see <http://www.gnu.org/licenses/>.

# -*- coding: utf-8 -*-
import sys
import traceback
import os

from qgis.core import QgsMessageLog, Qgis

# ==================================================================
# MODE DÉVELOPPEUR : DEBUG = True / MODE PRODUCTION : DEBUG = False
# ==================================================================
DEBUG = True   # <=========== Mettre False pour la version production

# ============================================================
#           REDIRECTION stdout / stderr vers le log
# ============================================================
class LogRedirector:
    def __init__(self, level="INFO"):
        self.level = level

    def write(self, message):
        message = message.strip()
        if not message:
            return

        if self.level == "INFO":
            QgsMessageLog.logMessage(message, "QdrawEVT", Qgis.Info)
        else:
            QgsMessageLog.logMessage(message, "QdrawEVT", Qgis.Critical)

    def flush(self):
        pass


# Redirection totale
sys.stdout = LogRedirector("INFO")
sys.stderr = LogRedirector("ERROR")


# ============================================================
#              EXCEPTION HOOK GLOBAL (DEBUG/PROD)
# ============================================================
def handle_uncaught_exception(exctype, value, tb):
    """
    Mode DEBUG :
        - popup scrollable
        - traceback complet
        - réélève l’erreur
    Mode PROD :
        - message court non intrusif
        - log complet
    """
    # Dernière frame = lieu exact de l’erreur
    last = traceback.extract_tb(tb)[-1]

    filename = os.path.basename(last.filename)
    filepath = last.filename
    line = last.lineno
    function = last.name
    module = os.path.splitext(filename)[0]

    # Traceback complet
    tb_str = ''.join(traceback.format_exception(exctype, value, tb))

    # Message résumé
    header = (
        f"Type d'erreur : {exctype.__name__}\n"
        f"Message       : {value}\n\n"
        f"Module        : {module}\n"
        f"Fichier       : {filepath}\n"
        f"Ligne         : {line}\n"
        f"Fonction      : {function}\n\n"
        f"Traceback complet ci-dessous :\n"
    )

    # Log complet dans QGIS
    QgsMessageLog.logMessage(header + tb_str, "QdrawEVT", Qgis.Critical)

    # ========================
    # MODE DÉVELOPPEUR
    # ========================
    if DEBUG:
        from qgis.utils import iface

        from qgis.PyQt.QtWidgets import (
            QDialog, QVBoxLayout, QTextEdit, QPushButton, QHBoxLayout
        )

        # --- Popup scrollable ---
        dialog = QDialog(iface.mainWindow())
        dialog.setWindowTitle("Erreur QdrawEVT (mode développeur)")
        dialog.resize(900, 600)

        layout = QVBoxLayout(dialog)
        text = QTextEdit()
        text.setReadOnly(True)
        text.setText(header + tb_str)
        layout.addWidget(text)

        btn_layout = QHBoxLayout()
        close_btn = QPushButton("Fermer")
        btn_layout.addStretch()
        btn_layout.addWidget(close_btn)
        layout.addLayout(btn_layout)
        close_btn.clicked.connect(dialog.close)

        dialog.exec_()

        # On réélève pour voir l’erreur dans la console DEV
        raise exctype(value).with_traceback(tb)

    # ========================
    # MODE PRODUCTION
    # ========================
    else:
        # Petit popup simple pour l'utilisateur
        from qgis.PyQt.QtWidgets import QMessageBox
        QMessageBox.warning(
            None,
            "Erreur dans QdrawEVT",
            f"Une erreur est survenue :\n\n{value}\n\n"
            "Détails disponibles dans le panneau Messages."
        )


# Active le hook global
sys.excepthook = handle_uncaught_exception


# ============================================================
#            IMPORT DE LA CLASSE PRINCIPALE DU PLUGIN
# ============================================================

def classFactory(iface):
    from .qdrawEVT import QdrawEVT
    return QdrawEVT(iface)
