import re
from apps.editor.models import Project

community_word_tokens = ("audiencia","comunidad","seguidores","feedback")
community_phrase_tokens = ("interacción con","interaccion con","compartir el live","comparten el live","cierre del live","logística del live","logistica del live","saluda a la","saludo a la")
promo_word_tokens = ("giveaway","sorteo","rifa","concurso","regalo","regalamos","premio","premios","kit")
promo_phrase_tokens = ("promoción del","promocion del","dinámica del","dinamica del","patrocin","para participar")

def _build(words):
    return re.compile(r"\b(" + "|".join(re.escape(w) for w in words) + r")\b", re.IGNORECASE)
cre = _build(community_word_tokens); pre = _build(promo_word_tokens)

def evaluate(a):
    parts = [str(a.get(k) or "") for k in ("sequence_name","topic_label","conversation_summary","editorial_rationale")]
    h = " ".join(parts); hl = h.lower()
    m = cre.search(h)
    if m: return ("community", m.group(0).lower())
    for p in community_phrase_tokens:
        if p in hl: return ("community", p)
    m = pre.search(h)
    if m: return ("promo", m.group(0).lower())
    for p in promo_phrase_tokens:
        if p in hl: return ("promo", p)
    return (None, "")

p = Project.objects.get(pk=8)
src = p.ai_suggestions.filter(is_active=True).order_by("-updated_at","-created_at").first()
alts = (src.structured_response or {}).get("alternatives") or []
USER_TARGETS = {30,29,23,22,20,18,16,14,13}
ok=0; bad=0
print(f"{'IDX':>3} {'EXP':<5} {'GOT':<5} {'KW':<22} {'DUR':>5}  NAME")
for i, a in enumerate(alts, 1):
    kind, kw = evaluate(a)
    dur = (int(a.get("end_ms") or 0) - int(a.get("start_ms") or 0)) / 1000
    name = (a.get("sequence_name") or "?")[:55]
    expect = "JUNK" if i in USER_TARGETS else "KEEP"
    got = "JUNK" if kind else "KEEP"
    mark = "OK " if expect == got else "MIS"
    if expect == got: ok += 1
    else: bad += 1
    print(f"{mark} {i:>2} {expect:<5} {got:<5} {kw:<22} {dur:>4.0f}s  {name}")
print(f"\nAciertos {ok}/{len(alts)}  ·  errores {bad}")
