
# Code permettant un calcul en arrière-plan des différentes analyses sans bloquer
# l'affichage de la fenêtre principale

# analyse_worker.py
from qgis.PyQt.QtCore import QObject, pyqtSignal
import time

from .Analyse import (
    calcul_surface_forestiere,
    calcul_surface_friche,
    compter_parcelles_possedees,
    analyse_types_parcelles,
    analyse_types_essences,
    total_plantation,
    calcul_regroupement,
    calcul_parcelles_achat,
    calcul_parcelles_echange

)

class AnalyseWorker(QObject):
    finished = pyqtSignal(dict)

    def __init__(self, features_data):
        super().__init__()
        self.features_data = features_data  # liste de dicts (copie mémoire)


    def run(self):
        print("[DEBUG] AnalyseWorker lancé")
        start = time.time()

        # 🔹 Exécute les calculs sur les données locales, pas la couche QGIS
        surface_forestiere = calcul_surface_forestiere(self.features_data)
        surface_friche = calcul_surface_friche(self.features_data)
        nb_parcelles = compter_parcelles_possedees(self.features_data)
        types_parcelles = analyse_types_parcelles(self.features_data)
        types_essences = analyse_types_essences(self.features_data)
        total_plants = total_plantation(self.features_data)
        surface_achat, liste_achat = calcul_parcelles_achat(self.features_data)
        surface_echange, liste_echange = calcul_parcelles_echange(self.features_data)
        regroupement = calcul_regroupement(self.features_data)

        results = {
            "surface_forestiere": surface_forestiere,
            "surface_friche": surface_friche,
            "nb_parcelles": nb_parcelles,
            "types_parcelles": types_parcelles,
            "types_essences": types_essences,
            "total_plants": total_plants,
            "surface_achat": surface_achat,
            "liste_achat": liste_achat,
            "surface_echange": surface_echange,
            "liste_echange": liste_echange,
            "regroupement": regroupement
        }

        elapsed = time.time() - start
        print(f"[DEBUG] Analyse terminée en {elapsed:.3f}s")
        self.finished.emit(results)
