"""Read-only discovery: list GSYS instances, their course, and start-group gun
times (UTC and +2h local), plus courses, to pin the real Race 1 / Digital 8."""
from datetime import UTC, datetime, timedelta

from google.cloud import firestore
from google.cloud.firestore_v1.base_query import FieldFilter

db = firestore.Client(project="apps-viewregatta")
FF = FieldFilter

uid = "e5c5d08e-f8e9-4c2d-a6c3-3f6cc5d8d6d6"  # GSYS (from probe)


def hhmm(ms, off=0):
    if not ms:
        return "—"
    return (datetime.fromtimestamp(ms / 1000, tz=UTC) + timedelta(hours=off)).strftime("%m-%d %H:%M")


print("uid", uid)

print("\n=== courses (owner) ===")
course_name = {}
for c in db.collection("courses").where(filter=FF("ownerUserId", "==", uid)).stream():
    d = c.to_dict() or {}
    course_name[c.id] = d.get("name")
    print(f"  {c.id}  {d.get('name')!r}")

print("\n=== instances ===")
for inst in db.collection("raceInstances").where(filter=FF("ownerUserId", "==", uid)).stream():
    d = inst.to_dict() or {}
    cid = d.get("courseId")
    cn = course_name.get(cid) or "?"
    print(f"\ninstance {inst.id}  name={d.get('name')!r}  status={d.get('status')}  course={cn!r} ({cid})")
    for g in db.collection("raceInstances").document(inst.id).collection("startGroups").stream():
        gd = g.to_dict() or {}
        nteams = sum(1 for _ in g.reference.collection("teamEntries").stream())
        print(f"    group {g.id[:8]} name={gd.get('name')!r} gunUTC={hhmm(gd.get('officialStartUtcMs'))} "
              f"gun+2={hhmm(gd.get('officialStartUtcMs'),2)} stopUTC={hhmm(gd.get('officialStopUtcMs'))} teams={nteams}")
