"""Validación automática del cache-bust (corre en segundo plano).

1) Espera a que la IP salga del rate-limit de X (sondea cada 2 min).
2) Compara cache-bust ON vs OFF en las cuentas que venían 'viejas' -> ¿ayuda?
3) Repasa las 10 cuentas con cache-bust ON.
"""

import os
import time
from datetime import datetime, timedelta, timezone

from agent.config import load_config
from agent.providers.syndication import SyndicationProvider, SyndicationError
from agent.store import load_accounts

HERE = os.path.dirname(os.path.abspath(__file__))
cfg = load_config(os.path.join(HERE, "config.yaml"))
ap = cfg["accounts_path"]
if not os.path.isabs(ap):
    ap = os.path.join(HERE, ap)

now = lambda: datetime.now(timezone.utc)
WIDE = timedelta(days=30)   # ventana amplia para ver el tweet más nuevo


def fetch_meta(handle, cache_bust):
    p = SyndicationProvider({"syndication_delay_seconds": 7, "syndication_retries": 0,
                             "syndication_cache_bust": cache_bust})
    p.fetch_user_tweets(handle, now() - WIDE, 50)
    return p.last_meta.get(handle.lstrip("@"), {})


def date_str(dt):
    return dt.date().isoformat() if hasattr(dt, "date") and dt else "—"


# --- 1) esperar al desbloqueo ---
print("Esperando a que la IP salga del rate-limit (sondeo cada 2 min, máx 30)...", flush=True)
unblocked = False
for i in range(15):
    try:
        fetch_meta("TechCrunch", True)
        unblocked = True
        print(f"✅ Desbloqueado (tras ~{i * 2} min).\n", flush=True)
        break
    except SyndicationError:
        time.sleep(120)

if not unblocked:
    print("Sigue bloqueado tras 30 min. Prueba run_real.py más tarde.\nVALIDATION_INCONCLUSIVE")
    raise SystemExit(0)

# --- 2) cache-bust ON vs OFF en cuentas que estaban viejas ---
print("=== cache-bust OFF vs ON (cuentas que venían viejas) ===", flush=True)
stale_handles = ["karpathy", "rowancheung", "AndrewYNg"]
improved = 0
for h in stale_handles:
    try:
        off = fetch_meta(h, False)
        time.sleep(7)
        on = fetch_meta(h, True)
        time.sleep(7)
        print(f"@{h:12} OFF: {date_str(off.get('newest'))} (viejo={off.get('stale')}) | "
              f"ON: {date_str(on.get('newest'))} (viejo={on.get('stale')})", flush=True)
        if on.get("stale") is False and off.get("stale") in (True, None):
            improved += 1
    except SyndicationError as e:
        print(f"@{h:12} error: {e}", flush=True)

verdict = "CACHE_BUST_WORKS" if improved else "CACHE_BUST_INSUFFICIENT"
print(f"\nMejoradas por cache-bust: {improved}/{len(stale_handles)}  ->  {verdict}\n", flush=True)

# --- 3) repaso de las 10 con cache-bust ON ---
print("=== repaso de todas las cuentas (cache-bust ON, ventana 30d) ===", flush=True)
provider = SyndicationProvider({**cfg, "syndication_cache_bust": True, "syndication_delay_seconds": 8})
fresh = 0
for a in [x for x in load_accounts(ap) if x.enabled]:
    try:
        provider.fetch_user_tweets(a.handle, now() - WIDE, 50)
        meta = provider.last_meta.get(a.handle.lstrip("@"), {})
        tag = "🟠 viejo" if meta.get("stale") else "✅ fresco"
        if not meta.get("stale"):
            fresh += 1
        print(f"  {tag}  @{a.handle:13} último: {date_str(meta.get('newest'))}", flush=True)
    except SyndicationError as e:
        print(f"  ❌ error  @{a.handle:13} {e}", flush=True)

print(f"\nFrescas: {fresh}/10\nVALIDATION_DONE")
