import mysql.connector
from app.db.connection import get_connection
from app.ai.analyzer import analyze_article
from app.ai.prompts import PROMPT_VERSION
from app.ai.triage_prompts import TRIAGE_VERSION
from app.utils.fetcher import fetch_article_text

# Garde-fou anti-dérapage (tu peux modifier)
MAX_TO_ANALYZE = 200

# Quand content < ce seuil, on considère "vide/pas utile" et on tente un scraping
MIN_CONTENT_CHARS = 400

# On tronque pour éviter d'envoyer des pavés à l'IA
MAX_CONTENT_CHARS = 12000


def analyze():
    conn = get_connection()
    cur = conn.cursor(dictionary=True)

    # Récupérer des articles bruts non scorés
    cur.execute(
        """
        SELECT
            ar.id, ar.title, ar.excerpt, ar.lang, ar.url, ar.content,
            tr.triage_score, tr.triage_label
        FROM articles_raw ar
        JOIN articles_triage tr
          ON tr.raw_id = ar.id AND tr.triage_version = %s
        LEFT JOIN articles_scored sc
          ON sc.raw_id = ar.id AND sc.prompt_version = %s
        WHERE sc.raw_id IS NULL
          AND tr.triage_label IN ('hot','maybe')
        ORDER BY tr.triage_score DESC, ar.published_at DESC
        LIMIT %s
        """,
        (TRIAGE_VERSION, PROMPT_VERSION, MAX_TO_ANALYZE)
    )

    rows = cur.fetchall()

    if not rows:
        print("ℹ️ Aucun article à analyser (tout est déjà scoré).")
        cur.close()
        conn.close()
        return

    inserted = 0
    failed = 0
    scores = []

    for r in rows:
        raw_id = r["id"]
        title = r.get("title") or ""
        excerpt = r.get("excerpt") or ""
        url = r.get("url") or ""
        content = r.get("content") or ""

        try:
            # ✅ 1) Si content est trop court, on tente de le récupérer depuis l'URL
            fetched = False
            if len(content.strip()) < MIN_CONTENT_CHARS and url:
                text = fetch_article_text(url)
                if text:
                    text = text.strip()[:MAX_CONTENT_CHARS]
                    # On stocke en DB pour éviter de re-scraper plus tard
                    cur.execute(
                        "UPDATE articles_raw SET content=%s WHERE id=%s",
                        (text, raw_id)
                    )
                    conn.commit()
                    content = text
                    fetched = True

            # ✅ 2) Analyse IA : maintenant on passe aussi content
            result = analyze_article(title=title, excerpt=excerpt, content=content)

            cur.execute(
                """
                INSERT INTO articles_scored
                  (raw_id, good_news_score, summary, wink_title, topic,
                   source_lang, output_lang, model, prompt_version, tokens_in, tokens_out)
                VALUES
                  (%s, %s, %s, %s, %s,
                   %s, %s, %s, %s, %s, %s)
                """,
                (
                    raw_id,
                    result["good_news_score"],
                    result["summary"],
                    result["wink_title"],
                    result["topic"],
                    result["source_lang"],
                    "fr",
                    result["model"],
                    PROMPT_VERSION,
                    result["tokens_in"],
                    result["tokens_out"],
                )
            )

            inserted += 1
            scores.append(result["good_news_score"])
            conn.commit()

            fetch_flag = " fetched_content=1" if fetched else ""
            print(
                f"✅ Scoré {PROMPT_VERSION} score={result['good_news_score']} "
                f"triage={r.get('triage_score')} label={r.get('triage_label')} "
                f"raw_id={raw_id}{fetch_flag} reason={result['score_reason']}"
            )

        except mysql.connector.errors.IntegrityError:
            # déjà scoré (rare si exécution concurrente)
            conn.commit()

        except Exception as e:
            failed += 1
            print(f"❌ Échec raw_id={raw_id}: {e}")

    cur.close()
    conn.close()

    scoremax = max(scores) if scores else None
    print(
        f"🎯 Analyse terminée — inserted={inserted}, failed={failed}, "
        f"limit={MAX_TO_ANALYZE}, scoremax={scoremax}"
    )


if __name__ == "__main__":
    analyze()