"""Test del proveedor 'syndication' SIN red.

Valida el parseo contra una respuesta REAL de X guardada como fixture, y que el
registry devuelve el proveedor. El fetch en vivo se prueba con run_real.py.

Ejecuta:  .venv/bin/python test_syndication.py
"""

import os
from datetime import datetime, timedelta, timezone

from agent.providers.syndication import SyndicationProvider
from agent.registry import get_provider

HERE = os.path.dirname(os.path.abspath(__file__))
FIXTURE = os.path.join(HERE, "tests", "fixtures", "syndication_sample.html")


def main():
    # 1) el registry devuelve el proveedor correcto
    p = get_provider("syndication", {})
    assert isinstance(p, SyndicationProvider), "registry no devuelve SyndicationProvider"
    print("registry OK ->", p.name())

    # 2) parseo offline contra una respuesta real guardada
    with open(FIXTURE, encoding="utf-8") as f:
        html = f.read()
    since = datetime(2015, 1, 1, tzinfo=timezone.utc)
    tweets = p.parse_html(html, "karpathy", since=since, limit=50)
    assert tweets, "no se parseó ningún tweet"
    print(f"tweets parseados: {len(tweets)}")

    t = tweets[0]
    assert t.id and t.author and t.created_at, "faltan campos básicos"
    assert isinstance(t.likes, int) and isinstance(t.retweets, int), "métricas no son int"
    assert t.url.startswith("https://x.com/"), "URL mal formada"
    print("ejemplo ->", f"@{t.author}", "❤", t.likes, "🔁", t.retweets, "|", (t.text or "")[:55])

    # 3) el orden es por fecha descendente
    assert all(
        tweets[i].created_at >= tweets[i + 1].created_at for i in range(len(tweets) - 1)
    ), "no está ordenado por fecha"
    print("orden por fecha OK")

    # 4) el filtro por ventana funciona (ventana futura -> 0 tweets)
    future = datetime(2030, 1, 1, tzinfo=timezone.utc)
    assert p.parse_html(html, "karpathy", since=future, limit=50) == [], "el filtro de ventana no filtra"
    print("filtro de ventana OK")

    # 5) detección de "caché viejo" (el fixture es de noviembre 2025)
    newest = p._parse_all(html, "karpathy")[0].created_at
    assert p.is_stale(newest), "no detecta el caché viejo del fixture"
    assert not p.is_stale(datetime.now(timezone.utc) - timedelta(hours=2)), "marca como viejo algo reciente"
    assert p.is_stale(None), "None debería contar como viejo"
    print(f"detección stale OK -> newest={newest.date()} marcado como viejo")

    print("\nSYNDICATION_PARSE_OK")


if __name__ == "__main__":
    main()
