import json
import sqlite3
from pathlib import Path
from urllib.request import urlopen, Request


def _get_first_steam_id(base_dir: Path) -> str:
    conn = sqlite3.connect(str(base_dir / "database" / "L2" / "L2.db"))
    try:
        cur = conn.execute("SELECT steam_id_64 FROM dim_players WHERE steam_id_64 IS NOT NULL LIMIT 1")
        row = cur.fetchone()
        return str(row[0]) if row else ""
    finally:
        conn.close()


def _get(url: str) -> tuple[int, str]:
    req = Request(url, headers={"User-Agent": "yrtv-smoke"})
    with urlopen(req, timeout=10) as resp:
        status = getattr(resp, "status", 200)
        body = resp.read().decode("utf-8", errors="replace")
        return status, body


if __name__ == "__main__":
    base_dir = Path(__file__).resolve().parents[1]
    steam_id = _get_first_steam_id(base_dir)
    if not steam_id:
        raise SystemExit("no steam_id in L2.dim_players")

    urls = [
        "http://127.0.0.1:5000/",
        "http://127.0.0.1:5000/players/",
        f"http://127.0.0.1:5000/players/{steam_id}",
        f"http://127.0.0.1:5000/players/{steam_id}/charts_data",
        "http://127.0.0.1:5000/matches/",
        "http://127.0.0.1:5000/teams/",
        "http://127.0.0.1:5000/teams/api/roster",
        "http://127.0.0.1:5000/tactics/",
        "http://127.0.0.1:5000/opponents/",
        "http://127.0.0.1:5000/wiki/",
    ]

    for u in urls:
        status, body = _get(u)
        print(f"{status} {u} len={len(body)}")
        if u.endswith("/charts_data"):
            obj = json.loads(body)
            for k in ["trend", "radar", "radar_dist"]:
                print(f"  {k}: {'ok' if k in obj else 'missing'}")
