"""
ICAC v2.2 — CSV Subventions 2025
Données extraites du « Tableau des Subventions 2025.pdf »
38 associations, 80 735,50 € total attribué.

Colonnes: association, attribution_2024, demande_2025, attribution_2025, observations
"""
import logging
import re
from functools import lru_cache

log = logging.getLogger("icac.csv_subventions")

# ── Données hardcodées depuis le PDF scanné ─────────────────────────
# (association, attrib_2024, demande_2025, attrib_2025, observations)
SUBVENTIONS_2025 = [
    # Page 1 — sous-total 52 753,00 €
    ("ACVG", 450.00, 450.00, 450.00, ""),
    ("AMICALE PERSONNEL COMMUNAL", 2500.00, 2500.00, 2500.00, ""),
    ("AMICALE DES SAPEURS POMPIERS", 300.00, 300.00, 300.00, ""),
    ("AMICALE VETERANS SAPEURS POMPIERS", 250.00, 500.00, 250.00, ""),
    ("APE COLLEGE LE CASTELLAS", 500.00, 600.00, 500.00, ""),
    ("ASSOCIATION SPORTIVE DU COLLEGE", 300.00, 300.00, 300.00, ""),
    ("BESSEGES BASKET CLUB", 8950.00, 8950.00, 8950.00, ""),
    ("BESSEGES ET SES ARTS", 200.00, 300.00, 200.00, ""),
    ("CAB", 8800.00, 8800.00, 8800.00, ""),
    ("CENTRE SOCIAL", 5000.00, 5000.00, 5000.00, ""),
    ("CHASSE GROS GIBIERS", 300.00, 400.00, 300.00, ""),
    ("CHORALE MOI JE VEUX CHANTER", 900.00, 1200.00, 900.00, ""),
    ("CLUB PHOTO", 800.00, 800.00, 800.00, ""),
    ("CLUB PONGISTE", 700.00, 800.00, 700.00, ""),
    ("EVEIL SPORTIF LA CANTONADE", 259.00, 1731.00, 203.00, "7 x 29 enf"),
    ("ETOILE DE BESSEGES", 22000.00, 22000.00, 22000.00, ""),
    ("FNATH", 300.00, 400.00, 300.00, ""),
    ("FOYER SOCIO EDUCATIF DU COLLEGE", 300.00, 300.00, 300.00, ""),
    # Page 2 — sous-total 17 482,50 €
    ("IRRP", 2500.00, 2500.00, 2500.00, ""),
    ("LA CHATTERIE", 400.00, 400.00, 400.00, ""),
    ("LA SAINT HUBERT", 450.00, 1233.00, 450.00, ""),
    ("LES AMIS DE LA CEZE", 350.00, 350.00, 350.00, ""),
    ("LES CAUSERIES DU BORD DE CEZE", 0.00, 500.00, 150.00, ""),
    ("LES CEVENNES BESSEGEOISE", 800.00, 1000.00, 800.00, ""),
    ("LES MAGNANARELLES", 250.00, 500.00, 250.00, ""),
    ("LES MARRONS GIVRES", 3000.00, 1000.00, 0.00, ""),
    ("LES PETITS FRIPONS", 1015.00, 350.00, 1116.50, "14,50 x 77 enf"),
    ("MAISON PERSEPHONE", 150.00, 3000.00, 150.00, ""),
    ("MIAOU EN CEVENNES", 0.00, 5400.00, 5400.00, ""),
    ("OGEC ST JOSEPH", 3250.00, 250.00, 250.00, ""),
    ("PASS'TEMPS", 250.00, 300.00, 300.00, ""),
    ("PUITS DE MEMOIRE", 300.00, 0.00, 0.00, "pas de demande cette année"),
    ("RENCONTRES CEVENOLES DE LA PHOTO", 3820.00, 700.00, 616.00, "7 x 88 enf"),
    ("SPORTING CLUB PETIT VILLARD", 609.00, 2000.00, 2000.00, ""),
    ("TAEKWONDO", 2000.00, 2000.00, 1800.00, ""),
    ("TENNIS CLUB", 1800.00, 6210.00, 1800.00, ""),
    ("UCB", 800.00, 800.00, 800.00, ""),
    # Page 3 — sous-total 10 500,00 €
    ("VIS TON SPORT", 200.00, 0.00, 0.00, "pas de demande cette année"),
    ("VELO SPRINT", 1500.00, 1500.00, 1500.00, ""),
    ("SALAMANDRA FESTIVAL", 0.00, 9000.00, 9000.00, ""),
]

TOTAL_ATTRIB_2024 = 76253.00
TOTAL_DEMANDE_2025 = 93324.00
TOTAL_ATTRIB_2025 = 80735.50


@lru_cache(maxsize=1)
def load_subventions() -> tuple:
    """Retourne les subventions comme tuple de dicts."""
    rows = []
    for nom, a24, d25, a25, obs in SUBVENTIONS_2025:
        rows.append({
            "association": nom,
            "attribution_2024": a24,
            "demande_2025": d25,
            "attribution_2025": a25,
            "observations": obs,
        })
    log.info("Subventions 2025 chargées: %d associations, total %s€",
             len(rows), f"{TOTAL_ATTRIB_2025:,.2f}")
    return tuple(rows)


def search_subventions(query: str, max_results: int = 10) -> str:
    """
    Recherche dans les subventions 2025.
    Retourne texte structuré pour Groq.
    """
    subventions = load_subventions()
    if not subventions:
        return ""

    query_low = query.lower()

    # Si requête générale "subventions associations" → tout retourner
    is_general = any(k in query_low for k in [
        "liste", "toutes", "total", "tableau",
        "subventions aux associations", "subventions municipales",
        "subventions versées",
    ])

    if is_general:
        return _format_all_subventions(subventions)

    # Recherche ciblée par mot-clé
    stopwords = {
        "les", "des", "une", "quelle", "subvention", "association",
        "commune", "bessèges", "besseges", "montant", "combien",
        "liste", "municipale", "versée",
    }
    keywords = [
        w for w in re.findall(r'\b[a-zàâéèêëîïôùûüç]{3,}\b', query_low)
        if w not in stopwords
    ]

    results = []
    for s in subventions:
        searchable = s["association"].lower()
        score = sum(1 for kw in keywords if kw in searchable)
        if score > 0:
            results.append((score, s))

    results.sort(key=lambda x: x[0], reverse=True)
    top = [r[1] for r in results[:max_results]]

    if not top:
        # Pas de match spécifique → retourner le tableau complet
        return _format_all_subventions(subventions)

    lines = [
        f"{len(top)} association(s) trouvée(s) "
        f"pour '{query}' dans les subventions 2025 :\n"
    ]
    for s in top:
        lines.append(_format_one(s))

    return "\n\n".join(lines)


def _format_all_subventions(subventions: tuple) -> str:
    """Format complet des subventions avec totaux et classement."""
    # Trier par montant attribué 2025 décroissant
    sorted_subs = sorted(subventions, key=lambda s: s["attribution_2025"], reverse=True)

    lines = [
        f"TABLEAU DES SUBVENTIONS 2025 — Commune de Bessèges",
        f"Source: Tableau des Subventions 2025.pdf (document officiel)",
        f"",
        f"TOTAL attribué 2024 : {TOTAL_ATTRIB_2024:>10,.2f} €",
        f"TOTAL demandé 2025 : {TOTAL_DEMANDE_2025:>10,.2f} €",
        f"TOTAL attribué 2025: {TOTAL_ATTRIB_2025:>10,.2f} €",
        f"Nombre d'associations: {len(subventions)}",
        f"Variation 2024→2025: {TOTAL_ATTRIB_2025 - TOTAL_ATTRIB_2024:+,.2f} € "
        f"({(TOTAL_ATTRIB_2025 - TOTAL_ATTRIB_2024) / TOTAL_ATTRIB_2024 * 100:+.1f}%)",
        f"",
        f"CLASSEMENT PAR MONTANT ATTRIBUÉ 2025 :",
    ]

    for i, s in enumerate(sorted_subs, 1):
        a25 = s["attribution_2025"]
        a24 = s["attribution_2024"]
        variation = a25 - a24
        var_str = f"({variation:+,.2f}€)" if variation != 0 else "(=)"

        obs = f" [{s['observations']}]" if s["observations"] else ""
        lines.append(
            f"  {i:>2}. {s['association']:<45s} {a25:>10,.2f} € {var_str}{obs}"
        )

    # Top 5 bénéficiaires
    top5 = sorted_subs[:5]
    top5_total = sum(s["attribution_2025"] for s in top5)
    lines.append(f"\nTOP 5 BÉNÉFICIAIRES ({top5_total:,.2f}€ = "
                 f"{top5_total/TOTAL_ATTRIB_2025*100:.1f}% du total) :")
    for i, s in enumerate(top5, 1):
        lines.append(f"  {i}. {s['association']}: {s['attribution_2025']:,.2f}€")

    # Nouvelles subventions (2024=0, 2025>0)
    nouvelles = [s for s in subventions if s["attribution_2024"] == 0 and s["attribution_2025"] > 0]
    if nouvelles:
        lines.append(f"\nNOUVELLES SUBVENTIONS 2025 ({len(nouvelles)}) :")
        for s in nouvelles:
            lines.append(f"  ■ {s['association']}: {s['attribution_2025']:,.2f}€")

    # Subventions supprimées (2024>0, 2025=0)
    supprimees = [s for s in subventions if s["attribution_2024"] > 0 and s["attribution_2025"] == 0]
    if supprimees:
        lines.append(f"\nSUBVENTIONS SUPPRIMÉES ({len(supprimees)}) :")
        for s in supprimees:
            lines.append(f"  ■ {s['association']}: {s['attribution_2024']:,.2f}€ en 2024 → 0€")

    return "\n".join(lines)


def _format_one(s: dict) -> str:
    """Format une subvention."""
    a24 = s["attribution_2024"]
    d25 = s["demande_2025"]
    a25 = s["attribution_2025"]
    variation = a25 - a24
    var_str = f"({variation:+,.2f}€)" if variation != 0 else "(stable)"
    obs = f"\n  Note     : {s['observations']}" if s["observations"] else ""

    return (
        f"■ {s['association']}\n"
        f"  Attribué 2024 : {a24:>10,.2f} €\n"
        f"  Demandé  2025 : {d25:>10,.2f} €\n"
        f"  Attribué 2025 : {a25:>10,.2f} € {var_str}\n"
        f"  Source        : Tableau Subventions 2025 (document officiel)"
        f"{obs}"
    )
