File size: 60,431 Bytes
4598c11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be69d1e
4598c11
 
3ee736f
 
4598c11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ee736f
 
4598c11
 
3ee736f
 
 
 
4598c11
3ee736f
 
 
 
 
4598c11
 
 
3ee736f
4598c11
3ee736f
4598c11
 
 
3ee736f
4598c11
3ee736f
4598c11
3ee736f
4598c11
3ee736f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4598c11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6437539
 
4598c11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ee736f
 
 
4598c11
3ee736f
 
4598c11
 
 
 
 
 
3ee736f
 
4598c11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ee736f
 
 
4598c11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6437539
 
4598c11
 
6437539
4598c11
 
6437539
4598c11
 
 
6437539
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4598c11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ee736f
 
 
 
4598c11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
"""End-to-end QA suite: uploads, sessions, swing reports, plan limit, drills, catalog (journeys 3.3 / 3.4, milestone 2).

Runs against a live server (real database and real storage). Creates its own accounts and deletes them at the end.

    BASE_URL=http://127.0.0.1:8000 .venv/bin/python e2e/qa_sessions_reports.py
"""

import copy
import json
import os
import re
import sys
import uuid
from datetime import UTC, date, datetime, timedelta

import httpx

BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:8000").rstrip("/")
RUN_ID = uuid.uuid4().hex[:8]
PASSWORD = "Qa-pass-12345"

VIDEO_BYTES = b"\x00\x00\x00\x18ftypmp42" + b"\x00\x00\x00\x00mp42isom" + os.urandom(512)
JPEG_BYTES = b"\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00" + os.urandom(256) + b"\xff\xd9"

client = httpx.Client(base_url=BASE_URL, timeout=90)
raw = httpx.Client(timeout=60)  # for presigned storage URLs

RESULTS = {"PASS": 0, "FAIL": 0}
FAILS: list[str] = []
NOTES: list[str] = []
CAMEL: set[str] = set()
FIVE_HUNDREDS: list[str] = []
FORBIDDEN_KEYS = {"password_hash", "password", "measurement_payload", "refresh_token_hash", "object_key"}
LEAKS: list[str] = []


# ---------------------------------------------------------------- helpers

def _short(text: str, n: int = 900) -> str:
    return text if len(text) <= n else text[:n] + "..."


def check(name: str, ok: bool, resp: httpx.Response | None = None, detail: str = "") -> bool:
    tag = "PASS" if ok else "FAIL"
    RESULTS[tag] += 1
    where = ""
    if resp is not None:
        where = f" [{resp.request.method} {resp.request.url.path} -> {resp.status_code}]"
    line = f"{tag}: {name}{where}"
    if not ok:
        body = ""
        if resp is not None:
            body = _short(resp.text)
        line += f"\n      detail: {detail}" if detail else ""
        line += f"\n      body: {body}" if body else ""
        FAILS.append(line)
    print(line, flush=True)
    return ok


def note(text: str) -> None:
    NOTES.append(text)
    print(f"NOTE: {text}", flush=True)


def scan_keys(obj, path="$", skip_children_of=("headers", "fields")):
    if isinstance(obj, dict):
        for k, v in obj.items():
            if isinstance(k, str):
                if re.search(r"[A-Z]", k) and not path.endswith(skip_children_of):
                    CAMEL.add(f"{path}.{k}")
                if k in FORBIDDEN_KEYS:
                    LEAKS.append(f"{path}.{k}")
            if k in skip_children_of:
                continue
            scan_keys(v, f"{path}.{k}")
    elif isinstance(obj, list):
        for v in obj[:50]:
            scan_keys(v, f"{path}[]")


def call(method: str, path: str, token: str | None = None, **kw) -> httpx.Response:
    headers = kw.pop("headers", {}) or {}
    if token:
        headers["Authorization"] = f"Bearer {token}"
    r = client.request(method, path, headers=headers, **kw)
    if r.status_code >= 500:
        FIVE_HUNDREDS.append(f"{method} {path} -> {r.status_code}: {_short(r.text, 300)}")
    try:
        if r.content:
            scan_keys(r.json(), f"{method} {re.sub(r'[0-9a-f-]{36}', '{id}', path)}")
    except ValueError:
        pass
    return r


def err_code(r: httpx.Response) -> str | None:
    try:
        return r.json()["error"]["code"]
    except Exception:
        return None


def err_fields(r: httpx.Response) -> dict:
    try:
        return r.json()["error"].get("fields") or {}
    except Exception:
        return {}


def expect_error(name: str, r: httpx.Response, status: int, code: str | None = None, field_prefix: str | None = None):
    ok = r.status_code == status and (code is None or err_code(r) == code)
    detail = f"expected {status} {code or ''}"
    if ok and field_prefix is not None:
        ok = any(k.startswith(field_prefix) for k in err_fields(r))
        detail += f" with a field starting {field_prefix!r}; got fields {list(err_fields(r))}"
    return check(name, ok, r, detail)


ACCOUNTS: list[dict] = []
n_accounts = 0


def register(role: str = "player") -> dict:
    global n_accounts
    n_accounts += 1
    email = f"qa-sess-{RUN_ID}-{n_accounts}@example.com"
    r = call("POST", "/v1/auth/register", json={"email": email, "password": PASSWORD, "role": role})
    if not check(f"register {email}", r.status_code == 201, r, "expected 201"):
        raise SystemExit("cannot continue without an account")
    data = r.json()
    acct = {"email": email, "token": data["tokens"]["access_token"], "id": data["user"]["id"], "deleted": False}
    ACCOUNTS.append(acct)
    return acct


def set_profile(acct: dict, **profile) -> httpx.Response:
    r = call("PATCH", "/v1/me", acct["token"], json={"profile": profile})
    check(f"PATCH /me profile {profile.get('name')}", r.status_code == 200, r, "expected 200")
    return r


def presign(acct, kind="video", content_type=None, size=None, duration=3.0) -> httpx.Response:
    body = {"kind": kind, "content_type": content_type or ("video/mp4" if kind == "video" else "image/jpeg"),
            "size_bytes": size if size is not None else (len(VIDEO_BYTES) if kind == "video" else len(JPEG_BYTES))}
    if kind == "video" and duration is not None:
        body["duration_sec"] = duration
    return call("POST", "/v1/uploads", acct["token"], json=body)


def put_object(upload: dict, data: bytes, headers: dict | None = None) -> httpx.Response:
    return raw.put(upload["url"], content=data, headers=headers if headers is not None else upload["headers"])


def uploaded(acct, kind="video", data=None) -> dict:
    r = presign(acct, kind)
    if r.status_code != 201:
        check(f"presign {kind}", False, r, "expected 201")
        raise SystemExit("presign failed")
    up = r.json()
    p = put_object(up, data if data is not None else (VIDEO_BYTES if kind == "video" else JPEG_BYTES))
    if p.status_code not in (200, 204):
        check(f"PUT {kind} to storage", False, None, f"storage returned {p.status_code}: {p.text[:300]}")
        raise SystemExit("storage PUT failed")
    return up


def marks(**over):
    m = {"contact_frame": 80, "contact_offset": 0, "contact_source": "detected", "stride_start_frame": 30,
         "stride_end_frame": 60, "pitcher_direction": {"from": [0.3, 0.5], "to": [0.7, 0.5]}}
    m.update(over)
    return m


def session_body(video_id, thumb_id=None, mode="h", is_self=True, athlete=None, **over):
    b = {"video_upload_id": video_id, "thumbnail_upload_id": thumb_id, "mode": mode, "is_self": is_self,
         "athlete": athlete, "duration_sec": 3.0, "fps": 30, "marks": marks()}
    b.update(over)
    return b


def new_session(acct, name, mode="h", is_self=True, athlete=None, with_thumb=True, expect=201) -> dict | None:
    v = uploaded(acct, "video")
    t = uploaded(acct, "thumbnail") if with_thumb else None
    r = call("POST", "/v1/sessions", acct["token"],
             json=session_body(v["upload_id"], t["upload_id"] if t else None, mode, is_self, athlete))
    if not check(f"create session {name}", r.status_code == expect, r, f"expected {expect}"):
        return None
    s = r.json()["session"]
    s["_video_upload"] = v
    return s


# ---------------------------------------------------------------- ML payload

BASE_PAYLOAD = {
    "schema_version": "1.0",
    "analysis_id": "analysis_001",
    "analysis_revision": 1,
    "swing_id": "swing_001",
    "status": "completed",
    "athlete": {"athlete_id": "player_001", "batting_hand": "right", "lead_foot": "left", "age_years": None,
                "height_cm": None},
    "context": {"sport": "baseball", "practice_type": "tee"},
    "measurement_definitions_version": "1.0",
    "events": {
        "stride_start": {"video_time_s": 1.0, "capture_time_s": 1.0, "status": "available", "source": "manual_review"},
        "front_foot_down": {"video_time_s": 1.2, "capture_time_s": 1.2, "status": "available",
                            "source": "manual_review"},
        "contact": {"video_time_s": None, "capture_time_s": None, "status": "unavailable", "source": None,
                    "reasons": ["contact_not_verified"]},
    },
    "measurements": [
        {"metric_id": "hip_shoulder_separation_at_foot_down", "group": "stride", "value": 28, "unit": "deg",
         "event_id": "front_foot_down", "reference": "signed_horizontal_shoulder_minus_hip_heading",
         "status": "available", "confidence": None, "uses_interpolated_input": False, "reasons": [],
         "benchmark": None},
        {"metric_id": "stride_relative_length", "group": "stride", "value": 24, "unit": "cm",
         "start_event_id": "stride_start", "end_event_id": "front_foot_down",
         "reference": "lead_ankle_displacement_relative_to_rear_ankle", "status": "limited", "confidence": None,
         "uses_interpolated_input": False, "reasons": ["scale_is_model_estimated"], "benchmark": None},
        {"metric_id": "hip_shoulder_separation_at_contact", "group": "contact_follow_through", "value": None,
         "unit": "deg", "event_id": "contact", "reference": "signed_horizontal_shoulder_minus_hip_heading",
         "status": "unavailable", "confidence": None, "uses_interpolated_input": False,
         "reasons": ["contact_not_verified"], "benchmark": None},
    ],
}


def payload(sep=3, analysis_id=None, rev=1, hand="right", lead="left", stride=24):
    p = copy.deepcopy(BASE_PAYLOAD)
    p["analysis_id"] = analysis_id or f"analysis-{RUN_ID}-{uuid.uuid4().hex[:6]}"
    p["analysis_revision"] = rev
    p["athlete"]["batting_hand"] = hand
    p["athlete"]["lead_foot"] = lead
    p["measurements"][0]["value"] = sep
    p["measurements"][1]["value"] = stride
    return p


def post_report(acct, sid, body, **kw) -> httpx.Response:
    return call("POST", f"/v1/sessions/{sid}/swing-report?queue=false", acct["token"], json=body, **kw)


TOP_KEYS = {"schema_version", "analysis_id", "analysis_revision", "overall_score", "overall_score_is_tentative",
            "overview", "groups", "focus_area", "measurements", "data_quality", "meta"}
GROUP_ORDER = ["balance_load", "stride", "power_move", "contact_follow_through"]


def rating_for(score):
    if score is None:
        return "not_rated"
    if score == 100:
        return "on_target"
    if score >= 70:
        return "satisfactory"
    return "off_target"


def text_fields(rep: dict):
    """(path, text) for every prose field that must contain no digits."""
    yield "overview.headline", rep["overview"].get("headline")
    for g in rep["groups"]:
        yield f"groups.{g['group']}.summary", g.get("summary")
        yield f"groups.{g['group']}.rating_label", g.get("rating_label")
        yield f"groups.{g['group']}.display_name", g.get("display_name")
    fa = rep.get("focus_area")
    if fa:
        for k in ("coach_message", "practice_feel", "display_name", "rating_label"):
            yield f"focus_area.{k}", fa.get(k)
        if fa.get("drill"):
            for k in ("name", "how", "cue"):
                yield f"focus_area.drill.{k}", fa["drill"].get(k)
    for m in rep["measurements"]:
        for k in ("display_name", "what_it_means", "result_text", "coach_tip", "rating_label"):
            yield f"measurements.{m['metric_id']}.{k}", m.get(k)
        for lim in m.get("limitations") or []:
            yield f"measurements.{m['metric_id']}.limitations.{lim.get('code')}", lim.get("text")
    for dq in rep.get("data_quality") or []:
        yield f"data_quality.{dq.get('code')}", dq.get("text")


def check_report_shape(name: str, r: httpx.Response) -> dict | None:
    if not check(f"{name}: 200", r.status_code == 200, r, "expected 200"):
        return None
    rep = r.json()
    check(f"{name}: exact top-level keys", set(rep) == TOP_KEYS, r,
          f"extra={set(rep) - TOP_KEYS} missing={TOP_KEYS - set(rep)}")
    groups = rep.get("groups") or []
    check(f"{name}: 4 groups in fixed order", [g.get("group") for g in groups] == GROUP_ORDER, r,
          f"got {[g.get('group') for g in groups]}")
    ms = rep.get("measurements") or []
    check(f"{name}: 3 measurements", len(ms) == 3 and len({m["metric_id"] for m in ms}) == 3, r)
    by_id = {m["metric_id"]: m for m in ms}
    for m in ms:
        check(f"{name}: measurement {m['metric_id']} rating matches score ({m.get('score')} -> {m.get('rating')})",
              m.get("rating") == rating_for(m.get("score")), r)
        if m["status"] == "unavailable":
            check(f"{name}: unavailable {m['metric_id']} is not_rated with null score/value/display_value",
                  m["rating"] == "not_rated" and m["score"] is None and m["value"] is None
                  and m["display_value"] is None and m["not_rated_reason"] == "measurement_unavailable", r)
        if m["status"] == "limited":
            check(f"{name}: limited {m['metric_id']} tentative with limitation text",
                  m.get("rating_is_tentative") is True and bool(m.get("limitations"))
                  and all(lim.get("text") for lim in m["limitations"]), r)
        if m.get("score") is not None:
            b = m.get("benchmark") or {}
            check(f"{name}: rated {m['metric_id']} has benchmark population",
                  bool(b.get("population")) and "on_target" in b and "satisfactory" in b, r, json.dumps(b))
    # group score = mean of every rated measurement score; limited ones count but mark the score tentative
    group_scores, tentative_groups = [], []
    for g in groups:
        members = [by_id[mid] for mid in g.get("metric_ids", []) if mid in by_id]
        rated = [m for m in members if m["score"] is not None]
        scores = [m["score"] for m in rated]
        expected = None if not scores else int(sum(scores) / len(scores) + 0.5)
        if expected is not None and expected == 100 and any(x < 100 for x in scores):
            expected = 99
        label = f"{name}: group {g['group']} score = mean of rated (expected {expected}, got {g.get('score')})"
        check(label, g.get("score") == expected, r)
        tentative = any(m.get("rating_is_tentative") for m in rated)
        check(f"{name}: group {g['group']} score_is_tentative = {tentative}",
              g.get("score_is_tentative") is tentative, r)
        check(f"{name}: group {g['group']} rating matches score", g.get("rating") == rating_for(g.get("score")), r)
        if g.get("score") is not None:
            group_scores.append(g["score"])
            tentative_groups.append(tentative)
    exp_overall = None if not group_scores else int(sum(group_scores) / len(group_scores) + 0.5)
    if exp_overall == 100 and any(x < 100 for x in group_scores):
        exp_overall = 99
    check(f"{name}: overall_score = mean of group scores ({exp_overall})", rep.get("overall_score") == exp_overall,
          r, f"got {rep.get('overall_score')}")
    check(f"{name}: overall_score_is_tentative", rep.get("overall_score_is_tentative") is any(tentative_groups), r)
    fa = rep.get("focus_area")
    check(f"{name}: focus area always present with a drill", bool(fa and (fa.get("drill") or {}).get("drill_id")), r)
    if fa:
        kind = fa.get("kind")
        fm = by_id.get(fa.get("metric_id"), {})
        if kind == "fix":
            needs_work = [m for m in ms if m.get("rating") in ("off_target", "satisfactory")]
            exact_needs_work = [m for m in needs_work if not m.get("rating_is_tentative")]
            check(f"{name}: fix focus is a non-on-target measurement, exact results first",
                  fm.get("rating") in ("off_target", "satisfactory")
                  and (not exact_needs_work or not fm.get("rating_is_tentative")), r,
                  f"focus={fa.get('metric_id')} rating={fm.get('rating')} tentative={fm.get('rating_is_tentative')}")
        elif kind == "maintain":
            check(f"{name}: maintain focus only when every rated result is on target",
                  fm.get("rating") == "on_target" and all(m.get("rating") in ("on_target", "not_rated") for m in ms), r)
        elif kind == "general":
            check(f"{name}: general focus only when nothing is rated",
                  fa.get("metric_id") is None and all(m.get("rating") == "not_rated" for m in ms), r)
        else:
            check(f"{name}: focus kind is fix, maintain or general", False, r, f"kind={kind}")
        check(f"{name}: focus is_tentative matches its measurement",
              fa.get("is_tentative") is bool(fm.get("rating_is_tentative")), r)
        if fa.get("metric_id"):
            check(f"{name}: focus evidence cites its metric",
                  fa.get("metric_id") in (fa.get("evidence_metric_ids") or []), r)
    bad = [(p, t) for p, t in text_fields(rep) if isinstance(t, str) and re.search(r"\d", t)]
    check(f"{name}: no digits in text fields", not bad, r, f"digits in {bad}")
    return rep


# ---------------------------------------------------------------- the suite

def run():
    today = date.today()
    # ------------------------------------------------------------ accounts
    A = register()
    set_profile(A, name="QA Alpha", age=20, height_cm=183, weight_kg=85, bats="R", throws="R", level="college")
    B = register()
    set_profile(B, name="QA Bravo", age=17, height_cm=175, weight_kg=70, bats="L", throws="L", level="college")
    C = register()  # fresh plan budget for idempotency, delete and the hand-fallback report
    set_profile(C, name="QA Charlie", age=16, height_cm=170, weight_kg=65, bats="L", throws="L", level="high_school")

    r = call("GET", "/v1/me", A["token"])
    ent0 = r.json().get("entitlement", {}) if r.status_code == 200 else {}
    check("GET /me entitlement starts free 20/0", ent0.get("plan") == "free" and ent0.get("weekly_limit") == 20
          and ent0.get("used_this_week") == 0 and ent0.get("left") == 20, r, json.dumps(ent0))

    # ------------------------------------------------------------ 1. uploads
    r = presign(A, "video")
    check("presign video 201 with url, headers, expires_at", r.status_code == 201 and {"upload_id", "url", "headers",
          "expires_at"} <= set(r.json()), r)
    vid = r.json()
    p = put_object(vid, VIDEO_BYTES)
    check(f"real PUT of video to Spaces succeeds ({p.status_code})", p.status_code in (200, 204), None,
          p.text[:300])
    r = presign(A, "thumbnail")
    check("presign thumbnail 201", r.status_code == 201, r)
    thumb = r.json()
    p = put_object(thumb, JPEG_BYTES)
    check(f"real PUT of thumbnail to Spaces succeeds ({p.status_code})", p.status_code in (200, 204), None,
          p.text[:300])
    r = presign(A, "video", content_type="video/quicktime")
    check("presign video/quicktime accepted (iOS .mov)", r.status_code == 201, r)
    expect_error("presign video with image/jpeg -> 400", presign(A, "video", content_type="image/jpeg"), 400,
                 "VALIDATION", "content_type")
    expect_error("presign thumbnail with image/png -> 400", presign(A, "thumbnail", content_type="image/png"), 400,
                 "VALIDATION", "content_type")
    expect_error("presign video 251 MB -> 413 TOO_LARGE", presign(A, "video", size=251 * 1024 * 1024), 413, "TOO_LARGE")
    expect_error("presign thumbnail 6 MB -> 413 TOO_LARGE", presign(A, "thumbnail", size=6 * 1024 * 1024), 413,
                 "TOO_LARGE")
    expect_error("presign video 61 s -> 400", presign(A, "video", duration=61), 400, "VALIDATION", "duration_sec")
    expect_error("presign video without duration -> 400", presign(A, "video", duration=None), 400, "VALIDATION")
    expect_error("presign size 0 -> 400", presign(A, "video", size=0), 400, "VALIDATION")
    r = call("POST", "/v1/uploads", A["token"], json={"kind": "video", "contentType": "video/mp4", "bytes": 10,
                                                      "durationSec": 2})
    expect_error("presign with camelCase (unknown) fields -> 400", r, 400, "VALIDATION")
    expect_error("presign without auth -> 401", call("POST", "/v1/uploads", json={"kind": "video"}), 401,
                 "UNAUTHENTICATED")
    # signed content type mismatch on PUT
    up = presign(A, "video").json()
    p = put_object(up, JPEG_BYTES, {"Content-Type": "image/jpeg"})
    check(f"storage refuses PUT whose Content-Type differs from the signed one ({p.status_code})",
          p.status_code in (400, 403), None, p.text[:200])

    # ------------------------------------------------------------ 2. sessions
    body = session_body(vid["upload_id"], thumb["upload_id"])
    r = call("POST", "/v1/sessions", A["token"], json=body)
    S1 = None
    if check("create self session 201", r.status_code == 201, r):
        S1 = r.json()["session"]
        check("new session status pending, report null, analyzed_at null",
              S1["status"] == "pending" and S1["report"] is None and S1["analyzed_at"] is None, r)
        check("athlete snapshot = profile", S1["athlete"] == {"name": "QA Alpha", "age": 20, "height_cm": 183.0,
              "weight_kg": 85.0, "bats": "R", "throws": "R", "level": "college"}, r, json.dumps(S1["athlete"]))
        check("first session ordinal 1, previous null", S1["ordinal"] == 1 and S1["previous"] is None, r)
        check("marks echoed with from/to", S1["marks"].get("pitcher_direction", {}).get("from") == [0.3, 0.5], r,
              json.dumps(S1["marks"]))
        g = raw.get(S1["media"]["video_url"])
        check("video_url downloads the exact uploaded bytes", g.status_code == 200 and g.content == VIDEO_BYTES, None,
              f"status {g.status_code}, len {len(g.content)}")
        g = raw.get(S1["media"]["thumbnail_url"])
        check("thumbnail_url downloads the exact uploaded bytes", g.status_code == 200 and g.content == JPEG_BYTES,
              None, f"status {g.status_code}")
        exp = datetime.fromisoformat(S1["media"]["expires_at"].replace("Z", "+00:00"))
        check("media URLs live at least ~1 hour", exp - datetime.now(UTC) > timedelta(minutes=55), r)
        A["video_url"] = S1["media"]["video_url"]
    # reuse attached upload
    expect_error("reuse of an attached upload -> 400",
                 call("POST", "/v1/sessions", A["token"], json=body), 400, "VALIDATION", "video_upload_id")
    # thumbnail id used as video
    t2 = uploaded(A, "thumbnail")
    expect_error("thumbnail upload used as video_upload_id -> 400",
                 call("POST", "/v1/sessions", A["token"], json=session_body(t2["upload_id"])), 400, "VALIDATION",
                 "video_upload_id")
    # other user's upload
    vb = uploaded(B, "video")
    expect_error("another user's upload id -> 400",
                 call("POST", "/v1/sessions", A["token"], json=session_body(vb["upload_id"])), 400, "VALIDATION",
                 "video_upload_id")
    # upload never PUT
    nv = presign(A, "video").json()
    expect_error("upload not uploaded -> 422 UPLOAD_MISSING",
                 call("POST", "/v1/sessions", A["token"], json=session_body(nv["upload_id"])), 422, "UPLOAD_MISSING")
    # JPEG bytes PUT to the video URL with the signed video/mp4 header: storage cannot tell; backend checks headers only
    jv = presign(A, "video").json()
    put_object(jv, JPEG_BYTES)
    r = call("POST", "/v1/sessions", A["token"], json=session_body(jv["upload_id"]))
    if r.status_code == 201:
        note("A JPEG body PUT to a video upload with the signed 'video/mp4' header is accepted as a session video "
             "(201). The backend validates the stored Content-Type and size only (HEAD), not the file bytes "
             "(app/modules/sessions/service.py _verify_object). A different Content-Type cannot be stored because "
             "it is part of the presigned signature. Session created; it counts as pending only.")
        JUNK_SESSION = r.json()["session"]["id"]
        call("DELETE", f"/v1/sessions/{JUNK_SESSION}", A["token"])
    else:
        note(f"JPEG bytes in a video upload: POST /v1/sessions -> {r.status_code} {err_code(r)}")

    # mark validation (runs before any upload lookup, so a random upload id is fine)
    rid = str(uuid.uuid4())
    cases = [
        ("stride start after stride end", dict(marks=marks(stride_start_frame=60, stride_end_frame=40)),
         "marks.stride_end_frame"),
        ("stride end after contact", dict(marks=marks(stride_end_frame=85, contact_frame=80)), "marks.contact_frame"),
        ("contact frame beyond the last frame", dict(marks=marks(contact_frame=90)), "marks.contact_frame"),
        ("negative stride start", dict(marks=marks(stride_start_frame=-1)), "marks.stride_start_frame"),
        ("pitcher_direction too short", dict(marks=marks(pitcher_direction={"from": [0.5, 0.5], "to": [0.55, 0.5]})),
         "marks.pitcher_direction"),
        ("pitcher_direction point out of 0..1", dict(marks=marks(pitcher_direction={"from": [0.1, 0.5],
                                                                                    "to": [1.5, 0.5]})),
         "marks.pitcher_direction"),
        ("pitcher_direction negative", dict(marks=marks(pitcher_direction={"from": [-0.1, 0.5], "to": [0.7, 0.5]})),
         "marks.pitcher_direction"),
        ("contact_source invalid", dict(marks=marks(contact_source="audio")), "marks.contact_source"),
        ("mode x", dict(mode="x"), "mode"),
        ("duration 61 s", dict(duration_sec=61), "duration_sec"),
        ("self with an athlete", dict(athlete={"name": "Some One", "age": 15, "height_cm": 170, "weight_kg": 60,
                                               "bats": "R", "throws": "R", "level": "high_school"}), "athlete"),
        ("someone else without athlete", dict(is_self=False), "athlete"),
        ("someone else athlete missing weight", dict(is_self=False, athlete={"name": "Some One", "age": 15,
                                                                            "height_cm": 170, "bats": "R",
                                                                            "throws": "R", "level": "college"}),
         "athlete.weight_kg"),
        ("unknown field", dict(extra_field=1), "extra_field"),
    ]
    for label, over, field in cases:
        b = session_body(rid)
        b.update(over)
        expect_error(f"session marks: {label} -> 400 with field {field}",
                     call("POST", "/v1/sessions", A["token"], json=b), 400, "VALIDATION", field)

    # ------------------------------------------------------------ 3. swing report: spec example
    rep1 = None
    if S1:
        p1 = payload(sep=3, analysis_id=f"analysis-{RUN_ID}-s1", rev=1)
        r = post_report(A, S1["id"], p1)
        rep1 = check_report_shape("spec example (R college, sep 3)", r)
        if rep1:
            by = {m["metric_id"]: m for m in rep1["measurements"]}
            sep, stride, contact = (by["hip_shoulder_separation_at_foot_down"], by["stride_relative_length"],
                                    by["hip_shoulder_separation_at_contact"])
            check("spec: separation score 55 off_target", sep["score"] == 55 and sep["rating"] == "off_target", r,
                  json.dumps({k: sep.get(k) for k in ("score", "rating")}))
            check("spec: separation display_value '3°'", sep["display_value"] == "3°", r, sep["display_value"])
            check("spec: separation benchmark right/college",
                  (sep.get("benchmark") or {}).get("benchmark_id")
                  == "obp-contract-v1.hip_shoulder_separation_at_foot_down.right.college"
                  and sep["benchmark"].get("on_target") == {"lower": -25.3, "upper": -8.5}, r,
                  json.dumps(sep.get("benchmark")))
            check("spec: stride 24 limited -> score 100 on_target tentative",
                  stride["score"] == 100 and stride["rating"] == "on_target" and stride["rating_is_tentative"] is True,
                  r, json.dumps({k: stride.get(k) for k in ("score", "rating", "rating_is_tentative")}))
            check("spec: contact unavailable -> not_rated", contact["rating"] == "not_rated", r)
            check("spec: overall_score 78 tentative (stride length is an estimate)",
                  rep1["overall_score"] == 78 and rep1["overall_score_is_tentative"] is True, r,
                  str(rep1["overall_score"]))
            g = {x["group"]: x for x in rep1["groups"]}
            check("spec: stride group 78 satisfactory tentative", g["stride"]["score"] == 78 and
                  g["stride"]["rating"] == "satisfactory" and g["stride"]["score_is_tentative"] is True, r)
            check("spec: balance_load not_rated no_measurements_available",
                  g["balance_load"]["not_rated_reason"] == "no_measurements_available"
                  and g["balance_load"]["metric_ids"] == [], r)
            check("spec: contact group not_rated measurements_unavailable",
                  g["contact_follow_through"]["not_rated_reason"] == "measurements_unavailable", r)
            fa = rep1.get("focus_area") or {}
            check("spec: fix focus hip_shoulder_separation_at_foot_down with drill hit_13",
                  fa.get("kind") == "fix" and fa.get("metric_id") == "hip_shoulder_separation_at_foot_down"
                  and (fa.get("drill") or {}).get("drill_id") == "hit_13", r, json.dumps(fa)[:300])
            check("spec: analysis_id/revision echoed", rep1["analysis_id"] == p1["analysis_id"]
                  and rep1["analysis_revision"] == 1, r)
            check("spec: data_quality has contact_not_verified and scale_is_model_estimated",
                  {"contact_not_verified", "scale_is_model_estimated"} <= {d["code"] for d in rep1["data_quality"]},
                  r)
            check("meta has generated_at, text_source, versions",
                  all(k in rep1["meta"] for k in ("generated_at", "text_source", "input_schema_version",
                                                  "benchmark_registry_version", "coaching_rules_version")), r)
            print(f"      (meta.text_source={rep1['meta'].get('text_source')}, model={rep1['meta'].get('model')}, "
                  f"fallback_reason={rep1['meta'].get('fallback_reason')})")

        # same id+rev -> identical report, no rebuild
        r = post_report(A, S1["id"], p1)
        check("same analysis_id+revision -> identical stored report (generated_at unchanged)",
              r.status_code == 200 and r.json() == rep1, r)
        # same id+rev with a different body -> stored report (documented)
        p1b = copy.deepcopy(p1)
        p1b["measurements"][0]["value"] = -15
        r = post_report(A, S1["id"], p1b)
        check("same id+revision with different values -> still the stored report", r.status_code == 200
              and r.json() == rep1, r)
        # revision 2 -> rebuilt
        p2 = copy.deepcopy(p1)
        p2["analysis_revision"] = 2
        p2["measurements"][0]["value"] = -15  # inside on-target
        r = post_report(A, S1["id"], p2)
        rep1v2 = check_report_shape("revision 2 rebuild", r)
        if rep1v2 and rep1:
            check("revision 2 rebuilt (revision 2, new generated_at, separation now on_target)",
                  rep1v2["analysis_revision"] == 2 and rep1v2["meta"]["generated_at"] != rep1["meta"]["generated_at"]
                  and rep1v2["measurements"][0]["rating"] == "on_target", r)
            check("all rated on target -> maintain focus with a drill and a headline",
                  (rep1v2["focus_area"] or {}).get("kind") == "maintain"
                  and bool(rep1v2["focus_area"]["drill"]["drill_id"]) and bool(rep1v2["overview"]["headline"]), r)
            rep1 = rep1v2
        expect_error("revision 1 after 2 -> 409 STALE_REVISION", post_report(A, S1["id"], p1), 409, "STALE_REVISION")
        p_other = copy.deepcopy(p2)
        p_other["analysis_id"] = f"analysis-{RUN_ID}-other"
        expect_error("different analysis_id -> 409 ANALYSIS_MISMATCH", post_report(A, S1["id"], p_other), 409,
                     "ANALYSIS_MISMATCH")
        r = call("GET", f"/v1/sessions/{S1['id']}", A["token"])
        if check("GET session after report 200", r.status_code == 200, r):
            s = r.json()["session"]
            check("GET session: status done, analyzed_at set", s["status"] == "done" and s["analyzed_at"], r)
            check("GET session: report equals the latest H1 response", s["report"] == rep1, r)
            check("GET session: measurement_payload not exposed", "measurement_payload" not in s, r)
        r = call("GET", "/v1/me", A["token"])
        ent = r.json().get("entitlement", {})
        check("entitlement used 1 after first report (re-posts and revisions do not count again)",
              ent.get("used_this_week") == 1 and ent.get("left") == 2, r, json.dumps(ent))

    # ------------------------------------------------------------ more sessions on A
    S_else = new_session(A, "someone else's (Kid Brother)", is_self=False, athlete={
        "name": "Kid Brother", "age": 12, "height_cm": 150, "weight_kg": 40, "bats": "L", "throws": "L",
        "level": "youth"})
    if S_else:
        check("someone-else snapshot = provided athlete", S_else["athlete"]["name"] == "Kid Brother"
              and S_else["athlete"]["bats"] == "L" and S_else["is_self"] is False, None, json.dumps(S_else["athlete"]))
    S_p = new_session(A, "pitching self", mode="p")
    if S_p:
        expect_error("pitching session report -> 422 MODE_NOT_SUPPORTED", post_report(A, S_p["id"], payload()), 422,
                     "MODE_NOT_SUPPORTED")

    # invalid payloads (on a pending session, so nothing is ever counted)
    if S_else:
        def mutate(fn):
            p = payload()
            fn(p)
            return p

        bad = [
            ("schema_version 2.0", lambda p: p.update(schema_version="2.0"), "schema_version"),
            ("measurement_definitions_version 2.0", lambda p: p.update(measurement_definitions_version="2.0"),
             "measurement_definitions_version"),
            ("missing metric", lambda p: p["measurements"].pop(2), "measurements"),
            ("duplicate metric", lambda p: p["measurements"].__setitem__(2, copy.deepcopy(p["measurements"][0])),
             "measurements"),
            ("available with null value", lambda p: p["measurements"][0].update(value=None), "measurements[0]"),
            ("limited without reasons", lambda p: p["measurements"][1].update(reasons=[]), "measurements[1]"),
            ("unavailable with a value", lambda p: p["measurements"][2].update(value=5), "measurements[2]"),
            ("stride end before start", lambda p: p["events"]["stride_start"].update(video_time_s=1.3),
             "events.stride_start"),
            ("pose_estimated contact source", lambda p: p["events"].__setitem__("contact", {
                "video_time_s": 1.4, "capture_time_s": 1.4, "status": "available", "source": "pose_estimated"}),
             "events.contact"),
            ("separation 180", lambda p: p["measurements"][0].update(value=180), "measurements[0]"),
            ("negative stride", lambda p: p["measurements"][1].update(value=-1), "measurements[1]"),
            ("revision 0", lambda p: p.update(analysis_revision=0), "analysis_revision"),
            ("empty analysis_id", lambda p: p.update(analysis_id=""), "analysis_id"),
            ("missing contact event", lambda p: p["events"].pop("contact"), "events"),
            ("wrong unit", lambda p: p["measurements"][0].update(unit="cm"), "measurements[0]"),
            ("unregistered reason", lambda p: p["measurements"][1].update(reasons=["made_up"]), "measurements[1]"),
            ("confidence 2", lambda p: p["measurements"][0].update(confidence=2), "measurements[0]"),
            ("bat_ball_detector on stride_start", lambda p: p["events"]["stride_start"].update(
                source="bat_ball_detector"), "events.stride_start"),
            ("benchmark lower > upper", lambda p: p["measurements"][0].update(benchmark={
                "benchmark_id": "x", "version": "1", "kind": "reference_interval", "lower": 10, "upper": 0,
                "unit": "deg", "source_reference": "x"}), "measurements[0]"),
        ]
        for label, fn, field in bad:
            expect_error(f"invalid payload: {label} -> 422 INVALID_PAYLOAD", post_report(A, S_else["id"], mutate(fn)),
                         422, "INVALID_PAYLOAD", field)
        r = call("POST", f"/v1/sessions/{S_else['id']}/swing-report", A["token"], json=[1, 2])
        expect_error("invalid payload: JSON array body -> 422 INVALID_PAYLOAD", r, 422, "INVALID_PAYLOAD")
        r = call("POST", f"/v1/sessions/{S_else['id']}/swing-report", A["token"], content=b"{not json",
                 headers={"Content-Type": "application/json"})
        check(f"invalid payload: malformed JSON -> 4xx (got {r.status_code})", 400 <= r.status_code < 500, r)
        big = payload()
        big["swing_id"] = "x" * (300 * 1024)
        expect_error("payload over 256 KB -> 413 TOO_LARGE", post_report(A, S_else["id"], big), 413, "TOO_LARGE")
        r = call("GET", f"/v1/sessions/{S_else['id']}", A["token"])
        check("invalid payloads left the session pending", r.status_code == 200 and
              r.json()["session"]["status"] == "pending", r)

    # B cannot touch A's sessions; unknown ids
    if S1:
        expect_error("other user's session report -> 403", post_report(B, S1["id"], payload()), 403, "FORBIDDEN")
        expect_error("other user's GET session -> 403", call("GET", f"/v1/sessions/{S1['id']}", B["token"]), 403,
                     "FORBIDDEN")
        expect_error("other user's DELETE session -> 403", call("DELETE", f"/v1/sessions/{S1['id']}", B["token"]), 403,
                     "FORBIDDEN")
    unknown = str(uuid.uuid4())
    expect_error("unknown session report -> 404", post_report(A, unknown, payload()), 404, "NOT_FOUND")
    expect_error("unknown GET session -> 404", call("GET", f"/v1/sessions/{unknown}", A["token"]), 404, "NOT_FOUND")
    expect_error("report without auth -> 401", call("POST", f"/v1/sessions/{unknown}/swing-report", json={}), 401,
                 "UNAUTHENTICATED")
    r = call("GET", "/v1/sessions/not-a-uuid", A["token"])
    check(f"malformed session id -> 400/404/422 (got {r.status_code})", r.status_code in (400, 404, 422), r)

    # ------------------------------------------------------------ 4. ordinal/previous across 3 analysed sessions
    S2 = new_session(A, "self #2")
    S3 = None
    rep2 = rep3 = None
    if S2:
        check("S2 ordinal 2 and previous = S1 (analysed)", S2["ordinal"] == 2 and S2["previous"]
              and S2["previous"]["id"] == S1["id"] and S2["previous"]["overall_score"] == rep1["overall_score"], None,
              json.dumps({"ordinal": S2["ordinal"], "previous": S2["previous"]}))
        r = post_report(A, S2["id"], payload(sep=-30))  # satisfactory band
        rep2 = check_report_shape("S2 report (sep -30, satisfactory)", r)
        if rep2:
            sep = rep2["measurements"][0]
            check(f"S2 separation -30 satisfactory (score {sep['score']})", sep["rating"] == "satisfactory", r)
    # pending session not analysed does not count: S_else and S_p exist pending
    S3 = new_session(A, "self #3")
    if S3:
        r = post_report(A, S3["id"], payload(sep=10))
        rep3 = check_report_shape("S3 report (sep 10)", r)
        r = call("GET", f"/v1/sessions/{S3['id']}", A["token"])
        if r.status_code == 200:
            s = r.json()["session"]
            # self sessions for "QA Alpha" in mode h: S1, S2, S3 (S_p is pitching, S_else other athlete)
            check("S3 ordinal 3 ('Swing 3')", s["ordinal"] == 3, r, f"ordinal={s['ordinal']}")
            check("S3 previous = S2 with S2's score", s["previous"] and s["previous"]["id"] == S2["id"]
                  and s["previous"]["overall_score"] == rep2["overall_score"], r, json.dumps(s["previous"]))
            check("S3 report equals H1 response", s["report"] == rep3, r)

    # ------------------------------------------------------------ 6. plan limit
    r = call("GET", "/v1/me", A["token"])
    ent = r.json().get("entitlement", {})
    check("entitlement used 3, left 17 (pending sessions S_else, S_p not counted)",
          ent.get("used_this_week") == 3 and ent.get("left") == 17, r, json.dumps(ent))
    r = call("GET", "/v1/me/entitlement", A["token"])
    check("GET /me/entitlement matches", r.status_code == 200 and (r.json().get("entitlement", r.json()).get("left")
                                                                   == 17), r)
    if S1:
        r = post_report(A, S1["id"], payload(sep=-15, analysis_id=rep1["analysis_id"], rev=3))
        check("a new revision on an already analysed session works", r.status_code == 200, r)
        if r.status_code == 200:
            rep1 = r.json()

    # The limit itself runs on its own account, so A's sessions stay as the list checks below expect.
    L = register()
    set_profile(L, name="QA Limit", age=20, height_cm=183, weight_kg=85, bats="R", throws="R", level="college")
    L_pending = new_session(L, "limit: pending, created before the limit", with_thumb=False)
    L_first, L_first_rep, analysed = None, None, 0
    for i in range(1, 21):
        s = new_session(L, f"limit: analysed #{i}", with_thumb=False)
        r = post_report(L, s["id"], payload()) if s else None
        if r is not None and r.status_code == 200:
            analysed += 1
            if L_first is None:
                L_first, L_first_rep = s, r.json()
    check("20 analyses in a week are allowed on free", analysed == 20, None, f"analysed={analysed}")
    r = call("GET", "/v1/me/entitlement", L["token"])
    ent = r.json().get("entitlement", r.json()) if r.status_code == 200 else {}
    check("entitlement used 20, left 0 (the pending session is not counted)", ent.get("weekly_limit") == 20
          and ent.get("used_this_week") == 20 and ent.get("left") == 0, r, json.dumps(ent))
    v21 = uploaded(L, "video")
    r = call("POST", "/v1/sessions", L["token"], json=session_body(v21["upload_id"]))
    expect_error("21st session in a week on free -> 402 PLAN_LIMIT", r, 402, "PLAN_LIMIT")
    check("402 message is the app's text", (r.json().get("error") or {}).get("message")
          == "The free plan includes 20 analyses a week.", r)
    if L_pending:
        expect_error("reporting a pending session after the limit -> 402 PLAN_LIMIT",
                     post_report(L, L_pending["id"], payload()), 402, "PLAN_LIMIT")
    if L_first:
        r = post_report(L, L_first["id"], payload(sep=-15, analysis_id=L_first_rep["analysis_id"], rev=2))
        check("a new revision on an already analysed session still works at the limit", r.status_code == 200, r)

    # ------------------------------------------------------------ left-handed hitter (B, someone else's swing)
    LB = new_session(B, "B someone else, left-handed college", is_self=False, athlete={
        "name": "Lefty Lou", "age": 20, "height_cm": 180, "weight_kg": 80, "bats": "L", "throws": "L",
        "level": "college"})
    if LB:
        r = post_report(B, LB["id"], payload(sep=17, hand="left", lead="right", stride=30))
        repL = check_report_shape("left-handed college (sep +17)", r)
        if repL:
            sep = repL["measurements"][0]
            check("left-handed +17 deg -> on_target 100 against left/college ranges",
                  sep["score"] == 100 and sep["rating"] == "on_target"
                  and "left" in (sep.get("benchmark") or {}).get("benchmark_id", ""), r,
                  json.dumps({"score": sep["score"], "benchmark": sep.get("benchmark")}))
        # left-handed but separation in the right-handed range -> off target
        LB2 = new_session(B, "B someone else, left-handed #2", is_self=False, athlete={
            "name": "Lefty Lou", "age": 20, "height_cm": 180, "weight_kg": 80, "bats": "L", "throws": "L",
            "level": "college"})
        if LB2:
            r = post_report(B, LB2["id"], payload(sep=-20, hand="left", lead="right", stride=30))
            repL2 = check_report_shape("left-handed college (sep -20)", r)
            if repL2:
                check("left-handed -20 deg -> off_target", repL2["measurements"][0]["rating"] == "off_target", r)
            r = call("GET", f"/v1/sessions/{LB2['id']}", B["token"])
            check("Lefty Lou #2: ordinal 2, previous = #1", r.status_code == 200 and r.json()["session"]["ordinal"] == 2
                  and (r.json()["session"]["previous"] or {}).get("id") == LB["id"], r)
    # B: high-school self session, unknown hand fallback via profile bats=L when payload batting_hand null
    BS = new_session(C, "C self high school, hand from profile")
    if BS:
        p = payload(sep=17, hand="right", lead="right")
        p["athlete"]["batting_hand"] = None
        r = post_report(C, BS["id"], p)
        repB = check_report_shape("hand fallback to profile bats=L, high school", r)
        if repB:
            bid = (repB["measurements"][0].get("benchmark") or {}).get("benchmark_id", "")
            codes = {d["code"] for d in repB["data_quality"]}
            check("left high school falls back to left college with population_fallback note",
                  bid.endswith("left.college") and "population_fallback" in codes, r, f"{bid} {codes}")

    # ------------------------------------------------------------ 5. list
    r = call("GET", "/v1/sessions", A["token"])
    if check("GET /v1/sessions 200", r.status_code == 200, r):
        items = r.json()["items"]
        ids = [i["id"] for i in items]
        expected = {s["id"] for s in (S1, S2, S3, S_else, S_p) if s}
        check(f"list has all {len(expected)} live sessions of A", set(ids) == expected, r, f"got {ids}")
        it1 = next((i for i in items if S1 and i["id"] == S1["id"]), None)
        it2 = next((i for i in items if S2 and i["id"] == S2["id"]), None)
        if it2:
            check("summary of S2: overall_score, focus with drill, thumbnail_url",
                  it2["overall_score"] == rep2["overall_score"] and it2["focus"]
                  and it2["focus"]["metric_id"] == rep2["focus_area"]["metric_id"] and it2["thumbnail_url"], r,
                  json.dumps(it2)[:400])
            g = raw.get(it2["thumbnail_url"])
            check("summary thumbnail_url downloads", g.status_code == 200 and g.content == JPEG_BYTES, None,
                  str(g.status_code))
        if it1:
            check("summary of S1 (all on target): maintain focus, score from latest revision",
                  it1["focus"] is not None and it1["focus"]["drill_id"] == rep1["focus_area"]["drill"]["drill_id"]
                  and it1["overall_score"] == rep1["overall_score"]
                  and it1["overall_score_is_tentative"] is rep1["overall_score_is_tentative"], r, json.dumps(it1)[:300])
        check("list ordered newest first", ids == [i["id"] for i in sorted(items, key=lambda x: (x["created_at"],
                                                                                              x["id"]), reverse=True)],
              r)
    r = call("GET", "/v1/sessions", A["token"], params={"mode": "p"})
    check("filter mode=p -> only the pitching session", r.status_code == 200 and S_p and
          [i["id"] for i in r.json()["items"]] == [S_p["id"]], r)
    r = call("GET", "/v1/sessions", A["token"], params={"mode": "h", "self": "true"})
    check("filter mode=h self=true -> S1,S2,S3", r.status_code == 200 and
          {i["id"] for i in r.json()["items"]} == {s["id"] for s in (S1, S2, S3) if s}, r)
    r = call("GET", "/v1/sessions", A["token"], params={"self": "false"})
    check("filter self=false -> only Kid Brother", r.status_code == 200 and S_else and
          [i["id"] for i in r.json()["items"]] == [S_else["id"]], r)
    r = call("GET", "/v1/sessions", A["token"], params={"athlete_name": "Kid Brother"})
    check("filter athlete_name=Kid Brother", r.status_code == 200 and S_else and
          [i["athlete_name"] for i in r.json()["items"]] == ["Kid Brother"], r)
    r = call("GET", "/v1/sessions", A["token"], params={"athlete_name": "Nobody Here"})
    check("filter athlete_name unknown -> empty", r.status_code == 200 and r.json()["items"] == [], r)
    future = (datetime.now(UTC) + timedelta(days=1)).isoformat()
    r = call("GET", "/v1/sessions", A["token"], params={"since": future})
    check("filter since=tomorrow -> empty", r.status_code == 200 and r.json()["items"] == [], r)
    if S3:
        r = call("GET", "/v1/sessions", A["token"], params={"since": S3["created_at"]})
        check("filter since=S3.created_at -> only S3 (inclusive)", r.status_code == 200 and
              [i["id"] for i in r.json()["items"]] == [S3["id"]], r)
    expect_error("filter mode=x -> 400", call("GET", "/v1/sessions", A["token"], params={"mode": "x"}), 400)
    expect_error("filter since=garbage -> 400", call("GET", "/v1/sessions", A["token"], params={"since": "yesterday"}),
                 400)
    expect_error("bad cursor -> 400", call("GET", "/v1/sessions", A["token"], params={"cursor": "!!!"}), 400)
    expect_error("limit=0 -> 400", call("GET", "/v1/sessions", A["token"], params={"limit": 0}), 400)
    walked, cursor, pages = [], None, 0
    while pages < 20:
        params = {"limit": 1}
        if cursor:
            params["cursor"] = cursor
        r = call("GET", "/v1/sessions", A["token"], params=params)
        if r.status_code != 200:
            check("cursor walk page", False, r)
            break
        d = r.json()
        walked += [i["id"] for i in d["items"]]
        pages += 1
        cursor = d.get("next_cursor")
        if not cursor:
            break
    full = [i["id"] for i in call("GET", "/v1/sessions", A["token"]).json()["items"]]
    check(f"cursor walk with limit=1 visits all items once in order ({len(walked)} of {len(full)})",
          walked == full and len(set(walked)) == len(walked), None, f"walked={walked} full={full}")
    r = call("GET", "/v1/sessions", B["token"])
    check("B's list does not include A's sessions", r.status_code == 200 and
          not ({i["id"] for i in r.json()["items"]} & {s["id"] for s in (S1, S2, S3, S_else, S_p) if s}), r)

    # ------------------------------------------------------------ 2b. idempotency on POST /sessions (B)
    iv = uploaded(C, "video")
    ib = session_body(iv["upload_id"])
    key = f"qa-{RUN_ID}-sess"
    r1 = call("POST", "/v1/sessions", C["token"], json=ib, headers={"Idempotency-Key": key})
    r2 = call("POST", "/v1/sessions", C["token"], json=ib, headers={"Idempotency-Key": key})
    check("Idempotency-Key replay returns the identical body and status", r1.status_code == 201
          and r2.status_code == 201 and r1.json() == r2.json(), r2)
    ib2 = copy.deepcopy(ib)
    ib2["fps"] = 60
    expect_error("same Idempotency-Key with a different body -> 409 IDEMPOTENCY_KEY_REUSED",
                 call("POST", "/v1/sessions", C["token"], json=ib2, headers={"Idempotency-Key": key}), 409,
                 "IDEMPOTENCY_KEY_REUSED")
    r = call("GET", "/v1/sessions", C["token"], params={"mode": "h", "self": "true"})
    if r1.status_code == 201:
        n = sum(1 for i in r.json()["items"] if i["id"] == r1.json()["session"]["id"])
        check("replay created only one session", n == 1, r)
    r = call("POST", "/v1/sessions", B["token"], json=ib, headers={"Idempotency-Key": key})
    check(f"same key and body from another account is not a replay (got {r.status_code} {err_code(r)})",
          r.status_code != 201 or r.json() != r1.json(), r)

    # ------------------------------------------------------------ 7. delete session (B)
    DS = new_session(C, "C to delete")
    if DS:
        r = call("DELETE", f"/v1/sessions/{DS['id']}", C["token"])
        check("DELETE session -> 204", r.status_code == 204, r)
        expect_error("GET deleted session -> 404", call("GET", f"/v1/sessions/{DS['id']}", C["token"]), 404,
                     "NOT_FOUND")
        r = call("GET", "/v1/sessions", C["token"])
        check("deleted session gone from list", r.status_code == 200 and DS["id"] not in
              [i["id"] for i in r.json()["items"]], r)
        expect_error("DELETE deleted session again -> 404", call("DELETE", f"/v1/sessions/{DS['id']}", C["token"]), 404)
        expect_error("report on deleted session -> 404", post_report(C, DS["id"], payload()), 404, "NOT_FOUND")
        g = raw.get(DS["media"]["video_url"])
        if g.status_code == 200:
            note("After DELETE /v1/sessions/{id} the earlier presigned video URL still downloads (200). By design "
                 "(DESIGN.md D5 soft delete; media removed later by app/jobs/cleanup.py), but frontend_spec 7.5 says "
                 "'D5 returns 204, deletes the objects'. Signed URLs live 1 h, so a deleted clip stays reachable up "
                 "to an hour, longer until the cleanup job runs.")
        else:
            check("deleted session's video URL unreachable", g.status_code in (403, 404), None, str(g.status_code))

    # ------------------------------------------------------------ 8. drills (B)
    dl = {"drill_id": "hit_13", "reps": 8, "day": today.isoformat()}
    r = call("POST", "/v1/drill-logs", B["token"], json=dl)
    if check("POST drill log valid -> 201", r.status_code == 201, r):
        log = r.json()["log"]
        check("drill log echoes fields", log["drill_id"] == "hit_13" and log["reps"] == 8 and log["day"] == dl["day"],
              r)
    if LB:
        r = call("POST", "/v1/drill-logs", B["token"], json={**dl, "session_id": LB["id"]})
        check("drill log linked to own session -> 201", r.status_code == 201, r)
    if S1:
        r = call("POST", "/v1/drill-logs", B["token"], json={**dl, "session_id": S1["id"]})
        check(f"drill log on another user's session refused (got {r.status_code})", r.status_code in (403, 404), r)
    expect_error("drill log unknown drill id -> 400", call("POST", "/v1/drill-logs", B["token"],
                 json={**dl, "drill_id": "hit_999"}), 400, "VALIDATION", "drill_id")
    expect_error("drill log reps 9 -> 400", call("POST", "/v1/drill-logs", B["token"], json={**dl, "reps": 9}), 400,
                 "VALIDATION", "reps")
    expect_error("drill log reps 0 -> 400", call("POST", "/v1/drill-logs", B["token"], json={**dl, "reps": 0}), 400,
                 "VALIDATION", "reps")
    expect_error("drill log bad day -> 400", call("POST", "/v1/drill-logs", B["token"], json={**dl, "day": "today"}),
                 400, "VALIDATION", "day")
    dkey = f"qa-{RUN_ID}-drill"
    d1 = call("POST", "/v1/drill-logs", B["token"], json={**dl, "reps": 5}, headers={"Idempotency-Key": dkey})
    d2 = call("POST", "/v1/drill-logs", B["token"], json={**dl, "reps": 5}, headers={"Idempotency-Key": dkey})
    check("drill log Idempotency-Key replay identical", d1.status_code == 201 and d2.status_code == 201
          and d1.json() == d2.json(), d2)
    expect_error("drill log same key different body -> 409", call("POST", "/v1/drill-logs", B["token"],
                 json={**dl, "reps": 6}, headers={"Idempotency-Key": dkey}), 409, "IDEMPOTENCY_KEY_REUSED")
    old = {"drill_id": "hit_01", "reps": 3, "day": (today - timedelta(days=20)).isoformat()}
    call("POST", "/v1/drill-logs", B["token"], json=old)
    r = call("GET", "/v1/drill-logs", B["token"], params={"from": (today - timedelta(days=6)).isoformat(),
                                                          "to": today.isoformat()})
    if check("GET drill logs 7-day range 200", r.status_code == 200, r):
        items = r.json()["items"]
        check("range filter: 3 logs in the last 7 days, old one excluded",
              len(items) == 3 and all(i["day"] >= (today - timedelta(days=6)).isoformat() for i in items), r,
              f"{len(items)} items")
    r = call("GET", "/v1/drill-logs", B["token"], params={"from": (today - timedelta(days=30)).isoformat(),
                                                          "to": today.isoformat()})
    check("range 30 days includes the old log", r.status_code == 200 and len(r.json()["items"]) == 4, r)
    expect_error("drill logs range > 90 days -> 400", call("GET", "/v1/drill-logs", B["token"], params={
        "from": (today - timedelta(days=91)).isoformat(), "to": today.isoformat()}), 400, "VALIDATION")
    r = call("GET", "/v1/drill-logs", B["token"], params={"from": (today - timedelta(days=90)).isoformat(),
                                                          "to": today.isoformat()})
    check("drill logs range exactly 90 days -> 200", r.status_code == 200, r)
    expect_error("drill logs to < from -> 400", call("GET", "/v1/drill-logs", B["token"], params={
        "from": today.isoformat(), "to": (today - timedelta(days=1)).isoformat()}), 400)
    expect_error("drill logs missing from -> 400", call("GET", "/v1/drill-logs", B["token"],
                                                        params={"to": today.isoformat()}), 400)
    r = call("GET", "/v1/drill-logs", A["token"], params={"from": (today - timedelta(days=6)).isoformat(),
                                                          "to": today.isoformat()})
    check("A does not see B's drill logs", r.status_code == 200 and r.json()["items"] == [], r)

    # ------------------------------------------------------------ 9. catalog
    r = call("GET", "/v1/catalog/metrics", A["token"], params={"mode": "h"})
    if check("catalog mode=h 200", r.status_code == 200, r):
        c = r.json()
        check("catalog h: 4 groups in order", [g["group"] for g in c["groups"]] == GROUP_ORDER, r)
        check("catalog h: 3 metrics", {m["metric_id"] for m in c["metrics"]} == {
            "hip_shoulder_separation_at_foot_down", "stride_relative_length", "hip_shoulder_separation_at_contact"}, r)
        check("catalog h: drills include hit_13", any(d["drill_id"] == "hit_13" for d in c["drills"]), r)
    r = call("GET", "/v1/catalog/metrics", A["token"], params={"mode": "p"})
    check("catalog mode=p 200 with drills and no metrics yet", r.status_code == 200 and r.json()["metrics"] == []
          and len(r.json()["drills"]) > 0, r)
    expect_error("catalog mode=x -> 400", call("GET", "/v1/catalog/metrics", A["token"], params={"mode": "x"}), 400)
    expect_error("catalog without auth -> 401", call("GET", "/v1/catalog/metrics", params={"mode": "h"}), 401)

    # ------------------------------------------------------------ openapi sanity: no camelCase in schemas
    spec = client.get("/openapi.json").json()
    camel_props = []
    for name, schema in spec.get("components", {}).get("schemas", {}).items():
        for prop in (schema.get("properties") or {}):
            if re.search(r"[A-Z]", prop) and not (name.startswith("Apple") and prop == "signedPayload"):
                camel_props.append(f"{name}.{prop}")
    check("openapi: no camelCase properties", not camel_props, None, str(camel_props))


def cleanup():
    print("\n--- cleanup ---")
    for acct in ACCOUNTS:
        r = call("DELETE", "/v1/me", acct["token"])
        acct["deleted"] = check(f"DELETE /v1/me {acct['email']} -> 204", r.status_code == 204, r)
        r = call("GET", "/v1/me", acct["token"])
        check(f"deleted account token no longer works ({acct['email']})", r.status_code in (401, 404), r)
        r = client.post("/v1/auth/login", json={"email": acct["email"], "password": PASSWORD})
        check(f"deleted account cannot log in ({acct['email']})", r.status_code in (400, 401), r)
    for acct in ACCOUNTS:
        url = acct.get("video_url")
        if url:
            g = raw.get(url)
            check(f"presigned video URL unreachable after account deletion ({g.status_code})",
                  g.status_code in (403, 404), None, f"status {g.status_code}")


def main() -> int:
    print(f"QA sessions/reports suite against {BASE_URL}, run {RUN_ID}\n")
    try:
        run()
    except SystemExit as exc:
        check(f"suite aborted: {exc}", False)
    except Exception as exc:  # keep going to cleanup
        import traceback
        traceback.print_exc()
        check(f"suite crashed: {exc!r}", False)
    finally:
        cleanup()
    check("no 5xx responses", not FIVE_HUNDREDS, None, "; ".join(FIVE_HUNDREDS))
    check("no camelCase keys in responses", not CAMEL, None, ", ".join(sorted(CAMEL)))
    check("no forbidden keys leaked", not LEAKS, None, ", ".join(sorted(set(LEAKS))))
    print(f"\n=== {RESULTS['PASS']} passed, {RESULTS['FAIL']} failed ===")
    for f in FAILS:
        print(f)
    for n in NOTES:
        print(f"NOTE: {n}")
    return 1 if RESULTS["FAIL"] else 0


if __name__ == "__main__":
    sys.exit(main())