"""Prueba EN VIVO del proveedor 'scweet' (requiere la cookie auth_token configurada).

Ejecuta:  .venv/bin/python run_scweet.py

Trae tweets frescos de tus cuentas activas usando Scweet + una cuenta secundaria.
Si falta la cookie, te dice cómo ponerla (ver SETUP_SCWEET.md).
"""

import os
from datetime import datetime, timedelta, timezone

from agent.config import load_config
from agent.providers.scweet_provider import ScweetError, ScweetProvider
from agent.store import load_accounts

HERE = os.path.dirname(os.path.abspath(__file__))
cfg = load_config(os.path.join(HERE, "config.yaml"))
accounts_path = cfg["accounts_path"]
if not os.path.isabs(accounts_path):
    accounts_path = os.path.join(HERE, accounts_path)
for k in ("scweet_db_path", "scweet_secrets_file"):
    if cfg.get(k) and not os.path.isabs(cfg[k]):
        cfg[k] = os.path.join(HERE, cfg[k])

accounts = [a for a in load_accounts(accounts_path) if a.enabled]
provider = ScweetProvider(cfg)
window = cfg["window_hours"]
since = datetime.now(timezone.utc) - timedelta(hours=window)

print(f"Scweet · {len(accounts)} cuentas · ventana {window}h\n")
try:
    provider._get_client()  # valida la cookie e inicializa antes del bucle
except ScweetError as e:
    print(f"❌ {e}")
    raise SystemExit(1)

fresh = 0
for a in accounts:
    try:
        tw = provider.fetch_user_tweets(a.handle, since, 50)
        meta = provider.last_meta.get(a.handle.lstrip("@"), {})
        newest = meta.get("newest")
        ns = newest.astimezone().strftime("%Y-%m-%d %H:%M") if newest else "—"
        if tw:
            fresh += 1
            print(f"✅ @{a.handle:13} {len(tw):2} en {window}h | último: {ns} | top ❤{tw[0].likes:,}")
        else:
            print(f"➖ @{a.handle:13} 0 en {window}h | último dato: {ns}")
    except ScweetError as e:
        print(f"❌ @{a.handle:13} {e}")

print(f"\nFrescas: {fresh}/{len(accounts)}")
