"""Read-only: for the candidate 2026-05-22 instances, list teams->boats->device
and count each device's track points in the user's window (13:06:30-13:19:00 UTC
= 15:06:30-15:19:00 CEST)."""
from datetime import UTC, datetime

from google.cloud import firestore
from google.cloud.firestore_v1.base_query import FieldFilter as FF

db = firestore.Client(project="apps-viewregatta")

TRACK_START = int(datetime(2026, 5, 22, 13, 6, 30, tzinfo=UTC).timestamp() * 1000)
GUN = int(datetime(2026, 5, 22, 13, 9, 45, tzinfo=UTC).timestamp() * 1000)
TRACK_END = int(datetime(2026, 5, 22, 13, 19, 0, tzinfo=UTC).timestamp() * 1000)
print("window UTC ms:", TRACK_START, GUN, TRACK_END)

CANDIDATES = {
    "hUokC5BxKlkPmzbfUmqj": "14:50-15:50",
    "FZoxFxpW9C7Nv8ykrEhy": "Race 1 (Team race)",
}


def device_for_boat(boat_id):
    if not boat_id:
        return None
    for m in db.collection("deviceMounts").where(filter=FF("boatId", "==", boat_id)).stream():
        md = m.to_dict() or {}
        if (md.get("fromUtcMs") or 0) <= GUN and (md.get("toUtcMs") is None or GUN <= md.get("toUtcMs")):
            return md.get("deviceId")
    return None


def count_points(dev):
    if not dev:
        return 0
    n = 0
    for tr in db.collection("tracks").where(filter=FF("deviceId", "==", dev)).stream():
        td = tr.to_dict() or {}
        if td.get("deletedAt") is not None:
            continue
        if (td.get("endUtcMs") or 0) < TRACK_START or (td.get("startUtcMs") or 0) > TRACK_END:
            continue
        for bb in db.collection("tracks").document(tr.id).collection("batches").stream():
            for p in (bb.to_dict() or {}).get("points", []):
                t = p.get("t") or 0
                if TRACK_START <= t <= TRACK_END and p.get("lat") is not None:
                    n += 1
    return n


for inst_id, label in CANDIDATES.items():
    idoc = db.collection("raceInstances").document(inst_id).get()
    if not idoc.exists:
        print(f"\n{label} ({inst_id}): NOT FOUND")
        continue
    inst = idoc.to_dict() or {}
    print(f"\n=== {label}  ({inst_id})  course={inst.get('courseId')} ===")
    for g in db.collection("raceInstances").document(inst_id).collection("startGroups").stream():
        gd = g.to_dict() or {}
        print(f"  group {gd.get('name')!r}")
        for t in g.reference.collection("teamEntries").stream():
            td = t.to_dict() or {}
            for b in t.reference.collection("boatEntries").stream():
                bd = b.to_dict() or {}
                dev = bd.get("deviceId") or device_for_boat(bd.get("boatId"))
                pts = count_points(dev)
                print(f"    team={td.get('teamName')!r} sail={bd.get('sailId')!r} visual={bd.get('visualId')!r} "
                      f"boatId={(bd.get('boatId') or '')[:8]} dev={(dev or 'NONE')[:12]} pts_in_window={pts}")
