#!/usr/bin/env python3
"""
refresh_from_tba.py — pull EVERY active FRC team's Instagram + YouTube
straight from The Blue Alliance, then rebuild the CSV / HTML board / PDF.

Setup (one time, ~2 minutes):
  1. Sign in at https://www.thebluealliance.com/account
  2. Create a Read API Key
  3. Run:  python refresh_from_tba.py --key YOUR_TBA_KEY
     Optional: --year 2026 (default)  --url https://your-hosted-board-link  (for the QR code)

What it does:
  * /teams/{year}/{page}        -> every team registered for events this season ("active")
  * /team/{key}/social_media    -> instagram-profile + youtube-channel records per team
  * Writes out/frc_socials.json + .csv, then re-runs build_html.py and build_pdf.py
  * Polite rate limiting + resumable cache (tba_cache.json) so re-runs are fast

Built for the Bedford Express (1023) media desk. 🚂
"""
import argparse, json, time, subprocess, sys, urllib.request, os

BASE = "https://www.thebluealliance.com/api/v3"

def get(path, key):
    req = urllib.request.Request(BASE + path, headers={"X-TBA-Auth-Key": key,
                                                       "User-Agent": "bx1023-media-board"})
    with urllib.request.urlopen(req, timeout=30) as r:
        return json.load(r)

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--key", required=True, help="TBA Read API key")
    ap.add_argument("--year", type=int, default=2026)
    ap.add_argument("--url", default="https://www.thebluealliance.com/teams",
                    help="URL the printed QR code should open (your hosted board)")
    args = ap.parse_args()

    cache = {}
    if os.path.exists("tba_cache.json"):
        cache = json.load(open("tba_cache.json"))

    # 1) all active teams this season
    teams, page = [], 0
    while True:
        batch = get(f"/teams/{args.year}/{page}", args.key)
        if not batch: break
        teams += batch
        print(f"  page {page}: {len(batch)} teams (total {len(teams)})")
        page += 1
    print(f"Active teams in {args.year}: {len(teams)}")

    # 2) social media per team
    out = []
    for i, t in enumerate(teams):
        k = t["key"]
        if k in cache:
            sm = cache[k]
        else:
            try:
                sm = get(f"/team/{k}/social_media", args.key)
            except Exception as e:
                print("  skip", k, e); sm = []
            cache[k] = sm
            time.sleep(0.12)                      # be kind to TBA
            if i % 200 == 0:
                json.dump(cache, open("tba_cache.json","w"))
                print(f"  ...{i}/{len(teams)} ({t['team_number']})")
        ig = next((m["foreign_key"] for m in sm if m["type"] == "instagram-profile"), "")
        yt = next((m["foreign_key"] for m in sm if m["type"] == "youtube-channel"), "")
        if not (ig or yt): continue
        loc = ", ".join(x for x in [t.get("city"), t.get("state_prov"), t.get("country")] if x)
        out.append({
            "num": t["team_number"], "name": t.get("nickname",""), "location": loc,
            "rookie": str(t.get("rookie_year","")), "website": t.get("website") or "",
            "instagram": f"https://www.instagram.com/{ig}" if ig else "",
            "instagram2": "", "youtube": (f"https://www.youtube.com/{yt}" if not yt.startswith("UC")
                                          else f"https://www.youtube.com/channel/{yt}") if yt else "",
            "source": f"TBA {time.strftime('%b %Y')}",
            "ig_handle": "@"+ig if ig else "", "ig2_handle": "",
            "yt_handle": ("/"+yt if not yt.startswith("UC") else "channel") if yt else "",
            "michigan": t.get("state_prov") in ("Michigan","MI"),
        })
    json.dump(cache, open("tba_cache.json","w"))
    out.sort(key=lambda x: x["num"])
    json.dump(out, open("out/frc_socials.json","w"), indent=1)
    print(f"Teams with IG or YT on TBA: {len(out)}")

    import csv
    with open("out/frc_socials.csv","w", newline="", encoding="utf-8") as f:
        w = csv.writer(f)
        w.writerow(["Team #","Name","Location","Rookie Year","Instagram","Instagram (2nd)","YouTube","Website","Data source"])
        for t in out:
            w.writerow([t["num"],t["name"],t["location"],t["rookie"],t["instagram"],"",t["youtube"],t["website"],t["source"]])

    subprocess.run([sys.executable, "build_html.py"], check=True)
    subprocess.run([sys.executable, "build_pdf.py", args.url,
                    "Live interactive board — search, filter, tap to open"], check=True)
    print("\nDone. Fresh out/frc_social_board.html + out/frc_social_board_print.pdf")

if __name__ == "__main__":
    main()
