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

"""
/***************************************************************************
 DeteccionDePalmeras
                                 A QGIS plugin
 Este plug-in permite detectar automáticamente 3 especies de palmeras en imágenes RGB adquiridas con RPAs:aguaje (Mauritia flexuosa), huasai (Euterpe precautoria) y ungurahui (Oenocarpus bataua). 
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2021-10-06
        copyright            : (C) 2021 by Susan Palacios, Rodolfo Cardenas, Ximena Tagle
        email                : spalacios.salcedo@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 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
"""

__author__ = 'Susan Palacios, Rodolfo Cardenas, Ximena Tagle'
__date__ = '2021-10-06'
__copyright__ = '(C) 2021 by Susan Palacios, Rodolfo Cardenas, Ximena Tagle'

# This will get replaced with a git SHA1 when you do a git archive

__revision__ = '$Format:%H$'

from qgis.PyQt.QtCore import QCoreApplication
from qgis.core import (QgsProcessing,
                       QgsFeatureSink,
                       QgsProcessingAlgorithm,
                       QgsProcessingParameterFeatureSource,
                       QgsProcessingParameterFeatureSink,
                       QgsProcessingParameterRasterLayer,
                       QgsProcessingParameterRasterDestination,
                       QgsProcessingOutputVectorLayer,
                       QgsProcessingOutputNumber,
                       QgsProcessingOutputFile)

import os
import inspect
from qgis.PyQt.QtGui import QIcon #icon

cmd_folder = os.path.split(inspect.getfile(inspect.currentframe()))[0]
class DeteccionDePalmerasAlgorithm(QgsProcessingAlgorithm):
    """
    This is an example algorithm that takes a vector layer and
    creates a new identical one.

    It is meant to be used as an example of how to create your own
    algorithms and explain methods and variables used to do it. An
    algorithm like this will be available in all elements, and there
    is not need for additional work.

    All Processing algorithms should extend the QgsProcessingAlgorithm
    class.
    """

    # Constants used to refer to parameters and outputs. They will be
    # used when calling the algorithm from another algorithm, or when
    # calling from the QGIS console.

    #OUTPUT = 'OUTPUT'
    #INPUT = 'INPUT'
    
    INPUT_RASTER = 'INPUT_RASTER'
    OUTPUT_RASTER = 'OUTPUT_RASTER'
    OUTPUT_VECTOR = 'OUTPUT_VECTOR'
    OUTPUT_CENTROIDES = 'OUTPUT_CENTROIDES'
    ATRIBUTOS_CSV = 'ATRIBUTOS_CSV'
    REPORTE_CSV = 'REPORTE_CSV'
    NMAURITIA = 'CANTIDAD_DE_MAURITIA_FLEXUOSA'
    NEUTERPE = 'CANTIDAD_DE_EUTERPE_PRECAUTORIA'
    NOENOCARPUS = 'CANTIDAD_DE_OENOCARPUS_BATAUA'
    AMAURITIA = 'AREA_DE_MAURITIA_FLEXUOSA'
    AEUTERPE = 'AREA_DE_EUTERPE_PRECAUTORIA'
    AOENOCARPUS = 'AREA_DE_OENOCARPUS_BATAUA'

    def initAlgorithm(self, config):
        """
        Here we define the inputs and output of the algorithm, along
        with some other properties.
        """
        #inputs
        self.addParameter(
            QgsProcessingParameterRasterLayer(
                self.INPUT_RASTER,
                self.tr('Input raster')
            )
        )


        # output
        self.addParameter(
            QgsProcessingParameterRasterDestination(
                self.OUTPUT_RASTER,
                self.tr('Output raster'),
                optional=False
            )
        )

        self.addOutput(
            QgsProcessingOutputVectorLayer(
                self.OUTPUT_VECTOR,
                self.tr('Output vector'),
                type = QgsProcessing.TypeVectorAnyGeometry
            )
        )

        self.addOutput(
            QgsProcessingOutputVectorLayer(
                self.OUTPUT_CENTROIDES,
                self.tr('Output centroides'),
                type = QgsProcessing.TypeVectorAnyGeometry
            )
        )

        self.addOutput(
            QgsProcessingOutputFile(
                self.ATRIBUTOS_CSV,
                self.tr('Tabla de Atributos')
            )
        )

        self.addOutput(
            QgsProcessingOutputFile(
                self.REPORTE_CSV,
                self.tr('Reporte')
            )
        )

        self.addOutput(
            QgsProcessingOutputNumber(
                'NMAURITIA',
                self.tr('Cantidad de Mauritia')
            )
        )

        self.addOutput(
            QgsProcessingOutputNumber(
                'NEUTERPE',
                self.tr('Cantidad de Euterpe')
            )
        )
        self.addOutput(
            QgsProcessingOutputNumber(
                'NOENOCARPUS',
                self.tr('Cantidad de Oenocarpus')
            )
        )
        self.addOutput(
            QgsProcessingOutputNumber(
                'AMAURITIA',
                self.tr('Area de Mauritia')
            )
        )
        self.addOutput(
            QgsProcessingOutputNumber(
                'AEUTERPE',
                self.tr('Area de Euterpe')
            )
        )
        self.addOutput(
            QgsProcessingOutputNumber(
                'AOENOCARPUS',
                self.tr('Area de Oenocarpus')
            )
        )

        # We add the input vector features source. It can have any kind of
        # geometry.
        """self.addParameter(
            QgsProcessingParameterFeatureSource(
                self.INPUT,
                self.tr('Input layer'),
                [QgsProcessing.TypeVectorAnyGeometry]
            )
        )"""

        # We add a feature sink in which to store our processed features (this
        # usually takes the form of a newly created vector layer when the
        # algorithm is run in QGIS).
        """self.addParameter(
            QgsProcessingParameterFeatureSink(
                self.OUTPUT,
                self.tr('Output layer')
            )
        )"""

    def processAlgorithm(self, parameters, context, feedback):
        """
        Here is where the processing itself takes place.
        Dependencies were already checked in initAlgorithm.
        """
        from .palmerasqgis_algo import palmeras_qgis_count
        from .palmerasqgis_algo import palmeras_qgis_clas
        # Return the results of the algorithm. In this case our only result is
        # the feature sink which contains the processed features, but some
        # algorithms may return multiple feature sinks, calculated numeric
        # statistics, etc. These should all be included in the returned
        # dictionary, with keys matching the feature corresponding parameter
        # or output names.
        


        INPUT_RASTER = self.parameterAsRasterLayer(
            parameters, self.INPUT_RASTER, context)

        
        OUTPUT_RASTER = self.parameterAsOutputLayer(
            parameters, self.OUTPUT_RASTER, context)

        OUTPUT_VECTOR = self.parameterAsOutputLayer(
            parameters, self.OUTPUT_VECTOR, context)

        OUTPUT_CENTROIDES = self.parameterAsOutputLayer(
            parameters, self.OUTPUT_CENTROIDES, context)

        ATRIBUTOS_CSV = self.parameterAsFileOutput(
            parameters, self.ATRIBUTOS_CSV, context)

        REPORTE_CSV = self.parameterAsFileOutput(
            parameters, self.REPORTE_CSV, context)

        if feedback.isCanceled():
            return {}
        
        # Ejecutar apply_palmeras dentro del venv aislado mediante QProcess
        from ._env_core import EnvCore
        from qgis.PyQt.QtCore import QProcess, QProcessEnvironment

        _env = EnvCore(plugin_name="deteccion_de_palmeras_env")
        if not _env.venv_exists():
            raise RuntimeError("El entorno aislado no está preparado. Abre 'Dependencias' y créalo primero.")

        # --- Preparar script a ejecutar en el venv ---
        import tempfile, json

        # Normaliza rutas en el lado QGIS (evitar backslashes en f-strings)
        _plugin_dir = os.path.dirname(__file__)
        _plugin_dir_norm = _plugin_dir.replace("\\", "/")
        _in_raster = INPUT_RASTER.source()
        _out_raster = OUTPUT_RASTER

        script_prolog = _env.dll_snippet() + "; import sys, os, json\n"

        # Intento robusto: primero paquete 'palmeras_algo', luego módulo suelto 'palmeras_deteccion'
        script_body = (
            "import sys, json, importlib\n"
            f"sys.path.insert(0, r'{_plugin_dir_norm}')\n"
            "try:\n"
            "    from palmeras_algo import palmeras_deteccion as _mod\n"
            "except Exception:\n"
            "    try:\n"
            "        _mod = importlib.import_module('palmeras_deteccion')\n"
            "    except Exception as e:\n"
            "        import traceback; traceback.print_exc()\n"
            "        raise\n"
            f"_out_raster, _out_raster_clas, _mau, _eut, _oeno = _mod.apply_palmeras(r'{_in_raster}', r'{_out_raster}')\n"
            "print(json.dumps({'out': [_out_raster, _out_raster_clas], 'counts': [_mau, _eut, _oeno]}))\n"
        )

        _script = tempfile.NamedTemporaryFile("w", suffix=".py", delete=False, encoding="utf-8")
        _script.write(script_prolog + script_body)
        _script.close()

        # --- Ejecutar proceso en el venv ---
        _proc = QProcess()
        _envvars = _env.build_env()
        _qenv = QProcessEnvironment.systemEnvironment()
        for k, v in _envvars.items():
            _qenv.insert(k, v)

        # Refuerza PYTHONPATH con la carpeta del plugin (donde viven palmeras_algo/ o palmeras_deteccion.py)
        _qenv.insert("PYTHONPATH", _plugin_dir)
        _proc.setProcessEnvironment(_qenv)
        _proc.setProcessChannelMode(QProcess.MergedChannels)

        _buf = []
        _proc.readyReadStandardOutput.connect(lambda: _buf.append(_proc.readAllStandardOutput().data().decode("utf-8", "replace")))
        _proc.start(_env.venv_python, [_script.name])
        _proc.waitForFinished(-1)
        _rc = _proc.exitCode()

        try:
            os.unlink(_script.name)
        except Exception:
            pass

        if _rc != 0:
            raise RuntimeError("Fallo ejecutando apply_palmeras en el entorno aislado:\n" + "".join(_buf))

        # --- Leer salida JSON ---
        _stdout = "".join(_buf).strip().splitlines()
        _last = _stdout[-1] if _stdout else "{}"
        try:
            _j = json.loads(_last)
            OUTPUT_RASTER, OUTPUT_RASTER_CLAS = _j["out"]
            mau, eut, oeno = _j["counts"]
        except Exception as _e:
            raise RuntimeError("No se pudo interpretar la salida del proceso aislado: " + str(_e))
        ##Fin Ejecutar

        
        if feedback.isCanceled():
            return {}
        c1, c2, c3, OUTPUT_VECTOR, OUTPUT_CENTROIDES,ATRIBUTOS_CSV = palmeras_qgis_count.apply_toolsqgis(OUTPUT_RASTER,OUTPUT_RASTER_CLAS,mau,eut,oeno)
        if feedback.isCanceled():
            return {}
        
        ca1, ca2, ca3,REPORTE_CSV = palmeras_qgis_clas.apply_toolsqgis(OUTPUT_RASTER,OUTPUT_RASTER_CLAS,mau,eut,oeno)
        if feedback.isCanceled():
            return {}
        
        # MOSTRAR RESULTADOS EN EL LOG
        feedback.pushInfo("═" * 50)
        feedback.pushInfo("RESULTADOS DE DETECCIÓN DE PALMERAS")
        feedback.pushInfo("═" * 50)
        feedback.pushInfo(f"Mauritia flexuosa: {c1} individuos, Área: {ca1:.2f} ha")
        feedback.pushInfo(f"Euterpe precautoria: {c2} individuos, Área: {ca2:.2f} ha") 
        feedback.pushInfo(f"Oenocarpus bataua: {c3} individuos, Área: {ca3:.2f} ha")
        feedback.pushInfo("═" * 50)
        feedback.pushInfo(f"TOTAL DETECTADO: {c1 + c2 + c3} palmeras")
        feedback.pushInfo("═" * 50)

        return {self.OUTPUT_RASTER: OUTPUT_RASTER,
                self.NMAURITIA: c1,
                self.AMAURITIA: ca1,
                self.NEUTERPE: c2,
                self.AEUTERPE: ca2,
                self.NOENOCARPUS: c3,
                self.AOENOCARPUS: ca3,
                self.OUTPUT_VECTOR: OUTPUT_VECTOR, 
                self.OUTPUT_CENTROIDES:OUTPUT_CENTROIDES,
                self.ATRIBUTOS_CSV:ATRIBUTOS_CSV,
                self.REPORTE_CSV:REPORTE_CSV}
        """return {self.OUTPUT: dest_id}"""


    def name(self):
        """
        Returns the algorithm name, used for identifying the algorithm. This
        string should be fixed for the algorithm, and must not be localised.
        The name should be unique within each provider. Names should contain
        lowercase alphanumeric characters only and no spaces or other
        formatting characters.
        """
        return 'Detección de Palmeras'

    def displayName(self):
        """
        Returns the translated algorithm name, which should be used for any
        user-visible display of the algorithm name.
        """
        return self.tr(self.name())

    def group(self):
        """
        Returns the name of the group this algorithm belongs to. This string
        should be localised.
        """
        return self.tr(self.groupId())

    def groupId(self):
        """
        Returns the unique ID of the group this algorithm belongs to. This
        string should be fixed for the algorithm, and must not be localised.
        The group id should be unique within each provider. Group id should
        contain lowercase alphanumeric characters only and no spaces or other
        formatting characters.
        """
        return ''

    def tr(self, string):
        return QCoreApplication.translate('Processing', string)

    def icon(self):#icon
        cmd_folder = os.path.split(inspect.getfile(inspect.currentframe()))[0]#icon
        icon = QIcon(os.path.join(os.path.join(cmd_folder, 'logo.png')))#icon
        return icon#icon

    def createInstance(self):
        return DeteccionDePalmerasAlgorithm()