"""Read-only: actual track time spans for boats 2/4/5/6 on 2026-05-22, to align
the window. Prints each track's start/end in UTC and +2 (CEST)."""
from datetime import UTC, datetime, timedelta

from google.cloud import firestore
from google.cloud.firestore_v1.base_query import FieldFilter as FF

db = firestore.Client(project="apps-viewregatta")
INSTANCE = "hUokC5BxKlkPmzbfUmqj"
DAY_FROM = int(datetime(2026, 5, 22, 0, 0, tzinfo=UTC).timestamp() * 1000)
DAY_TO = int(datetime(2026, 5, 23, 0, 0, tzinfo=UTC).timestamp() * 1000)


def hm(ms, off=0):
    return (datetime.fromtimestamp(ms / 1000, tz=UTC) + timedelta(hours=off)).strftime("%H:%M:%S") if ms else "—"


def dev_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 {}
        return md.get("deviceId")
    return None


grp = list(db.collection("raceInstances").document(INSTANCE).collection("startGroups").stream())[0]
sail_dev = {}
for t in grp.reference.collection("teamEntries").stream():
    for b in t.reference.collection("boatEntries").stream():
        bd = b.to_dict() or {}
        sail_dev[str(bd.get("sailId") or bd.get("visualId"))] = bd.get("deviceId") or dev_for_boat(bd.get("boatId"))

for sail in ["2", "4", "5", "6"]:
    dev = sail_dev.get(sail)
    print(f"\n--- boat {sail}  device {dev} ---")
    if not dev:
        continue
    trks = list(db.collection("tracks").where(filter=FF("deviceId", "==", dev)).stream())
    day = []
    for tr in trks:
        td = tr.to_dict() or {}
        s = td.get("startUtcMs") or 0
        if DAY_FROM <= s < DAY_TO:
            day.append((s, td.get("endUtcMs") or 0, td.get("pointCount"), td.get("deletedAt")))
    day.sort()
    print(f"  tracks on 2026-05-22: {len(day)}")
    for s, e, pc, dele in day:
        print(f"    UTC {hm(s)}–{hm(e)}   CEST {hm(s,2)}–{hm(e,2)}   pts={pc}  deleted={dele}")
