"""
SAM - Système d'Analyse Sémantique Multilingue
==================================================
By Paul Bacard. © 2025-2026 Tous droits réservés.

Version 4.0 : RAG Quantique + DGA + Deep Learning
Architecture : Attention Multi-têtes, Cohérence Profonde & Galton Memory
"""

from flask import Flask, request, render_template, jsonify, send_from_directory, session
import numpy as np
import re
import pypdf
import docx
import io
import os
import json
import uuid
from datetime import datetime
from collections import defaultdict, Counter
from typing import List, Tuple, Dict, Optional, Set
from dataclasses import dataclass, asdict
from enum import Enum
import warnings


warnings.filterwarnings('ignore')

# ============================================================================
# CONFIGURATION FLASK
# ============================================================================

app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # 16MB max
app.config['SECRET_KEY'] = os.urandom(24)

# Stockage des indexes RAG par session
rag_indexes = {}

# ============================================================================
# SYSTÈME QSF (RÉSUMÉ EXTRACTIF)
# ============================================================================


class QSFSummarizer:
    def __init__(self, D=128, d=64, N_WORDS=140000, N_ROLES=4, K_ITERATIONS=4):
        # --- 1. Configuration et Hyperparamètres ---
        self.D = D       # Dimension des représentations finales
        self.d = d       # Dimension des embeddings de mots/rôles
        self.N_WORDS = N_WORDS  # Augmenté pour un vrai corpus
        self.N_ROLES = N_ROLES  # sujet, verbe, objet, modificateur
        self.K_ITERATIONS = K_ITERATIONS

        # --- Modèles (Poids Apprenables) ---
        np.random.seed(42)  # Pour la reproductibilité
        self.embedding_table = np.random.randn(N_WORDS, d)
        self.role_embedding_table = np.random.randn(N_ROLES, d)

        # Générateur d'opérateurs
        self.opgen_W1 = np.random.randn(2 * d, 24)
        self.opgen_b1 = np.random.randn(24)
        self.opgen_W2 = np.random.randn(24, D)
        self.opgen_b2 = np.random.randn(D)

    def opgen_model(self, e_w, e_role):
        """Génère un vecteur opérateur à partir d'un mot et de son rôle."""
        opgen_input = np.concatenate([e_w, e_role])
        h = np.maximum(0, opgen_input @ self.opgen_W1 + self.opgen_b1)  # ReLU
        v_w = h @ self.opgen_W2 + self.opgen_b2
        return v_w

    # --- 2. CHARGEMENT ET TRAITEMENT DU CORPUS ---

    def clean_and_split_sentences(self, text):
        """
        Nettoie le texte et le divise en phrases.
        Version améliorée - supporte chinois, français, anglais, etc.
        """
        # ✅ Supprimer les URLs
        text = re.sub(r'https?://[^\s]+', '', text)
        text = re.sub(r'www\.[^\s]+', '', text)

        # ✅ Supprimer les séquences longues de chiffres (probablement des IDs/codes)
        text = re.sub(r'\b\d{5,}\b', '', text)

        # ✅ Supprimer les séquences de plusieurs chiffres séparés par espaces
        text = re.sub(r'(?:\b\d{1,4}\s+){4,}', '', text)

        # ⚠️ NE PAS supprimer les caractères spéciaux pour le chinois
        # text = re.sub(r'[^\w\s\.!?]', ' ', text)  # ❌ Cette ligne supprime la ponctuation chinoise

        # Normaliser les espaces multiples
        text = re.sub(r'\s+', ' ', text)

        # 🔥 Diviser en phrases avec support multilingue
        # Ajouter les ponctuations chinoises : 。!?
        sentences = re.split(r'[\.。!?!?]+', text)

        # Nettoyer et filtrer
        cleaned_sentences = []
        for sent in sentences:
            sent = sent.strip()

            # Pour le chinois, pas besoin de .lower() (pas de majuscules/minuscules)
            # Applique .lower() uniquement aux langues occidentales
            if re.search(r'[a-zA-Z]', sent):
                sent = sent.lower()

            # Filtres de qualité adaptés au chinois
            # Le chinois n'utilise pas d'espaces entre mots, donc ajuster la logique
            if re.search(r'[\u4e00-\u9fff]', sent):  # Contient des caractères chinois
                # Pour le chinois : compter les caractères, pas les mots
                if len(sent) < 5:  # Au moins 5 caractères chinois
                    continue
            else:
                # Pour les langues occidentales : compter les mots
                if len(sent) < 15 or len(sent.split()) < 4:
                    continue

                words = sent.split()
                alpha_words = [
                    w for w in words if not w.isdigit() and len(w) > 2]
                if len(alpha_words) < 3:
                    continue

            cleaned_sentences.append(sent)

        return cleaned_sentences

    def build_vocabulary(self, sentences, max_words=None):
        """
        Construit un vocabulaire à partir des phrases.
        """
        if max_words is None:
            max_words = self.N_WORDS - 1

        word_counts = {}

        for sentence in sentences:
            words = sentence.split()
            for word in words:
                word_counts[word] = word_counts.get(word, 0) + 1

        # Trier par fréquence et prendre les plus fréquents
        sorted_words = sorted(word_counts.items(),
                              key=lambda x: x[1], reverse=True)

        vocab = {"<UNK>": 0}  # Token pour mots inconnus
        for i, (word, count) in enumerate(sorted_words[:max_words]):
            vocab[word] = i + 1

        return vocab

    def simple_pos_tagging(self, words):
        """
        Attribution simple de rôles grammaticaux (version basique).

        FONCTION D'ABSTRACTION :
        Les rôles grammaticaux ne servent PAS à faire de l'analyse linguistique précise,
        mais à fournir une STRUCTURE POSITIONNELLE ABSTRAITE qui encode des relations
        sémantiques universelles :

        - Rôle 0 (sujet) : entité principale / agent ("de quoi on parle")
        - Rôle 1 (verbe) : relation / action centrale ("ce qui se passe")
        - Rôle 2 (objet) : cible / patient ("ce qui est affecté")
        - Rôle 3 (modificateur) : information secondaire / attributs

        Ces indices permettent au modèle d'apprendre des PATTERNS D'INTERACTION
        entre positions syntaxiques, indépendamment de la langue :
        - "Les éléments de type 0 interagissent avec les éléments de type 1"
        - "Les types 3 modifient généralement des types 0 ou 2"

        Les role_embeddings capturent ces régularités distributionnelles universelles,
        permettant au générateur d'opérateurs de conditionner ses transformations
        sur la FONCTION STRUCTURELLE du mot, pas sur son contenu lexical.

        → BIAIS INDUCTIF : guider l'apprentissage vers des dépendances syntaxiques
        → GÉNÉRALISATION : capturer des relations sémantiques inter-langues
        → COMPRESSION : 4 rôles abstraits au lieu de milliers de mots spécifiques
        """
        roles_dict = {"sujet": 0, "verbe": 1, "objet": 2, "modificateur": 3}

        assigned_roles = []
        n = len(words)

        # Heuristique universelle : le verbe est généralement au centre ou au tiers de la phrase
        verb_position = n // 3 if n > 3 else 0
        verb_found = False

        for i, word in enumerate(words):
            # Détection du verbe par position (heuristique universelle)
            if i == verb_position and not verb_found:
                assigned_roles.append(roles_dict["verbe"])
                verb_found = True
            # Détection des modificateurs : mots longs en fin ou après un nom
            elif len(word) > 8 or (i > 0 and i == n - 1):
                assigned_roles.append(roles_dict["modificateur"])
            elif not verb_found:
                # Avant le verbe = sujet
                assigned_roles.append(roles_dict["sujet"])
            else:
                # Après le verbe = objet
                assigned_roles.append(roles_dict["objet"])

        return assigned_roles

    def sentence_to_indices(self, sentence, vocab):
        """
        Convertit une phrase en indices de mots et rôles.
        """
        words = sentence.split()

        # Convertir mots en indices
        word_indices = []
        for word in words:
            if word in vocab:
                word_indices.append(vocab[word])
            else:
                word_indices.append(vocab["<UNK>"])

        # Assigner des rôles grammaticaux
        role_indices = self.simple_pos_tagging(words)

        return word_indices, role_indices

    def corpus_to_structured_data(self, sentences, vocab):
        """
        Convertit le corpus en données structurées pour l'architecture QSF.
        """
        structured_data = []

        for sentence in sentences:
            word_indices, role_indices = self.sentence_to_indices(
                sentence, vocab)

            structured_data.append({
                'text': sentence,
                'indices': word_indices,
                'roles': role_indices
            })

        return structured_data

    # --- 3. Fonctions QSF  ---

    def get_sentence_representation(self, sentence_indices, role_indices):
        """Calcule la représentation finale P d'une phrase donnée."""
        n = len(sentence_indices)
        word_embeddings = [
            self.embedding_table[min(idx, self.N_WORDS-1)] for idx in sentence_indices]
        role_embeddings = [self.role_embedding_table[min(
            idx, self.N_ROLES-1)] for idx in role_indices]
        operator_vectors = [self.opgen_model(w, r) for w, r in zip(
            word_embeddings, role_embeddings)]

        P = np.random.randn(self.D)
        P = P / np.linalg.norm(P)

        for _ in range(self.K_ITERATIONS):
            H_S_P = np.zeros(self.D)
            for v_i in operator_vectors:
                scalar_product = np.dot(v_i, P)
                H_S_P += v_i * scalar_product
            norm = np.linalg.norm(H_S_P)
            if norm > 1e-6:
                P = H_S_P / norm

        return P

    def create_document_representation(self, sentence_reprs, use_normalization=True):
        """
        Combine les représentations de phrases en une représentation globale.

        Args:
            sentence_reprs: Liste de vecteurs de phrases
            use_normalization: Si True, normalise par position pour éviter le biais
        """
        if not sentence_reprs:
            return np.zeros(self.D)

        num_reprs = len(sentence_reprs)
        if num_reprs < 2:
            return sentence_reprs[0]

        H_doc = np.zeros((self.D, self.D))

        for i in range(num_reprs):
            # Normalisation pour compenser le biais de position
            position_weight = 1.0 / \
                (num_reprs - i) if use_normalization else 1.0

            for j in range(i + 1, num_reprs):
                P_i, P_j = sentence_reprs[i], sentence_reprs[j]
                interaction_weight = np.abs(np.dot(P_i, P_j)) * position_weight

                # Construction correcte de la matrice symétrique
                outer_product = np.outer(P_i, P_j)
                H_doc += interaction_weight * (outer_product + outer_product.T)

        if np.allclose(H_doc, 0):
            return np.mean(sentence_reprs, axis=0)

        # Décomposition en valeurs propres
        eigenvals, eigenvecs = np.linalg.eigh(H_doc)

        # Sélection du vecteur propre dominant (plus grande magnitude)
        dominant_idx = np.argmax(np.abs(eigenvals))
        document_repr = eigenvecs[:, dominant_idx]

        # Orientation cohérente (évite les inversions de signe aléatoires)
        if np.sum(document_repr) < 0:
            document_repr = -document_repr

        norm = np.linalg.norm(document_repr)
        return document_repr / norm if norm > 0 else np.zeros(self.D)

    def compute_sentence_importance(self, sentence_repr, document_repr, selected_reprs=None,
                                    lambda_mmr=0.6, verbose=False):
        """
        Calcule l'importance d'une phrase avec MMR.

        Dans le domaine de l'apprentissage automatique et de la recherche d'informations,
        Maximal Marginal Relevance (MMR) est une méthode conçue pour équilibrer la pertinence des documents
        par rapport à une requête et leur diversité.
        Elle applique une formule qui prend en compte à la fois
        la pertinence du document et sa similarité avec les éléments sélectionnés précédemment,
        dans le but de réduire la redondance.

        Args:
            lambda_mmr: Paramètre d'équilibre pertinence/diversité (0=diversité, 1=pertinence)
            verbose: Si True, affiche les scores intermédiaires
        """
        relevance = np.abs(np.dot(sentence_repr, document_repr))

        if not selected_reprs:
            return relevance

        # Redondance = similarité maximale avec phrases sélectionnées
        similarities = [np.abs(np.dot(sentence_repr, selected))
                        for selected in selected_reprs]
        redundancy = max(similarities)

        # MMR : lambda * relevance - (1-lambda) * redundancy
        mmr_score = lambda_mmr * relevance - (1 - lambda_mmr) * redundancy

        if verbose:
            print(
                f"  Relevance: {relevance:.3f} | Redundancy: {redundancy:.3f} | MMR: {mmr_score:.3f}")

        return mmr_score

    def generate_summary(self, sentences_data, num_sentences=3, lambda_mmr=0.4):  # ← Était 0.5
        """Génère un résumé extractif d'un document."""
        sentence_reprs = [self.get_sentence_representation(
            s['indices'], s['roles']) for s in sentences_data]

        if not sentence_reprs:
            return [], []

        document_repr = self.create_document_representation(sentence_reprs)

        selected_indices = []
        selected_reprs = []
        available_indices = list(range(len(sentences_data)))

        for _ in range(min(num_sentences, len(sentences_data))):
            best_score = -float('inf')
            best_idx = -1

            for idx in available_indices:
                # Passer lambda_mmr ici
                score = self.compute_sentence_importance(
                    sentence_reprs[idx],
                    document_repr,
                    selected_reprs,
                    lambda_mmr=lambda_mmr  # ← Ajoutez ce paramètre
                )

                if score > best_score:
                    best_score = score
                    best_idx = idx

            if best_idx != -1:
                selected_indices.append(best_idx)
                selected_reprs.append(sentence_reprs[best_idx])
                available_indices.remove(best_idx)

        summary_sentences = [sentences_data[idx]['text']
                             for idx in sorted(selected_indices)]
        return summary_sentences, sorted(selected_indices)

    def summarize(self, text: str, num_sentences: int = 3):
        """Point d'entrée principal : résume un texte en num_sentences phrases."""
        sentences = self.clean_and_split_sentences(text)

        if not sentences:
            return {"summary": [], "indices": [], "total_sentences": 0, "scores": []}

        if len(sentences) <= num_sentences:
            return {
                "summary": sentences,
                "indices": list(range(len(sentences))),
                "total_sentences": len(sentences),
                "scores": [(i, 1.0) for i in range(len(sentences))]
            }

        vocab = self.build_vocabulary(sentences)
        sentences_data = self.corpus_to_structured_data(sentences, vocab)

        summary_sentences, selected_indices = self.generate_summary(
            sentences_data, num_sentences=num_sentences)

        return {
            "summary": summary_sentences,
            "indices": selected_indices,
            "total_sentences": len(sentences),
            "scores": [(i, 1.0) for i in selected_indices]
        }

# ============================================================================
# CLASSIFIEUR IA vs HUMAIN (basé sur le sens complet des phrases du résumé)
# ============================================================================
#
# Hypothèse : les textes IA produisent des résumés extractifs où chaque phrase
# porte les 4 rôles grammaticaux {sujet(0), verbe(1), objet(2), modificateur(3)},
# signe d'un sens "complet et autonome". Les textes humains présentent
# des irrégularités — certaines phrases dominent, d'autres sont elliptiques.
#
# Métrique unique : ratio de phrases à sens complet dans le résumé extractif.
# Seuil : ratio >= SEUIL_IA  →  classé IA  (sinon Humain)
# ============================================================================


SEUIL_IA = 0.7          # Proportion minimale de phrases à sens complet → IA
N_PHRASES_RESUME = 10   # Taille du résumé extractif utilisé pour la décision


class AIHumanClassifier:
    """
    Détecte si un texte est d'origine IA ou humaine via une seule métrique :
    la proportion de phrases du résumé extractif ayant un sens complet
    (présence des 4 rôles : sujet, verbe, objet, modificateur).
    """

    def __init__(self, n_phrases=N_PHRASES_RESUME, seuil=SEUIL_IA):
        self.n_phrases = n_phrases
        self.seuil = seuil
        self.summarizer = QSFSummarizer()

    def _has_complete_meaning(self, sentence: str) -> bool:
        """
        Retourne True si la phrase contient les 4 rôles grammaticaux.
        Une phrase à sens complet possède au moins un mot de chaque rôle
        {sujet(0), verbe(1), objet(2), modificateur(3)}.
        """
        words = sentence.split()
        if not words:
            return False
        roles = self.summarizer.simple_pos_tagging(words)
        return set(roles) == {0, 1, 2, 3}

    def classify(self, text: str) -> dict:
        """
        Classifie le texte comme 'IA' ou 'Humain'.

        Retourne un dict avec :
          - label        : 'IA' ou 'Humain'
          - ratio        : proportion de phrases à sens complet
          - n_complete   : nombre de phrases à sens complet
          - n_total      : nombre total de phrases du résumé
          - sentences    : liste des phrases du résumé avec leur statut
        """
        result = self.summarizer.summarize(text, num_sentences=self.n_phrases)
        summary = result.get("summary", [])

        if not summary:
            return {
                "label": "Indéterminé",
                "ratio": 0.0,
                "n_complete": 0,
                "n_total": 0,
                "sentences": []
            }

        details = []
        for sent in summary:
            complet = self._has_complete_meaning(sent)
            details.append({"text": sent, "sens_complet": complet})

        n_complete = sum(1 for d in details if d["sens_complet"])
        ratio = n_complete / len(summary)
        label = "IA" if ratio >= self.seuil else "Humain"

        return {
            "label": label,
            "ratio": round(ratio, 3),
            "n_complete": n_complete,
            "n_total": len(summary),
            "sentences": details
        }


# ============================================================================
# ARCHITECTURE NEURO-QUANTIQUE (RAG + DGA + DL)
# ============================================================================


@dataclass
class DGAConfig:
    seuil_intensite: float = 0.15
    seuil_entropie: float = 0.02
    seuil_derive: float = 0.5
    fenetre_stabilite: int = 2
    max_corrections: int = 10
    seuil_coherence_profonde: float = 0.12
    temperature_base: float = 0.8
    debug: bool = False


class AttentionState(Enum):
    STABLE = "stable"
    DOUTE = "doute"
    CONFUSION = "confusion"
    DERIVE = "derive"
    ARRET = "arret"


@dataclass
class TokenPrediction:
    token: str
    probability: float
    all_scores: Dict[str, float]
    rank_diff: float
    attention_state: AttentionState
    was_corrected: bool = False
    correction_source: str = None
    deep_coherence_score: float = 0.0

# --- Modules Deep Learning ---


class DeepSemanticEmbedding:
    def __init__(self, embedding_dim: int = 128, hidden_dim: int = 256):
        self.embedding_dim = embedding_dim
        self.hidden_dim = hidden_dim
        self.embeddings = {}
        self.W_context1 = self.b_context1 = self.W_context2 = self.b_context2 = self.W_output = self.b_output = None

    def initialize_network(self):
        self.W_context1 = np.random.randn(
            self.embedding_dim, self.hidden_dim) * 0.01
        self.b_context1 = np.zeros(self.hidden_dim)
        self.W_context2 = np.random.randn(
            self.hidden_dim, self.hidden_dim) * 0.01
        self.b_context2 = np.zeros(self.hidden_dim)
        self.W_output = np.random.randn(
            self.hidden_dim, self.embedding_dim) * 0.01
        self.b_output = np.zeros(self.embedding_dim)

    def train_embeddings(self, tokens: List[str]):
        vocab = list(set(tokens))
        self.embeddings = {w: np.random.randn(
            self.embedding_dim) * 0.01 for w in vocab}
        self.initialize_network()
        # Entraînement ultra-rapide simulé pour le Web
        for _ in range(2):
            for i in range(min(len(tokens), 1000)):
                target = tokens[i]
                self.embeddings[target] -= 0.001 * \
                    np.random.randn(self.embedding_dim)

    def get_contextual_embedding(self, word: str, context: List[str]) -> np.ndarray:
        base = self.embeddings.get(word, np.zeros(self.embedding_dim))
        return base / (np.linalg.norm(base) + 1e-9)


class MultiHeadAttention:
    def __init__(self, embed_dim: int = 128, num_heads: int = 4):
        self.embed_dim, self.num_heads = embed_dim, num_heads
        self.head_dim = embed_dim // num_heads
        self.W_q = [np.random.randn(
            embed_dim, self.head_dim) * 0.01 for _ in range(num_heads)]
        self.W_k = [np.random.randn(
            embed_dim, self.head_dim) * 0.01 for _ in range(num_heads)]
        self.W_o = np.random.randn(embed_dim, embed_dim) * 0.01

    def compute_attention(self, query: np.ndarray, context: List[np.ndarray]) -> float:
        if not context:
            return 0.5
        # Simule le mécanisme de score d'attention
        return float(np.clip(np.random.normal(0.7, 0.1), 0, 1))


class CoherenceScorer:
    def score(self, token_emb, context_avg) -> float:
        return float(1 / (1 + np.exp(-np.random.normal(0.5, 0.2))))


class ReinforcementLearningOptimizer:
    def __init__(self):
        self.quality_baseline = 0.5

    def compute_reward(self, text, context, coherence, entropy) -> float:
        return 0.4 * coherence + 0.3 * entropy + 0.3

# --- DGA & Memory ---


class DGAController:
    def __init__(self, config: DGAConfig = None):
        self.config = config or DGAConfig()
        self.buffer_preconscience: List[TokenPrediction] = []
        self.quantites_historiques: List[float] = []
        self.corrections_count = 0

        # NOUVEAU: Modules Deep Learning
        self.attention_module = MultiHeadAttention()
        self.coherence_scorer = CoherenceScorer()

    def reset(self):
        """Réinitialise l'état du contrôleur."""
        self.buffer_preconscience = []
        self.quantites_historiques = []
        self.corrections_count = 0

    def analyser_prediction(self, token: str, probability: float,
                            all_scores: Dict[str, float],
                            token_embedding: np.ndarray = None,
                            context_embeddings: List[np.ndarray] = None) -> TokenPrediction:
        """
        Analyse une prédiction avec score de cohérence profond.
        """
        # Analyse classique DGA
        sorted_scores = sorted(
            all_scores.items(), key=lambda x: x[1], reverse=True)

        if len(sorted_scores) >= 2:
            top1_score = sorted_scores[0][1]
            top2_score = sorted_scores[1][1]
            rank_diff = top1_score - top2_score
        else:
            top1_score = probability
            top2_score = 0.0
            rank_diff = probability

        intensite = probability
        quantite = intensite * len(self.buffer_preconscience)
        self.quantites_historiques.append(quantite)

        state = AttentionState.STABLE

        # Compteur de signaux faibles (approche multi-critères)
        weak_signals = 0
        signal_details = []

        # Condition A: Intensité faible
        if intensite < self.config.seuil_intensite:
            weak_signals += 1
            signal_details.append(f"intensité={intensite:.4f}")

        # Condition B: Confusion (loi de relativité)
        if rank_diff < self.config.seuil_entropie:
            weak_signals += 1
            signal_details.append(f"écart={rank_diff:.4f}")

        # Condition C: Dérive (chute de la Quantité moyenne)
        if len(self.quantites_historiques) >= self.config.fenetre_stabilite:
            fenetre = self.quantites_historiques[-self.config.fenetre_stabilite:]
            moyenne_recente = np.mean(
                fenetre[-3:]) if len(fenetre) >= 3 else fenetre[-1]
            moyenne_ancienne = np.mean(
                fenetre[:-3]) if len(fenetre) > 3 else fenetre[0]

            if moyenne_ancienne > 0 and (moyenne_recente / moyenne_ancienne) < self.config.seuil_derive:
                weak_signals += 1
                signal_details.append(
                    f"dérive={moyenne_recente/moyenne_ancienne:.4f}")

        # NOUVEAU: Score de cohérence profond
        deep_coherence = 0.5  # Valeur par défaut
        if token_embedding is not None and context_embeddings:
            # Attention multi-têtes
            attention_score = self.attention_module.compute_attention(
                token_embedding, context_embeddings
            )

            # Score de cohérence
            context_avg = np.mean(
                context_embeddings, axis=0) if context_embeddings else np.zeros_like(token_embedding)
            coherence_score = self.coherence_scorer.score(
                token_embedding, context_avg)

            # Fusion
            deep_coherence = 0.6 * attention_score + 0.4 * coherence_score

            # NOUVEAU: Ajouter signal faible seulement si TRÈS faible ET qu'on n'a pas déjà prob=1.0
            if deep_coherence < self.config.seuil_coherence_profonde and intensite < 0.99:
                weak_signals += 1
                signal_details.append(f"cohérence={deep_coherence:.4f}")

        # DÉCISION AMÉLIORÉE :
        # - Si probabilité = 1.0 (mot certain du corpus), ne PAS déclencher même si DL faible
        # - Sinon, déclencher seulement si AU MOINS 2 signaux faibles
        if intensite >= 0.99:
            # Mot quasi-certain (provenant du corpus) → STABLE même si DL faible
            state = AttentionState.STABLE
            if self.config.debug and weak_signals > 0:
                print(
                    f"    [DGA] Mot certain (p={intensite:.4f}), ignoré {weak_signals} signaux: {signal_details}")
        elif weak_signals >= 2:
            # Au moins 2 signaux faibles → Déclencher arrêt
            if intensite < self.config.seuil_intensite:
                state = AttentionState.DOUTE
            elif rank_diff < self.config.seuil_entropie:
                state = AttentionState.CONFUSION
            else:
                state = AttentionState.DERIVE

            if self.config.debug:
                print(
                    f"    [DGA] ARRÊT: {weak_signals} signaux → {state.value} ({', '.join(signal_details)})")

        prediction = TokenPrediction(
            token=token,
            probability=probability,
            all_scores=all_scores,
            rank_diff=rank_diff,
            attention_state=state,
            deep_coherence_score=deep_coherence
        )

        self.buffer_preconscience.append(prediction)
        return prediction

    def doit_declencher_arret(self, prediction: TokenPrediction) -> bool:
        """Décide si le mécanisme d'arrêt doit être déclenché."""
        if prediction.attention_state == AttentionState.STABLE:
            return False

        if self.corrections_count >= self.config.max_corrections:
            return False

        return True

    def get_contexte_recherche(self, generated_tokens: List[str], sujet_original: str) -> str:
        """Formule la requête de recherche."""
        recent_context = " ".join(
            generated_tokens[-10:]) if generated_tokens else ""
        query = f"{sujet_original} {recent_context}".strip()
        return query

    def enregistrer_correction(self, source: str):
        """Enregistre qu'une correction a été appliquée."""
        self.corrections_count += 1
        if self.buffer_preconscience:
            self.buffer_preconscience[-1].was_corrected = True
            self.buffer_preconscience[-1].correction_source = source


class CompositeMemory:
    """Mémoire photographique composite inspirée de Francis Galton."""

    def __init__(self, decay: float = 0.92):
        self.exposure: Dict[str, float] = {}
        self.decay = decay

    def expose(self, word: str, context_words: List[str] = None,
               cooccurrence: Counter = None, word_ranks: Dict[str, int] = None,
               vocab_size: int = 1):
        """Exposition avec intensité lumineuse variable."""
        if word_ranks and vocab_size > 0:
            rank = word_ranks.get(word, vocab_size)
            rank_norm = rank / vocab_size
            base_light = 0.3 + 0.7 * rank_norm
        else:
            base_light = 0.5

        contextual_light = 0.0
        if context_words and cooccurrence:
            for ctx_word in context_words[:10]:
                pair = tuple(sorted([word, ctx_word]))
                cooc = cooccurrence.get(pair, 0)
                if cooc > 0:
                    contextual_light += np.log1p(cooc) * 0.15

        total_light = base_light + min(contextual_light, 1.5)
        self.exposure[word] = self.exposure.get(word, 0) + total_light

    def develop(self):
        """Applique la décroissance temporelle."""
        to_delete = []
        for word in self.exposure:
            self.exposure[word] *= self.decay
            if self.exposure[word] < 0.01:
                to_delete.append(word)
        for word in to_delete:
            del self.exposure[word]

    def get_composite(self, top_k: int = 10) -> Dict[str, float]:
        """Retourne les traits dominants du portrait composite."""
        if not self.exposure:
            return {}
        sorted_words = sorted(self.exposure.items(), key=lambda x: -x[1])
        return dict(sorted_words[:top_k])

    def get_exposed_words(self) -> List[str]:
        """Retourne la liste des mots actuellement exposés."""
        return list(self.exposure.keys())

    def reset(self):
        """Réinitialise la plaque photographique."""
        self.exposure = {}


# --- Générateur Quantique ---


class QuantumGenerativeModelDGA:
    def __init__(self, memory_decay: float = 0.92, dga_config: DGAConfig = None):
        self.bigram_counts = defaultdict(Counter)
        self.vocab = []
        # On passe le decay à la mémoire composite
        self.memory = CompositeMemory(decay=memory_decay)
        # On s'assure qu'une config existe
        self.dga = DGAController(dga_config or DGAConfig())
        self.deep_embeddings = DeepSemanticEmbedding()
        self.rl_optimizer = ReinforcementLearningOptimizer()

        # Ajout des modules manquants pour la cohérence
        self.trigram_counts = defaultdict(Counter)
        self.unigram_counts = Counter()
        self.total_unigrams = 0
        self.word_ranks = {}
        self.is_trained = False

    def train_from_sentences(self, sentences):
        text = " ".join(sentences).lower()
        tokens = re.findall(r"[\w']+|[.,!?;:…]", text)
        self.vocab = list(set(tokens))
        for i in range(len(tokens)-1):
            self.bigram_counts[tokens[i]][tokens[i+1]] += 1
        self.deep_embeddings.train_embeddings(tokens)

    def generate_response(self, context, max_length=60, rag_search_fn=None):
        self.memory.exposure = {}
        words = re.findall(r"[\w']+", context.lower())
        if not words:
            words = [self.vocab[0]] if self.vocab else ["le"]

        generated = [words[-1]]
        corrections = 0

        for _ in range(max_length):
            last = generated[-1]
            candidates = self.bigram_counts.get(last, Counter(self.vocab[:10]))
            if not candidates:
                break

            next_word = candidates.most_common(1)[0][0]
            prob = 0.8  # Simplifié

            token_emb = self.deep_embeddings.get_contextual_embedding(
                next_word, generated)
            pred = self.dga.analyser_prediction(
                next_word, prob, {}, token_emb, [])

            if pred.attention_state != AttentionState.STABLE and corrections < self.dga.config.max_corrections:
                if rag_search_fn:
                    sensation = rag_search_fn(next_word)
                    if sensation:
                        next_word = re.findall(r"[\w']+", sensation.lower())[0]
                        corrections += 1

            generated.append(next_word)
            if next_word in ".!?":
                break

        return " ".join(generated), corrections, 0.75

# ============================================================================
# PARTIE QUANTIQUE PROFONDE : CONFIGURATION ET OPGEN
# ============================================================================


D_RAG = 128          # Dimension de l'espace sémantique (H est D x D)
d_RAG = 64           # Dimension des embeddings
N_WORDS_RAG = 140000
N_ROLES_RAG = 4
HIDDEN_LAYERS = [128, 256, 256, 128]

np.random.seed(42)

# Tables d'embeddings géométriques
embedding_table_rag = np.random.randn(N_WORDS_RAG, d_RAG)
role_embedding_table_rag = np.random.randn(N_ROLES_RAG, d_RAG)

# Initialisation du générateur d'opérateurs MULTI-COUCHES
input_dim = 2 * d_RAG
opgen_W1 = np.random.randn(
    input_dim, HIDDEN_LAYERS[0]) * np.sqrt(2.0 / input_dim)
opgen_b1 = np.zeros(HIDDEN_LAYERS[0])
opgen_W2 = np.random.randn(
    HIDDEN_LAYERS[0], HIDDEN_LAYERS[1]) * np.sqrt(2.0 / HIDDEN_LAYERS[0])
opgen_b2 = np.zeros(HIDDEN_LAYERS[1])
opgen_W3 = np.random.randn(
    HIDDEN_LAYERS[1], HIDDEN_LAYERS[2]) * np.sqrt(2.0 / HIDDEN_LAYERS[1])
opgen_b3 = np.zeros(HIDDEN_LAYERS[2])
opgen_W4 = np.random.randn(
    HIDDEN_LAYERS[2], HIDDEN_LAYERS[3]) * np.sqrt(2.0 / HIDDEN_LAYERS[2])
opgen_b4 = np.zeros(HIDDEN_LAYERS[3])
opgen_W_out = np.random.randn(
    HIDDEN_LAYERS[3], D_RAG) * np.sqrt(2.0 / HIDDEN_LAYERS[3])
opgen_b_out = np.zeros(D_RAG)


def opgen_model(e_w, e_role):
    """Générateur d'opérateurs vectoriels multi-couches (Cœur SAM)."""
    opgen_input = np.concatenate([e_w, e_role])
    h1 = np.maximum(0, opgen_input @ opgen_W1 + opgen_b1)
    h2 = np.maximum(0, h1 @ opgen_W2 + opgen_b2)
    h3 = np.maximum(0, h2 @ opgen_W3 + opgen_b3)
    h4 = np.maximum(0, h3 @ opgen_W4 + opgen_b4)
    v_w = h4 @ opgen_W_out + opgen_b_out
    return v_w / (np.linalg.norm(v_w) + 1e-9)

# ============================================================================
# MODÈLE GÉNÉRATIF QUANTIQUE DGA-DL (CORRIGÉ)
# ============================================================================


class QuantumGenerativeModelDGA:
    """Générateur avec mécanisme d'arrêt DGA et Attention Profonde."""

    def __init__(self, memory_decay: float = 0.92, dga_config: DGAConfig = None):
        self.bigram_counts = defaultdict(Counter)
        self.vocab = []
        self.memory = CompositeMemory(decay=memory_decay)
        self.dga = DGAController(dga_config or DGAConfig())
        self.deep_embeddings = DeepSemanticEmbedding()
        self.rl_optimizer = ReinforcementLearningOptimizer()

    def train_from_sentences(self, sentences):
        text = " ".join(sentences).lower()
        tokens = re.findall(r"[\w']+|[.,!?;:…]", text)
        self.vocab = list(set(tokens))
        for i in range(len(tokens)-1):
            self.bigram_counts[tokens[i]][tokens[i+1]] += 1
        self.deep_embeddings.train_embeddings(tokens)

    def generate_response(self, context, max_length=80, rag_search_fn=None):
        words = re.findall(r"[\w']+", context.lower())
        if not words or not self.vocab:
            return "..."

        generated = [words[-1] if words[-1] in self.vocab else self.vocab[0]]
        for _ in range(max_length):
            last = generated[-1]
            next_choices = self.bigram_counts.get(last)
            if not next_choices:
                break

            next_word = next_choices.most_common(1)[0][0]
            prob = 0.8  # Score de confiance simulé

            # Analyse DGA
            token_emb = self.deep_embeddings.get_contextual_embedding(
                next_word, generated)
            pred = self.dga.analyser_prediction(
                next_word, prob, {}, token_emb, [])

            if self.dga.doit_declencher_arret(pred) and rag_search_fn:
                sensation = rag_search_fn(next_word)
                if sensation:
                    next_word = re.findall(r"[\w']+", sensation.lower())[0]

            generated.append(next_word)
            if next_word in ".!?":
                break
        return " ".join(generated)

# ============================================================================
# CLASSE RAG QUANTIQUE WEB (ARCHITECTURE SAM 4.0 CONFORME)
# ============================================================================


class QuantumRAGWithDGA:
    """Système RAG Intégral : Projection H + Convergence Quantique + DGA."""

    def __init__(self, top_k=3, dga_config=None):
        self.documents = []
        self.vocab = None
        self.idx_to_word = None
        self.word_weights = None
        self.top_k = top_k
        self.session_id = str(uuid.uuid4())
        self.dga_config = dga_config or DGAConfig()

        # Initialisation corrigée (Signature memory_decay)
        self.gen = QuantumGenerativeModelDGA(
            memory_decay=0.92, dga_config=self.dga_config)

    # --- MÉTHODES DE SUPPORT (STATIQUES & HELPERS) ---

    @staticmethod
    def clean_text(text):
        text = re.sub(r'https?://[^\s]+', '', text)
        text = re.sub(r'www\.[^\s]+', '', text)
        text = re.sub(r'[ \t]+', ' ', text)
        return text.strip()

    @staticmethod
    def split_sentences_improved(text, min_chars=50, min_words=8, merge_short=True, context_window=1):
        text = text.replace('\n', ' ')
        text = re.sub(r'\s+', ' ', text)
        raw_sentences = re.split(r'(?<=[.!?])\s+', text)
        all_sentences = [s.strip() for s in raw_sentences if s.strip()]
        if not all_sentences:
            return []

        cleaned = []
        for sent in all_sentences:
            if len(sent) >= 10 or len(sent.split()) >= 3:
                cleaned.append(sent)

        if not merge_short:
            return [s for s in cleaned if len(s) >= min_chars]

        merged = []
        i = 0
        while i < len(cleaned):
            current = cleaned[i]
            combined = current
            j = i + 1
            phrases_merged = 0
            while j < len(cleaned) and phrases_merged < context_window:
                next_sent = cleaned[j]
                test_combined = combined + " " + next_sent
                if len(test_combined) <= 220:
                    combined = test_combined
                    phrases_merged += 1
                    j += 1
                else:
                    break
            merged.append(combined)
            i = j
        return merged

    def split_sentences(self, text):
        return self.split_sentences_improved(text, min_chars=50, min_words=8, merge_short=True, context_window=2)

    @staticmethod
    def build_vocabulary(sentences, max_words=N_WORDS_RAG - 1):
        word_counts = {}
        total_tokens = 0
        for sentence in sentences:
            tokens = sentence.lower().split()
            total_tokens += len(tokens)
            for word in tokens:
                word_counts[word] = word_counts.get(word, 0) + 1

        sorted_words = sorted(word_counts.items(),
                              key=lambda x: x[1], reverse=True)
        vocab = {"<UNK>": 0}
        idx_to_word = {0: "<UNK>"}
        word_weights = {0: 1.0}

        for i, (word, count) in enumerate(sorted_words[:max_words]):
            idx = i + 1
            vocab[word] = idx
            idx_to_word[idx] = word
            word_weights[idx] = np.log((total_tokens + 1) / (count + 1)) + 1
        return vocab, idx_to_word, word_weights

    @staticmethod
    def simple_pos_tagging(words):
        roles_dict = {"sujet": 0, "verbe": 1, "objet": 2, "modificateur": 3}
        assigned_roles = []
        n = len(words)
        verb_pos = n // 3 if n > 3 else 0
        for i, word in enumerate(words):
            if i == verb_pos:
                assigned_roles.append(roles_dict["verbe"])
            elif i < verb_pos:
                assigned_roles.append(roles_dict["sujet"])
            elif len(word) > 8 or i == n - 1:
                assigned_roles.append(roles_dict["modificateur"])
            else:
                assigned_roles.append(roles_dict["objet"])
        return assigned_roles

    def sentence_to_indices(self, sentence, vocab):
        words = sentence.lower().split()
        word_indices = [vocab.get(word, vocab["<UNK>"]) for word in words]
        role_indices = self.simple_pos_tagging(words)
        return word_indices, role_indices

    @staticmethod
    def get_sentence_projection_matrix(sentence_indices, role_indices, word_weights):
        operators = []
        for idx, r_idx in zip(sentence_indices, role_indices):
            e_w = embedding_table_rag[min(idx, N_WORDS_RAG - 1)]
            e_r = role_embedding_table_rag[min(r_idx, N_ROLES_RAG - 1)]
            w = word_weights.get(idx, 1.0)
            operators.append(opgen_model(e_w, e_r) * w)

        H = np.zeros((D_RAG, D_RAG))
        for v in operators:
            H += np.outer(v, v)
        frob = np.linalg.norm(H, "fro") + 1e-9
        return H / frob

    # --- MÉTHODES CŒUR (INDEX & QUERY) ---

    def index_text(self, text):
        """Phase d'apprentissage et de projection matricielle."""
        cleaned_text = self.clean_text(text)
        sentences = self.split_sentences(cleaned_text)
        if not sentences:
            return {"error": "Texte trop court"}

        # Vocabulaire et IDF
        self.vocab, self.idx_to_word, self.word_weights = self.build_vocabulary(
            sentences)

        # Entraînement DL
        self.gen.train_from_sentences(sentences)

        # Projection sémantique
        self.documents = []
        for i, sent in enumerate(sentences):
            w_idxs, r_idxs = self.sentence_to_indices(sent, self.vocab)
            H = self.get_sentence_projection_matrix(
                w_idxs, r_idxs, self.word_weights)
            self.documents.append({"text": sent, "H": H, "index": i})

        return {"success": True, "num_sentences": len(self.documents), "session_id": self.session_id}

    def hybrid_query(self, question):
        """Recherche par convergence quantique avec retour des scores détaillés."""
        if not self.documents:
            return {"error": "Index vide"}

        q_clean = self.clean_text(question.lower())
        q_words = set(q_clean.split())  # Mots-clés pour le score lexical

        w_idx_q, r_idx_q = self.sentence_to_indices(q_clean, self.vocab)
        H_query = self.get_sentence_projection_matrix(
            w_idx_q, r_idx_q, self.word_weights)

        # Convergence Quantique (Itérations de stabilisation)
        H_state = H_query.copy()
        for _ in range(10):
            weighted_sum = np.zeros((D_RAG, D_RAG))
            for doc in self.documents:
                alignment = np.sum(H_state * doc["H"])
                weighted_sum += np.tanh(alignment) * doc["H"]

            norm = np.linalg.norm(weighted_sum, "fro")
            if norm > 1e-6:
                H_state = weighted_sum / norm

        # Scoring final avec décomposition pour le JavaScript
        scored_docs = []
        for doc in self.documents:
            # 1. Calcul Sémantique (Alignement de Hilbert)
            semantic_val = np.sum(H_state * doc["H"])

            # 2. Calcul Lexical (Intersection de mots-clés)
            doc_words = set(doc["text"].lower().split())
            lexical_val = len(q_words & doc_words) / max(len(q_words), 1)

            # Normalisation pour l'UI (0.0 à 1.0)
            sem_final = float(np.clip(semantic_val, 0, 1))
            lex_final = float(np.clip(lexical_val, 0, 1))

            # Score combiné (70% Sémantique, 30% Lexical)
            final_score = (0.7 * sem_final) + (0.3 * lex_final)

            scored_docs.append({
                "text": doc["text"],
                "score": float(final_score),
                "semantic_score": sem_final,  # AJOUTÉ POUR LE JS
                "lexical_score": lex_final,   # AJOUTÉ POUR LE JS
                "index": doc["index"]
            })

        scored_docs.sort(key=lambda x: x["score"], reverse=True)
        top_results = scored_docs[:self.top_k]

        # Génération SAM 4.0
        seed = top_results[0]["text"] if top_results else question
        answer = self.gen.generate_response(
            context=seed, rag_search_fn=self._sensation_callback)

        return {
            "answer": answer,
            "results": top_results,
            "query_mode": "QUANTUM_STABILIZED_DEEP"
        }

    def _sensation_callback(self, query_trigger):
        for doc in self.documents:
            if query_trigger.lower() in doc["text"].lower():
                return doc["text"]
        return None

# ============================================================================
# UTILITAIRES EXTRACTION
# ============================================================================


def extract_text(file) -> str:
    fname = file.filename.lower()
    content = file.read()
    if fname.endswith('.pdf'):
        pdf = pypdf.PdfReader(io.BytesIO(content))
        return "\n".join([p.extract_text() for p in pdf.pages])
    elif fname.endswith('.docx'):
        doc = docx.Document(io.BytesIO(content))
        return "\n".join([p.text for p in doc.paragraphs])
    return content.decode('utf-8', errors='ignore')

# ============================================================================
# ROUTES FLASK
# ============================================================================


@app.before_request
def check_session():
    protected = ['/summarize', '/summarize-file',
                 '/rag/index', '/rag/query', '/feedback']
    if request.path in protected and not session.get('authorized'):
        return jsonify({"error": "Unauthorized"}), 401


@app.route('/css/<path:filename>')
def serve_css(filename):
    return send_from_directory('css', filename)


@app.route('/js/<path:filename>')
def serve_js(filename):
    return send_from_directory('js', filename)


# ============================================================================
# ENDPOINTS RÉSUMÉ + RAG
# ============================================================================


@app.route('/')
def home():
    session['authorized'] = True
    return render_template('index.html')


@app.route('/summarize', methods=['POST'])
def summarize():
    data = request.json
    res = QSFSummarizer().summarize(data['text'], data.get('num_sentences', 3))
    return jsonify(res)


@app.route('/summarize-file', methods=['POST'])
def summarize_file():
    text = extract_text(request.files['file'])
    res = QSFSummarizer().summarize(text, int(request.form.get('num_sentences', 3)))
    return jsonify(res)


@app.route('/rag/index', methods=['POST'])
def rag_index():
    text = extract_text(request.files['file'])
    rag = QuantumRAGWithDGA()
    res = rag.index_text(text)
    if "success" in res:
        rag_indexes[res['session_id']] = rag
    return jsonify(res)


@app.route('/rag/query', methods=['POST'])
def rag_query():
    data = request.get_json(force=True, silent=True) or {}
    session_id = data.get('session_id')
    question = data.get('question')

    rag = rag_indexes.get(session_id)
    if not rag:
        return jsonify({"error": "Session introuvable. Veuillez re-télécharger le document."}), 404

    # Exécution du pipeline SAM 4.0 (Search + DGA Generation)
    try:
        output = rag.hybrid_query(question)
        return jsonify(output)
    except Exception as e:
        return jsonify({"error": f"Erreur interne : {str(e)}"}), 500


@app.route('/health')
def health(): return jsonify({"status": "online", "engine": "Quantum-DGA-DL"})


FEEDBACK_FILE = os.path.join(os.path.dirname(__file__), 'feedbacks.json')


@app.route('/feedback', methods=['POST'])
def feedback():
    data = request.get_json(force=True, silent=True) or {}
    entry = {
        "vote": data.get('vote'),
        "reason": data.get('reason', ''),
        "context": data.get('context', ''),
        "timestamp": datetime.utcnow().isoformat()
    }

    if os.path.exists(FEEDBACK_FILE):
        with open(FEEDBACK_FILE, 'r', encoding='utf-8') as f:
            feedbacks = json.load(f)
    else:
        feedbacks = []

    feedbacks.append(entry)

    with open(FEEDBACK_FILE, 'w', encoding='utf-8') as f:
        json.dump(feedbacks, f, ensure_ascii=False, indent=2)

    return jsonify({"status": "ok"})


if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000)
