#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
SAM — Détecteur IA vs Humain
Extraction QSFSummarizer → question unique → verdict utilisateur.

Usage : python3 app.py
"""

from hello import QSFSummarizer
import os
import sys
import warnings

from flask import Flask, render_template, request, jsonify

warnings.filterwarnings("ignore")
sys.path.insert(0, os.path.dirname(__file__))

app = Flask(__name__)

N_PHRASES = 10


# =============================================================================
# EXTRACTION
# =============================================================================

def extract_with_qsf(text: str, n_phrases: int = N_PHRASES):
    qsf = QSFSummarizer()
    sentences = qsf.clean_and_split_sentences(text)
    if not sentences:
        return None

    n_total = len(sentences)
    vocab = qsf.build_vocabulary(sentences)
    sentences_data = qsf.corpus_to_structured_data(sentences, vocab)
    sentence_reprs = [
        qsf.get_sentence_representation(s["indices"], s["roles"])
        for s in sentences_data
    ]
    doc_repr = qsf.create_document_representation(sentence_reprs)

    if n_total <= n_phrases:
        return {
            "n_total": n_total,
            "phrases": [{"index": i, "text": sd["text"]}
                        for i, sd in enumerate(sentences_data)],
        }

    lambda_mmr = 0.4
    selected_indices = []
    selected_reprs = []
    available = list(range(n_total))

    for _ in range(min(n_phrases, n_total)):
        best_mmr = -float("inf")
        best_idx = -1
        for idx in available:
            mmr = qsf.compute_sentence_importance(
                sentence_reprs[idx], doc_repr, selected_reprs,
                lambda_mmr=lambda_mmr,
            )
            if mmr > best_mmr:
                best_mmr = mmr
                best_idx = idx
        if best_idx != -1:
            selected_indices.append(best_idx)
            selected_reprs.append(sentence_reprs[best_idx])
            available.remove(best_idx)

    phrases = sorted(
        [{"index": idx, "text": sentences_data[idx]["text"]}
         for idx in selected_indices],
        key=lambda p: p["index"],
    )
    return {"n_total": n_total, "phrases": phrases}


# =============================================================================
# ROUTES
# =============================================================================

@app.route("/")
def index():
    return render_template("index.html")


@app.route("/status")
def status():
    return jsonify({"ready": True})


@app.route("/analyze", methods=["POST"])
def analyze():
    data = request.get_json(silent=True) or {}
    text = str(data.get("text", "")).strip()

    if len(text) < 200:
        return jsonify({"error": "Texte trop court (minimum 200 caractères)."}), 400

    raw = extract_with_qsf(text)
    if raw is None:
        return jsonify({"error": "Impossible d'extraire un résumé."}), 400

    return jsonify({
        "n_total":  raw["n_total"],
        "n_phrases": len(raw["phrases"]),
        "phrases":  raw["phrases"],
    })


# =============================================================================
# STARTUP
# =============================================================================

if __name__ == "__main__":
    print("[SAM] Prêt.")
    app.run(debug=False, host="0.0.0.0", port=5000)
