File size: 53,721 Bytes
fe40b87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
"""Contract conformance QA: spec sections 5 (C01-C04) and 6 (N01-N50) JSON examples vs the live API.

Expected shapes are transcribed from the spec examples (docs/reference/coaching_workflow_spec.md), not from the
implementation. Each response is compared recursively: the key set must equal the example's key set, and every value
must have the example's type (or a spec-stated enum / nullability). Known deviations are marked
`xfail(strict=True, reason="CONTRACT: ...")` so a fix turns the test green and forces the marker to be removed.
"""

import uuid
from datetime import UTC, datetime, timedelta
from types import SimpleNamespace

import httpx
import pytest
from sqlalchemy import update

from app.common.academy_access import normalize_permissions
from app.core.database import get_session_factory
from app.integrations.push import get_push_client
from app.modules.academy.models import AcademyMembership, GroupCoach, GroupPlayer, PlayerGroup
from app.modules.goals.models import Goal
from app.modules.settings.models import ConsentEvent
from app.modules.uploads.models import Upload
from tests.factories import METRICS, FakePush, create_team, join, make_account, make_session

# ---------------------------------------------------------------------------------------------------------------
# Tiny shape language
# ---------------------------------------------------------------------------------------------------------------


class Leaf:
    def __init__(self, name, ok):
        self.name, self.ok = name, ok

    def check(self, value, path):
        return [] if self.ok(value) else [f"{path}: expected {self.name}, got {value!r:.70}"]


def _is_uuid(v):
    try:
        return isinstance(v, str) and str(uuid.UUID(v)) == v.lower()
    except ValueError:
        return False


def _is_ts(v):
    try:
        return isinstance(v, str) and datetime.fromisoformat(v.replace("Z", "+00:00")).tzinfo is not None
    except ValueError:
        return False


def _is_date(v):
    try:
        return isinstance(v, str) and len(v) == 10 and datetime.strptime(v, "%Y-%m-%d") is not None
    except ValueError:
        return False


U = Leaf("uuid", _is_uuid)
TS = Leaf("rfc3339 instant", _is_ts)
DATE = Leaf("YYYY-MM-DD", _is_date)
S = Leaf("string", lambda v: isinstance(v, str))
I = Leaf("integer", lambda v: isinstance(v, int) and not isinstance(v, bool))  # noqa: E741
NUM = Leaf("number", lambda v: isinstance(v, (int, float)) and not isinstance(v, bool))
B = Leaf("boolean", lambda v: isinstance(v, bool))
NIL = Leaf("null", lambda v: v is None)
ANY = Leaf("any", lambda v: True)  # spec example is null / untyped


class Opt:
    def __init__(self, inner):
        self.inner = inner

    def check(self, value, path, extra=frozenset()):
        return [] if value is None else diff(value, self.inner, path, extra)


class E:
    def __init__(self, *values):
        self.values = values

    def check(self, value, path):
        return [] if value in self.values else [f"{path}: expected one of {self.values}, got {value!r}"]


class L:
    def __init__(self, inner, nonempty=False):
        self.inner, self.nonempty = inner, nonempty

    def check(self, value, path, extra=frozenset()):
        if not isinstance(value, list):
            return [f"{path}: expected list, got {type(value).__name__}"]
        if self.nonempty and not value:
            return [f"{path}: expected non-empty list (test setup)"]
        out = []
        for i, item in enumerate(value):
            out += diff(item, self.inner, f"{path}[{i}]", extra)
        return out


class M:
    """Object with arbitrary keys and uniform values."""

    def __init__(self, inner):
        self.inner = inner

    def check(self, value, path, extra=frozenset()):
        if not isinstance(value, dict):
            return [f"{path}: expected object, got {type(value).__name__}"]
        out = []
        for k, v in value.items():
            out += diff(v, self.inner, f"{path}.{k}", extra)
        return out


def diff(value, shape, path="$", extra=frozenset()):
    if isinstance(shape, dict):
        if not isinstance(value, dict):
            return [f"{path}: expected object, got {type(value).__name__}"]
        out = []
        missing, unexpected = set(shape) - set(value), set(value) - set(shape) - extra
        if missing:
            out.append(f"{path}: missing keys {sorted(missing)}")
        if unexpected:
            out.append(f"{path}: unexpected keys {sorted(unexpected)}")
        for key in set(shape) & set(value):
            out += diff(value[key], shape[key], f"{path}.{key}", extra)
        return out
    if isinstance(shape, (Opt, L, M)):
        return shape.check(value, path, extra)
    return shape.check(value, path)


def conforms(value, shape, extra=frozenset()):
    problems = diff(value, shape, "$", extra)
    assert not problems, "contract violations:\n  " + "\n  ".join(problems)


def ok(response, status):
    assert response.status_code == status, f"{response.request.method} {response.request.url.path}: " \
                                           f"{response.status_code} {response.text[:300]}"
    return response


def empty(response, status=204):
    ok(response, status)
    assert response.content == b""


# ---------------------------------------------------------------------------------------------------------------
# Shapes transcribed from the spec examples
# ---------------------------------------------------------------------------------------------------------------

PAGE = {"next_cursor": Opt(S)}
MEDIA_REF = {"upload_id": U, "url": S, "expires_at": TS}                       # C01 voice_note minus seconds / N35
AUDIO = {"upload_id": U, "seconds": NUM, "url": S, "expires_at": TS}            # N14 voice example, C01 voice_note

SETTINGS = {k: B for k in ("coach_can_see_sessions", "share_with_parent", "auto_monthly_report", "private_links",
                           "clips_as_examples", "help_improve_ai", "notify_results", "notify_coach", "notify_drills",
                           "notify_weekly", "skip_filming_guide")}
SETTINGS.update(parent_email=Opt(S), consented_at=Opt(TS), consent_version=Opt(S), version=I)

NOTIFICATION = {"id": U, "kind": E("review", "drill", "armcare", "result", "report"), "title": S, "body": S,
                "at": TS, "read": B, "target": Leaf("target with at most one of thread_id/session_id/month",
                                                    lambda v: isinstance(v, dict) and len(v) <= 1
                                                    and set(v) <= {"thread_id", "session_id", "month"})}

MSG_COMMON = {"id": U, "author_id": U, "from": E("coach", "player"), "at": TS}
MESSAGES = {
    "text": {**MSG_COMMON, "kind": E("text"), "text": S},
    "voice": {**MSG_COMMON, "kind": E("voice"), "seconds": NUM, "audio": AUDIO},
    "session": {**MSG_COMMON, "kind": E("session"), "session_id": U, "label": S, "score": Opt(I)},
    "review": {**MSG_COMMON, "kind": E("review"), "cue": S, "voice_seconds": Opt(NUM), "audio": Opt(AUDIO),
               "findings": L({"metric_id": S, "name": S, "verdict": E("agree", "change", "later")}),
               "drill_id": Opt(S), "name": Opt(S), "assignment_id": Opt(U)},
}


class Message:
    def check(self, value, path, extra=frozenset()):
        if not isinstance(value, dict) or value.get("kind") not in MESSAGES:
            return [f"{path}: unknown message kind {value!r:.80}"]
        return diff(value, MESSAGES[value["kind"]], path, extra)


MESSAGE = Message()


def message_shape(message):
    return MESSAGES[message["kind"]]


THREAD = {"id": U, "mode": E("h", "p"), "session_id": Opt(U), "session_label": S, "score": Opt(I),
          "tone": E("g", "y", "r"), "coach_id": U, "coach_name": S, "player_id": U, "player_name": S,
          "status": E("reviewed", "waiting_for_coach"), "unread_for_player": B, "unread_for_coach": B,
          "updated_at": TS, "messages": L(MESSAGE), "next_message_cursor": Opt(S)}

GOAL = {"id": U, "player_id": U, "mode": E("h", "p"), "type": E("groups", "param", "score"), "target": NUM,
        "metric_id": Opt(S), "metric_name": Opt(S), "due": S, "due_at": TS, "set_at": TS, "set_by": S,
        "set_by_id": U, "note": S, "weekly": {"practice_days": I, "drill_sets": I}, "version": I}
GOAL_HISTORY = {"id": U, "text": S, "range": S, "met": Opt(B), "outcome": E("met", "not_met", "superseded", "unknown"),
                "start_at": TS, "end_at": TS, "evaluated_session_id": Opt(U)}
MILESTONE = {"id": U, "icon": E("trend", "check", "flag", "bolt", "heart"), "tone": E("g", "y", "r", "b"),
             "title": S, "when": S, "occurred_at": TS, "source_goal_id": Opt(U)}

ASSIGNMENT = {"id": U, "player_id": U, "mode": E("h", "p"), "drill_id": S, "drill_source": E("catalog", "library"),
              "name": S, "fixes": S, "sets": I, "reps": I, "due": S, "due_date": DATE, "assigned_by": S,
              "assigned_by_id": U, "done": I, "session_id": Opt(U), "assigned_at": TS, "media": Opt(MEDIA_REF)}

OUTING = {"id": U, "date": TS, "local_date": DATE, "label": S, "pitches": I, "rest": ANY, "rest_days": ANY}
ARM_CARE = {"outings": L(OUTING), "feel": Opt(E("sore", "tight", "good")), "feel_recorded_at": Opt(TS),
            "daily_max": Opt(I), "innings_last_12_months": Opt(I), "innings_limit": Opt(I),
            "rest_status": E("unknown", "rest_required", "no_rest_due"), "next_eligible_date": Opt(DATE),
            "rule_version": Opt(S), "unavailable_reason": Opt(S)}

COACH_ACCESS = {"status": E("none", "pending", "approved", "declined"), "code": Opt(S), "sent_at": Opt(TS)}
GROUP = {"id": U, "name": S, "focus": E("Hitting", "Pitching", "Both"), "players": I, "player_ids": L(U),
         "coaches": L(S), "coach_ids": L(U)}
NOTE = {"player_id": U, "text": S, "updated_at": Opt(TS), "version": I}
MEMBER = {"id": U, "name": S, "focus": Opt(E("h", "p")), "level": Opt(S), "group_ids": L(U)}
LIBRARY_DRILL = {"id": U, "name": S, "fixes": S, "fault_tags": L(S), "by": S, "author_id": U, "mode": E("h", "p"),
                 "media": Opt(MEDIA_REF), "created_at": TS}

PERMISSIONS = {k: B for k in ("review", "drills", "goals", "library", "earnings")}
COACH_MEMBER = {"id": U, "name": S, "coaches": S, "joined": TS, "joined_with": Opt(S),
                "role": E("admin", "coach", "assistant"), "is_me": B, "sees_all": B, "group_ids": L(U),
                "permissions": PERMISSIONS,
                "activity": Opt({"reviews": I, "avg_reply_hours": Opt(NUM), "players": I, "drills_set": I,
                                 "period_start": DATE, "period_end": DATE}),
                "status": E("active", "paused", "removed"), "version": I}
COACH_REQUEST = {"id": U, "user_id": U, "name": S, "code": S, "at": TS, "also_player": B,
                 "status": E("pending", "approved", "declined")}
STAFF_CODE = {"code": S, "role": E("coach", "assistant"), "expires": TS, "uses": I, "max_uses": I,
              "approval": E("admin", "auto"), "status": E("active", "expired", "revoked")}

DASHBOARD = {"month": S, "currency": Opt(S), "earnings_minor": Opt(I), "paying_players": Opt(I),
             "per_player_minor": Opt(I), "active_players": I, "new_this_month": I, "improving_pct": Opt(NUM),
             "analyses_this_week": I, "avg_review_hours": Opt(NUM), "cards": {"g": I, "y": I, "r": I},
             "coaches": L({"id": U, "name": S, "coaches": S, "reviews": I}), "pending_requests": I,
             "not_filmed_7d": I, "earnings_bars": L({"month": S, "amount_minor": I}), "as_of": TS}
EARNINGS = {"month": S, "currency": Opt(S), "month_minor": Opt(I), "players": Opt(I), "per_player_minor": Opt(I),
            "ytd_minor": Opt(I), "projected_minor": Opt(I), "as_of": TS,
            "payouts": L({"id": U, "scheduled_for": DATE, "amount_minor": Opt(I),
                          "status": E("scheduled", "paid", "failed", "cancelled"), "paid_at": Opt(TS)}),
            "next_cursor": Opt(S)}
CORPORATE = {"month": S, "as_of": TS,
             "kpis": {"locations_live": I, "active_players": I, "analyses": I, "improving_pct": Opt(NUM)},
             "locations": L({"id": U, "name": S, "active_players": I, "improving_pct": Opt(NUM)}),
             "fixes": L({"metric_id": S, "label": S, "mode": E("h", "p"), "affected_pct": Opt(NUM)})}
CONSENT_ITEM = {"player_id": U, "name": S, "group": S, "group_ids": L(U), "note": S, "version": Opt(S),
                "accepted_at": Opt(TS), "withdrawn_at": Opt(TS), "help_improve_ai": B}

# ---------------------------------------------------------------------------------------------------------------
# Scenario builders
# ---------------------------------------------------------------------------------------------------------------

DRILL_BODY = {"mode": "h", "drill_source": "catalog", "drill_id": "hit_13"}
REVIEW = {"cue": "Keep the hands back as the front foot lands.", "drill_id": "hit_13",
          "verdicts": {METRICS[0]: "agree", METRICS[1]: "change"}}
M4A = b"\x00\x00\x00\x18ftypM4A " + b"\x00" * 40


@pytest.fixture(autouse=True)
def push(app):
    fake = FakePush()
    app.dependency_overrides[get_push_client] = lambda: fake
    yield fake
    app.dependency_overrides.pop(get_push_client, None)


async def _staff(team_id, name="Jamie K.", role="coach", **perms):
    account = await make_account("coach", name=name)
    async with get_session_factory()() as db:
        db.add(AcademyMembership(team_id=team_id, account_id=account["id"], role=role, status="active",
                                 sees_all=False, permissions=normalize_permissions(role, perms)))
        await db.commit()
    return account


@pytest.fixture
async def w(client):
    owner = await make_account("coach", name="Imran Baig")
    team = await create_team(client, owner)
    player = await make_account("player", name="Alex R.")
    await join(client, player, team["code"])
    team_id = uuid.UUID(team["id"])
    jamie = await _staff(team_id, library=True, goals=True, drills=True)
    async with get_session_factory()() as db:
        group = PlayerGroup(team_id=team_id, name="14U", focus="Both")
        db.add(group)
        await db.flush()
        db.add(GroupPlayer(group_id=group.id, player_id=player["id"]))
        db.add(GroupCoach(group_id=group.id, coach_id=jamie["id"]))
        await db.commit()
        group_id = group.id
    return SimpleNamespace(owner=owner, team=team, team_id=team_id, player=player, jamie=jamie, group_id=group_id)


async def _audio(client, headers, put=True):
    response = await client.post("/v1/uploads", headers=headers, json={
        "kind": "audio", "content_type": "audio/mp4", "size_bytes": len(M4A), "duration_sec": 12})
    target = ok(response, 201).json()
    if put:
        async with httpx.AsyncClient() as s3:
            await s3.put(target["url"], content=M4A, headers=target["headers"])
    return target["upload_id"]


async def _review(client, w, **extra):
    session_id = await make_session(w.player["id"])
    response = await client.post(f"/v1/sessions/{session_id}/review", headers=w.owner["headers"],
                                 json={**REVIEW, **extra})
    assert response.status_code in (200, 201), response.text
    return session_id, response


async def _thread(client, w, mode="h"):
    response = await client.post(f"/v1/coach/players/{w.player['id']}/thread", headers=w.owner["headers"],
                                 json={"mode": mode})
    assert response.status_code in (200, 201), response.text
    return response.json()["thread"]


async def _assignment(client, w, **extra):
    due = (datetime.now(UTC).date() + timedelta(days=1)).isoformat()
    response = await client.post(f"/v1/coach/players/{w.player['id']}/drill-assignments", headers=w.owner["headers"],
                                 json={**DRILL_BODY, "due_date": due, **extra})
    return ok(response, 201).json()["assignment"]


async def _staff_code(client, owner, **kw):
    body = {"role": "coach", "expires_days": 7, "max_uses": 5, "approval": "admin", **kw}
    response = await client.post("/v1/academy/staff-codes", headers=owner["headers"], json=body)
    return ok(response, 201).json()["staff_code"]


# ---------------------------------------------------------------------------------------------------------------
# OpenAPI inventory
# ---------------------------------------------------------------------------------------------------------------

ENDPOINTS = [
    ("get", "/v1/me/settings"), ("patch", "/v1/me/settings"), ("post", "/v1/me/consent"),
    ("delete", "/v1/me/consent"), ("post", "/v1/me/exports"),
    ("get", "/v1/notifications"), ("get", "/v1/notifications/unread-count"), ("post", "/v1/notifications/{id}/read"),
    ("post", "/v1/notifications/read-all"),
    ("get", "/v1/threads"), ("get", "/v1/threads/{id}"), ("get", "/v1/sessions/{id}/thread"),
    ("post", "/v1/threads/{id}/read"), ("post", "/v1/threads/{id}/messages"),
    ("post", "/v1/coach/players/{id}/thread"),
    ("get", "/v1/players/{id}/goals"), ("put", "/v1/players/{id}/goals/{id}"),
    ("get", "/v1/players/{id}/goals/history"),
    ("get", "/v1/me/milestones"),
    ("get", "/v1/drill-assignments"), ("post", "/v1/coach/players/{id}/drill-assignments"),
    ("post", "/v1/drill-assignments/{id}/sets"),
    ("get", "/v1/me/arm-care"), ("post", "/v1/me/arm-care/outings"), ("put", "/v1/me/arm-care/feel"),
    ("get", "/v1/me/coach-access"), ("post", "/v1/me/coach-access"),
    ("get", "/v1/academy/groups"), ("post", "/v1/academy/groups"),
    ("get", "/v1/coach/players/{id}/note"), ("put", "/v1/coach/players/{id}/note"),
    ("get", "/v1/academy/members"), ("post", "/v1/coach/roster/players"),
    ("get", "/v1/academy/library"), ("post", "/v1/academy/library"),
    ("get", "/v1/academy/dashboard"), ("get", "/v1/academy/earnings"), ("get", "/v1/academy/corp"),
    ("get", "/v1/academy/coaches"), ("get", "/v1/academy/coaches/{id}"), ("patch", "/v1/academy/coaches/{id}"),
    ("delete", "/v1/academy/coaches/{id}"), ("get", "/v1/academy/coach-requests"),
    ("post", "/v1/academy/coach-requests/{id}/decision"), ("get", "/v1/academy/staff-codes"),
    ("post", "/v1/academy/staff-codes"), ("delete", "/v1/academy/staff-codes/{id}"),
    ("get", "/v1/academy/consent"), ("post", "/v1/academy/consent/export"),
    ("get", "/v1/me"), ("get", "/v1/coach/roster"), ("post", "/v1/uploads"), ("post", "/v1/sessions/{id}/review"),
]


def _normalise(path):
    import re
    return re.sub(r"\{[^}]+\}", "{id}", path)


async def test_openapi_lists_every_new_path_and_method(client):
    spec = ok(await client.get("/openapi.json"), 200).json()
    paths = {_normalise(p): ops for p, ops in spec["paths"].items()}
    missing = [f"{m.upper()} {p}" for m, p in ENDPOINTS if m not in paths.get(p, {})]
    assert not missing, missing


# ---------------------------------------------------------------------------------------------------------------
# Settings and consent (N01-N05)
# ---------------------------------------------------------------------------------------------------------------

async def test_n01_read_settings(client, w):
    body = ok(await client.get("/v1/me/settings", headers=w.player["headers"]), 200).json()
    conforms(body, {"settings": SETTINGS})
    assert body["settings"]["version"] == 1


async def test_n02_update_settings(client, w):
    request = {"share_with_parent": False, "auto_monthly_report": False, "expected_version": 1}
    body = ok(await client.patch("/v1/me/settings", headers=w.player["headers"], json=request), 200).json()
    conforms(body, {"settings": SETTINGS})
    assert body["settings"]["version"] == 2


async def test_n03_record_consent(client, w):
    body = ok(await client.post("/v1/me/consent", headers=w.player["headers"],
                                json={"version": "1.0", "accepted": True}), 201).json()
    conforms(body, {"consent": {"version": S, "accepted_at": TS, "withdrawn_at": Opt(TS)}})
    assert body["consent"]["version"] == "1.0" and body["consent"]["withdrawn_at"] is None


async def test_n04_withdraw_consent(client, w):
    await client.post("/v1/me/consent", headers=w.player["headers"], json={"version": "1.0", "accepted": True})
    empty(await client.delete("/v1/me/consent", headers=w.player["headers"]))
    empty(await client.delete("/v1/me/consent", headers=w.player["headers"]))


async def test_n05_request_export(client, w):
    body = ok(await client.post("/v1/me/exports", headers=w.player["headers"], json={"scope": "videos"}), 202).json()
    conforms(body, {"export": {"id": U, "status": E("queued"), "requested_at": TS, "delivery": E("account_email")}})


# ---------------------------------------------------------------------------------------------------------------
# Notifications (N06-N09)
# ---------------------------------------------------------------------------------------------------------------

@pytest.mark.xfail(strict=True,
    reason="CONTRACT: review notification target has both thread_id and session_id; N06 proposes at most one")
async def test_n06_list_notifications(client, w):
    await _review(client, w)
    body = ok(await client.get("/v1/notifications", headers=w.player["headers"]), 200).json()
    conforms(body, {"items": L(NOTIFICATION, nonempty=True), **PAGE})
    assert body["items"][0]["kind"] == "review" and set(body["items"][0]["target"]) == {"thread_id"}


async def test_n07_unread_count(client, w):
    await _review(client, w)
    body = ok(await client.get("/v1/notifications/unread-count", headers=w.player["headers"]), 200).json()
    conforms(body, {"count": I})
    assert body["count"] == 1


async def test_n08_mark_one_read(client, w):
    await _review(client, w)
    items = (await client.get("/v1/notifications", headers=w.player["headers"])).json()["items"]
    empty(await client.post(f"/v1/notifications/{items[0]['id']}/read", headers=w.player["headers"]))
    empty(await client.post(f"/v1/notifications/{items[0]['id']}/read", headers=w.player["headers"]))
    assert (await client.get("/v1/notifications/unread-count", headers=w.player["headers"])).json() == {"count": 0}


async def test_n09_mark_all_read(client, w):
    await _review(client, w)
    through = (datetime.now(UTC) + timedelta(seconds=1)).strftime("%Y-%m-%dT%H:%M:%SZ")
    empty(await client.post("/v1/notifications/read-all", headers=w.player["headers"], json={"through": through}))
    assert (await client.get("/v1/notifications/unread-count", headers=w.player["headers"])).json() == {"count": 0}
    empty(await client.post("/v1/notifications/read-all", headers=w.player["headers"]))


# ---------------------------------------------------------------------------------------------------------------
# Conversations (N10-N15) and C01
# ---------------------------------------------------------------------------------------------------------------

@pytest.mark.xfail(strict=True,
    reason="CONTRACT: review message has drill_name where spec N14 lists name (drill_id/name nullable strings)")
async def test_n10_list_threads_with_review_message(client, w):
    await _review(client, w)
    body = ok(await client.get("/v1/threads", headers=w.player["headers"]), 200).json()
    conforms(body, {"items": L(THREAD, nonempty=True), **PAGE})
    assert body["items"][0]["messages"][0]["kind"] == "review"


async def test_n10_list_threads_with_text_voice_session_messages(client, w):
    thread = await _thread(client, w)
    audio_id = await _audio(client, w.player["headers"])
    own = await make_session(w.player["id"])
    url = f"/v1/threads/{thread['id']}/messages"
    ok(await client.post(url, headers=w.owner["headers"], json={"kind": "text", "text": "Try the drill."}), 201)
    ok(await client.post(url, headers=w.player["headers"], json={"kind": "voice", "upload_id": audio_id,
                                                                  "seconds": 12}), 201)
    ok(await client.post(url, headers=w.player["headers"], json={"kind": "session", "session_id": str(own)}), 201)
    body = ok(await client.get("/v1/threads", headers=w.owner["headers"]), 200).json()
    conforms(body, {"items": L(THREAD, nonempty=True), **PAGE})
    assert {m["kind"] for m in body["items"][0]["messages"]} == {"text", "voice", "session"}


@pytest.mark.xfail(strict=True,
    reason="CONTRACT: review message has drill_name where spec N14 lists name (drill_id/name nullable strings)")
async def test_n11_read_thread(client, w):
    session_id, _ = await _review(client, w)
    found = await client.get(f"/v1/sessions/{session_id}/thread", headers=w.player["headers"])
    thread_id = found.json()["thread"]["id"]
    body = ok(await client.get(f"/v1/threads/{thread_id}", headers=w.player["headers"]), 200).json()
    conforms(body, {"thread": THREAD})
    assert body["thread"]["unread_for_player"] is True and body["thread"]["tone"] in ("g", "y", "r")


@pytest.mark.xfail(strict=True,
    reason="CONTRACT: review message has drill_name where spec N14 lists name (drill_id/name nullable strings)")
async def test_n12_session_thread(client, w):
    session_id, _ = await _review(client, w)
    body = ok(await client.get(f"/v1/sessions/{session_id}/thread", headers=w.player["headers"]), 200).json()
    conforms(body, {"thread": THREAD})
    assert body["thread"]["session_id"] == str(session_id) and body["thread"]["score"] == 70


async def test_n13_advance_read_watermark(client, w):
    session_id, _ = await _review(client, w)
    thread = (await client.get(f"/v1/sessions/{session_id}/thread", headers=w.player["headers"])).json()["thread"]
    empty(await client.post(f"/v1/threads/{thread['id']}/read", headers=w.player["headers"],
                            json={"last_message_id": thread["messages"][-1]["id"]}))
    empty(await client.post(f"/v1/threads/{thread['id']}/read", headers=w.player["headers"],
                            json={"last_message_id": None}))


SEND_COMMON = {"thread_status": E("reviewed", "waiting_for_coach"), "updated_at": TS}


async def test_n14_send_text(client, w):
    thread = await _thread(client, w)
    body = ok(await client.post(f"/v1/threads/{thread['id']}/messages", headers=w.owner["headers"],
                                json={"kind": "text", "text": "Try the drill before hitting."}), 201).json()
    conforms(body, {"message": MESSAGES["text"], **SEND_COMMON})
    assert body["thread_status"] == "reviewed" and body["message"]["from"] == "coach"


async def test_n14_send_voice(client, w):
    thread = await _thread(client, w)
    audio_id = await _audio(client, w.player["headers"])
    body = ok(await client.post(f"/v1/threads/{thread['id']}/messages", headers=w.player["headers"],
                                json={"kind": "voice", "upload_id": audio_id, "seconds": 12}), 201).json()
    conforms(body, {"message": MESSAGES["voice"], **SEND_COMMON})
    assert body["thread_status"] == "waiting_for_coach" and body["message"]["audio"]["upload_id"] == audio_id


async def test_n14_send_session(client, w):
    thread = await _thread(client, w)
    own = await make_session(w.player["id"])
    body = ok(await client.post(f"/v1/threads/{thread['id']}/messages", headers=w.player["headers"],
                                json={"kind": "session", "session_id": str(own)}), 201).json()
    conforms(body, {"message": MESSAGES["session"], **SEND_COMMON})
    assert body["message"]["label"] and body["message"]["score"] == 70


async def test_n15_ensure_player_thread(client, w):
    url = f"/v1/coach/players/{w.player['id']}/thread"
    created = ok(await client.post(url, headers=w.owner["headers"], json={"mode": "h"}), 201).json()
    conforms(created, {"thread": THREAD})
    assert created["thread"]["session_id"] is None and created["thread"]["messages"] == []
    again = ok(await client.post(url, headers=w.owner["headers"], json={"mode": "h"}), 200).json()
    conforms(again, {"thread": THREAD})


async def test_c01_review_response_without_voice(client, w):
    _, response = await _review(client, w)
    conforms(response.json(), {"review": {"coach_id": U, "coach_name": S, "cue": S, "drill_id": S,
                                          "verdicts": M(E("agree", "change", "later")), "at": TS,
                                          "voice_note": Opt(AUDIO)}, "thread_id": U})
    assert response.json()["review"]["voice_note"] is None


async def test_c01_review_response_with_voice_note(client, w):
    audio_id = await _audio(client, w.owner["headers"])
    _, response = await _review(client, w, voice_note_upload_id=audio_id, voice_note_seconds=12)
    conforms(response.json(), {"review": {"coach_id": U, "coach_name": S, "cue": S, "drill_id": S,
                                          "verdicts": M(E("agree", "change", "later")), "at": TS,
                                          "voice_note": AUDIO}, "thread_id": U})


@pytest.mark.xfail(strict=True,
    reason="CONTRACT: first review create returns 201, spec C01 example says 200 (201 is the pre-existing behaviour)")
async def test_c01_review_status_code_is_200(client, w):
    # Spec C01 labels the additive success response "200"; the endpoint already returned 201 on first create.
    _, response = await _review(client, w)
    assert response.status_code == 200


# ---------------------------------------------------------------------------------------------------------------
# C02 / C03 / C04
# ---------------------------------------------------------------------------------------------------------------

UPLOAD = {"upload_id": U, "url": S, "headers": M(S), "expires_at": TS}


async def test_c02_audio_upload(client, w):
    body = ok(await client.post("/v1/uploads", headers=w.player["headers"], json={
        "kind": "audio", "content_type": "audio/mp4", "size_bytes": 184320, "duration_sec": 12}), 201).json()
    conforms(body, UPLOAD)


async def test_c02_drill_video_upload(client, w):
    body = ok(await client.post("/v1/uploads", headers=w.owner["headers"], json={
        "kind": "drill_video", "content_type": "video/mp4", "size_bytes": 2_000_000, "duration_sec": 20}), 201).json()
    conforms(body, UPLOAD)


async def _approved_coach(client, w):
    code = await _staff_code(client, w.owner)
    who = await make_account("coach", name="Sam T.")
    ok(await client.post("/v1/me/coach-access", headers=who["headers"], json={"code": code["code"]}), 201)
    requests = (await client.get("/v1/academy/coach-requests?status=pending", headers=w.owner["headers"])).json()
    request = next(r for r in requests["items"] if r["user_id"] == str(who["id"]))
    decision = {"decision": "approve", "role": "coach", "sees_all": False, "group_ids": [str(w.group_id)]}
    ok(await client.post(f"/v1/academy/coach-requests/{request['id']}/decision", headers=w.owner["headers"],
                         json=decision), 200)
    return who


async def test_c03_me_additions_for_member(client, w):
    who = await _approved_coach(client, w)
    body = ok(await client.get("/v1/me", headers=who["headers"]), 200).json()
    academy = {"id": U, "name": S, "role": E("admin", "coach", "assistant"), "status": E("active", "paused", "removed"),
               "sees_all": B, "group_ids": L(U), "permissions": PERMISSIONS}
    for key, shape in (("academy", Opt(academy)), ("coach_access", COACH_ACCESS),
                       ("capabilities", {k: B for k in ("player", "coach", "academy_admin", "corporate_view")})):
        assert key in body, f"/v1/me missing {key}"
        conforms(body[key], shape)
    assert body["academy"] is not None and body["academy"]["group_ids"] == [str(w.group_id)]
    assert body["coach_access"]["status"] == "approved" and body["coach_access"]["sent_at"] is not None


async def test_c03_me_additions_without_academy(client):
    lone = await make_account("player")
    body = ok(await client.get("/v1/me", headers=lone["headers"]), 200).json()
    assert body["academy"] is None
    conforms(body["coach_access"], COACH_ACCESS)
    conforms(body["capabilities"], {k: B for k in ("player", "coach", "academy_admin", "corporate_view")})


async def test_c04_roster_group_ids(client, w):
    ok(await client.post("/v1/coach/roster/players", headers=w.jamie["headers"],
                         json={"player_ids": [str(w.player["id"])], "group_id": str(w.group_id)}), 200)
    body = ok(await client.get("/v1/coach/roster", headers=w.jamie["headers"]), 200).json()
    assert body["items"], "roster empty"
    for item in body["items"]:
        conforms(item["group_ids"], L(U))
        assert "group_ids" in item and item["group_ids"] == [str(w.group_id)]
        assert not {"height_cm", "weight_kg", "age"} & set(item), "roster must not leak body data"


# ---------------------------------------------------------------------------------------------------------------
# Goals (N16-N19)
# ---------------------------------------------------------------------------------------------------------------

GOAL_REQUEST = {"type": "groups", "target": 3, "metric_id": None, "due": "2 weeks",
                "weekly": {"practice_days": 4, "drill_sets": 9}, "note": "Keep the back hip loaded."}


def _goal_url(w, mode="h"):
    return f"/v1/players/{w.player['id']}/goals/{mode}"


async def test_n16_read_goal(client, w):
    empty_body = ok(await client.get(f"/v1/players/{w.player['id']}/goals?mode=h", headers=w.player["headers"]), 200)
    assert empty_body.json() == {"goal": None}
    ok(await client.put(_goal_url(w), headers=w.owner["headers"], json=GOAL_REQUEST), 200)
    body = ok(await client.get(f"/v1/players/{w.player['id']}/goals?mode=h", headers=w.player["headers"]), 200).json()
    conforms(body, {"goal": GOAL})


async def test_n17_set_goal(client, w):
    body = ok(await client.put(_goal_url(w), headers=w.owner["headers"], json=GOAL_REQUEST), 200).json()
    conforms(body, {"goal": GOAL})
    assert body["goal"]["version"] == 1 and body["goal"]["set_by"] == "Imran Baig"


async def test_n17_param_goal_has_metric_fields(client, w):
    request = {**GOAL_REQUEST, "type": "param", "target": 12.5, "metric_id": METRICS[0]}
    body = ok(await client.put(_goal_url(w), headers=w.owner["headers"], json=request), 200).json()
    conforms(body, {"goal": GOAL})
    assert body["goal"]["metric_id"] == METRICS[0] and body["goal"]["metric_name"]


async def test_n18_goal_history(client, w):
    ok(await client.put(_goal_url(w), headers=w.owner["headers"], json=GOAL_REQUEST), 200)
    ok(await client.put(_goal_url(w), headers=w.owner["headers"], json={**GOAL_REQUEST, "target": 2}), 200)
    body = ok(await client.get(f"/v1/players/{w.player['id']}/goals/history?mode=h", headers=w.player["headers"]),
              200).json()
    conforms(body, {"items": L(GOAL_HISTORY, nonempty=True), **PAGE})


async def test_n19_milestones(client, w):
    envelope = {"items": L(MILESTONE), **PAGE}
    body = ok(await client.get("/v1/me/milestones?mode=h", headers=w.player["headers"]), 200).json()
    conforms(body, envelope)
    goal = ok(await client.put(_goal_url(w), headers=w.owner["headers"], json=GOAL_REQUEST), 200).json()["goal"]
    async with get_session_factory()() as db:
        await db.execute(update(Goal).where(Goal.id == uuid.UUID(goal["id"]))
                         .values(outcome="met", ended_at=datetime.now(UTC)))
        await db.commit()
    body = ok(await client.get("/v1/me/milestones?mode=h", headers=w.player["headers"]), 200).json()
    conforms(body, {"items": L(MILESTONE, nonempty=True), **PAGE})


# ---------------------------------------------------------------------------------------------------------------
# Assignments (N20-N22)
# ---------------------------------------------------------------------------------------------------------------

async def test_n20_list_assignments(client, w):
    await _assignment(client, w)
    body = ok(await client.get("/v1/drill-assignments?mode=h", headers=w.player["headers"]), 200).json()
    conforms(body, {"items": L(ASSIGNMENT, nonempty=True), **PAGE})


async def test_n21_assign_drill(client, w):
    due = (datetime.now(UTC).date() + timedelta(days=1)).isoformat()
    body = ok(await client.post(f"/v1/coach/players/{w.player['id']}/drill-assignments", headers=w.owner["headers"],
                                json={**DRILL_BODY, "due_date": due}), 201).json()
    conforms(body, {"assignment": ASSIGNMENT})
    assert (body["assignment"]["sets"], body["assignment"]["reps"], body["assignment"]["done"]) == (3, 8, 0)
    assert body["assignment"]["due"] == "Tomorrow"


async def test_n22_log_set(client, w):
    assignment = await _assignment(client, w)
    request = {"set_number": 1, "reps_done": 8, "day": datetime.now(UTC).date().isoformat()}
    headers = {**w.player["headers"], "Idempotency-Key": "set-1"}
    body = ok(await client.post(f"/v1/drill-assignments/{assignment['id']}/sets", headers=headers, json=request),
              201).json()
    conforms(body, {"assignment": ASSIGNMENT, "set_log": {"id": U, "set_number": I, "reps_done": I, "day": DATE}})
    assert body["assignment"]["done"] == 1
    replay = ok(await client.post(f"/v1/drill-assignments/{assignment['id']}/sets", headers=headers, json=request),
                201).json()
    assert replay == body


# ---------------------------------------------------------------------------------------------------------------
# Arm care (N23-N25)
# ---------------------------------------------------------------------------------------------------------------

async def test_n23_read_arm_care(client, w):
    body = ok(await client.get("/v1/me/arm-care", headers=w.player["headers"]), 200).json()
    conforms(body, {"arm_care": ARM_CARE})
    assert body["arm_care"]["rest_status"] == "unknown" and body["arm_care"]["rule_version"] is None
    ok(await client.post("/v1/me/arm-care/outings", headers=w.player["headers"], json={"pitches": 45}), 201)
    body = ok(await client.get("/v1/me/arm-care", headers=w.player["headers"]), 200).json()
    conforms(body, {"arm_care": ARM_CARE})
    assert len(body["arm_care"]["outings"]) == 1


async def test_n24_log_outing(client, w):
    request = {"pitches": 45, "local_date": datetime.now(UTC).date().isoformat()}
    body = ok(await client.post("/v1/me/arm-care/outings", headers=w.player["headers"], json=request), 201).json()
    conforms(body, {"outing": OUTING, "arm_care": ARM_CARE})
    assert body["outing"]["label"] == "Game, logged by you" and body["arm_care"]["outings"] == [body["outing"]]


async def test_n25_record_feel(client, w):
    body = ok(await client.put("/v1/me/arm-care/feel", headers=w.player["headers"], json={"feel": "tight"}),
              200).json()
    conforms(body, {"feel": E("sore", "tight", "good"), "recorded_at": TS})
    assert body["feel"] == "tight"


# ---------------------------------------------------------------------------------------------------------------
# Coach access (N26-N27)
# ---------------------------------------------------------------------------------------------------------------

async def test_n26_read_coach_access(client, w):
    none = ok(await client.get("/v1/me/coach-access", headers=w.player["headers"]), 200).json()
    conforms(none, {"coach_access": COACH_ACCESS})
    code = await _staff_code(client, w.owner)
    who = await make_account("coach")
    ok(await client.post("/v1/me/coach-access", headers=who["headers"], json={"code": code["code"]}), 201)
    body = ok(await client.get("/v1/me/coach-access", headers=who["headers"]), 200).json()
    conforms(body, {"coach_access": COACH_ACCESS})
    assert body["coach_access"]["status"] == "pending" and body["coach_access"]["code"] == code["code"]
    assert body["coach_access"]["sent_at"] is not None


async def test_n27_apply_with_code(client, w):
    code = await _staff_code(client, w.owner)
    who = await make_account("coach")
    body = ok(await client.post("/v1/me/coach-access", headers=who["headers"], json={"code": code["code"]}),
              201).json()
    conforms(body, {"coach_access": COACH_ACCESS})
    assert body["coach_access"]["sent_at"] is not None
    again = ok(await client.post("/v1/me/coach-access", headers=who["headers"], json={"code": code["code"]}), 200)
    assert again.json() == body


# ---------------------------------------------------------------------------------------------------------------
# Groups, roster, notes (N28-N33)
# ---------------------------------------------------------------------------------------------------------------

async def test_n28_list_groups(client, w):
    body = ok(await client.get("/v1/academy/groups", headers=w.owner["headers"]), 200).json()
    conforms(body, {"items": L(GROUP, nonempty=True), **PAGE})
    assert body["items"][0]["players"] == 1 and body["items"][0]["coaches"] == ["Jamie K."]


async def test_n29_create_group(client, w):
    request = {"name": "16U", "focus": "Both", "coach_ids": [str(w.jamie["id"])], "player_ids": [str(w.player["id"])]}
    body = ok(await client.post("/v1/academy/groups", headers=w.owner["headers"], json=request), 201).json()
    conforms(body, {"group": GROUP})
    assert body["group"]["players"] == 1 and body["group"]["coach_ids"] == [str(w.jamie["id"])]


async def test_n30_read_note(client, w):
    url = f"/v1/coach/players/{w.player['id']}/note"
    blank = ok(await client.get(url, headers=w.owner["headers"]), 200).json()
    conforms(blank, {"note": NOTE})
    assert blank["note"]["text"] == "" and blank["note"]["updated_at"] is None and blank["note"]["version"] == 0
    ok(await client.put(url, headers=w.owner["headers"], json={"text": "Focus on balance."}), 200)
    body = ok(await client.get(url, headers=w.owner["headers"]), 200).json()
    conforms(body, {"note": NOTE})
    assert body["note"]["version"] == 1


async def test_n31_save_note(client, w):
    url = f"/v1/coach/players/{w.player['id']}/note"
    body = ok(await client.put(url, headers=w.owner["headers"],
                               json={"text": "Focus on balance before adding speed.", "expected_version": 0}),
              200).json()
    conforms(body, {"note": NOTE})
    assert body["note"]["version"] == 1 and body["note"]["player_id"] == str(w.player["id"])


@pytest.mark.xfail(strict=True,
    reason="CONTRACT: focus is 'both' for dual-focus players; spec N32 example is h (h/p only)")
async def test_n32_search_members(client, w):
    body = ok(await client.get("/v1/academy/members", headers=w.jamie["headers"]), 200).json()
    conforms(body, {"items": L(MEMBER, nonempty=True), **PAGE})
    assert body["items"][0]["group_ids"] == [str(w.group_id)]


async def test_n33_add_roster_players(client, w):
    request = {"player_ids": [str(w.player["id"])], "group_id": str(w.group_id)}
    body = ok(await client.post("/v1/coach/roster/players", headers=w.jamie["headers"], json=request), 200).json()
    conforms(body, {"added_player_ids": L(U), "already_present_player_ids": L(U)})
    assert body == {"added_player_ids": [str(w.player["id"])], "already_present_player_ids": []}


# ---------------------------------------------------------------------------------------------------------------
# Library (N35-N36)
# ---------------------------------------------------------------------------------------------------------------

async def _library_upload(owner_id):
    import os

    import boto3
    key = f"drills/{owner_id}/{uuid.uuid4()}.mp4"
    row = Upload(owner_id=owner_id, kind="drill_video", object_key=key, content_type="video/mp4", size_bytes=5)
    async with get_session_factory()() as db:
        db.add(row)
        await db.commit()
    boto3.client("s3", endpoint_url=os.environ["STORAGE_ENDPOINT"], region_name="us-east-1",
                 aws_access_key_id="test", aws_secret_access_key="test").put_object(
        Bucket="test-media", Key=key, Body=b"video", ContentType="video/mp4")
    return str(row.id)


@pytest.mark.xfail(strict=True,
    reason="CONTRACT: media has extra key seconds; spec N35 media is {upload_id,url,expires_at}")
async def test_n35_read_library(client, w):
    upload_id = await _library_upload(w.jamie["id"])
    ok(await client.post("/v1/academy/library", headers=w.jamie["headers"], json={
        "upload_id": upload_id, "name": "Posture wall drill", "mode": "h", "fault_tags": ["posture"],
        "fixes": "Posture"}), 201)
    body = ok(await client.get("/v1/academy/library", headers=w.owner["headers"]), 200).json()
    conforms(body, {"items": L(LIBRARY_DRILL, nonempty=True), **PAGE})


@pytest.mark.xfail(strict=True,
    reason="CONTRACT: media has extra key seconds; spec N36 media is {upload_id,url,expires_at}")
async def test_n36_publish_library_drill(client, w):
    upload_id = await _library_upload(w.jamie["id"])
    body = ok(await client.post("/v1/academy/library", headers=w.jamie["headers"], json={
        "upload_id": upload_id, "name": "Posture wall drill", "mode": "h", "fault_tags": ["posture"],
        "fixes": "Posture"}), 201).json()
    conforms(body, {"drill": LIBRARY_DRILL})
    assert body["drill"]["media"]["upload_id"] == upload_id


# ---------------------------------------------------------------------------------------------------------------
# Reporting (N37-N39)
# ---------------------------------------------------------------------------------------------------------------

async def test_n37_dashboard(client, w):
    await _review(client, w)
    body = ok(await client.get("/v1/academy/dashboard", headers=w.owner["headers"]), 200).json()
    conforms(body, {"dashboard": DASHBOARD}, extra={"unavailable_reason"})  # spec text: null "plus unavailable_reason"
    assert body["dashboard"]["month"] == datetime.now(UTC).strftime("%Y-%m")


async def test_n38_earnings(client, w):
    body = ok(await client.get("/v1/academy/earnings", headers=w.owner["headers"]), 200).json()
    conforms(body, {"earnings": EARNINGS}, extra={"unavailable_reason"})


@pytest.mark.xfail(strict=True,
    reason="CONTRACT: GET /v1/academy/corp is 403 for everyone (no grant mechanism); the 200 shape is unreachable")
async def test_n39_corporate(client, w):
    # No corporate grant mechanism exists, so no account can ever receive the documented 200 shape.
    body = ok(await client.get("/v1/academy/corp", headers=w.owner["headers"]), 200).json()
    conforms(body, {"corporate": CORPORATE})


async def test_n39_corporate_without_grant_is_403(client, w):
    ok(await client.get("/v1/academy/corp", headers=w.owner["headers"]), 403)


# ---------------------------------------------------------------------------------------------------------------
# Academy staff (N40-N48)
# ---------------------------------------------------------------------------------------------------------------

async def test_n40_list_coaches(client, w):
    body = ok(await client.get("/v1/academy/coaches", headers=w.owner["headers"]), 200).json()
    conforms(body, {"items": L(COACH_MEMBER, nonempty=True), **PAGE})
    assert {i["role"] for i in body["items"]} == {"admin", "coach"}


async def test_n41_coach_detail(client, w):
    body = ok(await client.get(f"/v1/academy/coaches/{w.jamie['id']}", headers=w.owner["headers"]), 200).json()
    conforms(body, {"coach": COACH_MEMBER})
    assert body["coach"]["version"] == 1 and body["coach"]["activity"] is not None


async def test_n42_edit_coach(client, w):
    request = {"role": "assistant", "sees_all": False, "group_ids": [str(w.group_id)],
               "permissions": {"review": True, "drills": False, "goals": False, "library": False, "earnings": False},
               "expected_version": 1}
    body = ok(await client.patch(f"/v1/academy/coaches/{w.jamie['id']}", headers=w.owner["headers"], json=request),
              200).json()
    conforms(body, {"coach": COACH_MEMBER})
    assert body["coach"]["role"] == "assistant" and body["coach"]["version"] == 2


async def test_n43_remove_coach(client, w):
    other = await _staff(w.team_id, name="Other C.")
    empty(await client.delete(f"/v1/academy/coaches/{w.jamie['id']}?reassign_to={other['id']}",
                              headers=w.owner["headers"]))
    empty(await client.delete(f"/v1/academy/coaches/{w.jamie['id']}?reassign_to={other['id']}",
                              headers=w.owner["headers"]))


async def test_n44_list_requests(client, w):
    code = await _staff_code(client, w.owner)
    who = await make_account("coach", name="Alex R.")
    ok(await client.post("/v1/me/coach-access", headers=who["headers"], json={"code": code["code"]}), 201)
    body = ok(await client.get("/v1/academy/coach-requests", headers=w.owner["headers"]), 200).json()
    conforms(body, {"items": L(COACH_REQUEST, nonempty=True), "total_pending": I, **PAGE})
    assert body["total_pending"] == 1 and body["items"][0]["status"] == "pending"


async def test_n45_decide_request(client, w):
    code = await _staff_code(client, w.owner)
    who = await make_account("coach", name="Alex R.")
    ok(await client.post("/v1/me/coach-access", headers=who["headers"], json={"code": code["code"]}), 201)
    request = (await client.get("/v1/academy/coach-requests", headers=w.owner["headers"])).json()["items"][0]
    body = ok(await client.post(f"/v1/academy/coach-requests/{request['id']}/decision", headers=w.owner["headers"],
                                json={"decision": "approve", "role": "assistant", "sees_all": False,
                                      "group_ids": [str(w.group_id)]}), 200).json()
    conforms(body, {"request": COACH_REQUEST, "coach": COACH_MEMBER})
    assert body["request"]["status"] == "approved" and body["coach"]["role"] == "assistant"


async def test_n45_decline_request_shape(client, w):
    code = await _staff_code(client, w.owner)
    who = await make_account("coach", name="Alex R.")
    ok(await client.post("/v1/me/coach-access", headers=who["headers"], json={"code": code["code"]}), 201)
    request = (await client.get("/v1/academy/coach-requests", headers=w.owner["headers"])).json()["items"][0]
    body = ok(await client.post(f"/v1/academy/coach-requests/{request['id']}/decision", headers=w.owner["headers"],
                                json={"decision": "decline"}), 200).json()
    conforms(body["request"], COACH_REQUEST)
    assert body["request"]["status"] == "declined"


async def test_n46_list_codes(client, w):
    await _staff_code(client, w.owner)
    body = ok(await client.get("/v1/academy/staff-codes", headers=w.owner["headers"]), 200).json()
    conforms(body, {"items": L(STAFF_CODE, nonempty=True), **PAGE})


async def test_n47_generate_code(client, w):
    request = {"role": "coach", "expires_days": 7, "max_uses": 5, "approval": "admin"}
    body = ok(await client.post("/v1/academy/staff-codes", headers=w.owner["headers"], json=request), 201).json()
    conforms(body, {"staff_code": STAFF_CODE})
    assert body["staff_code"]["uses"] == 0 and body["staff_code"]["max_uses"] == 5
    assert body["staff_code"]["status"] == "active"


async def test_n48_revoke_code(client, w):
    code = await _staff_code(client, w.owner)
    empty(await client.delete(f"/v1/academy/staff-codes/{code['code']}", headers=w.owner["headers"]))
    empty(await client.delete(f"/v1/academy/staff-codes/{code['code']}", headers=w.owner["headers"]))


# ---------------------------------------------------------------------------------------------------------------
# Consent administration (N49-N50)
# ---------------------------------------------------------------------------------------------------------------

async def _accept(account_id):
    async with get_session_factory()() as db:
        db.add(ConsentEvent(account_id=account_id, category="analysis", action="accepted", policy_version="1.0"))
        await db.commit()


async def test_n49_consent_records(client, w):
    await _accept(w.player["id"])
    body = ok(await client.get("/v1/academy/consent", headers=w.owner["headers"]), 200).json()
    conforms(body, {"accepted": I, "ai_opt_in": I, "items": L(CONSENT_ITEM, nonempty=True), **PAGE})
    assert body["accepted"] == 1 and body["items"][0]["group"] == "14U"


async def test_n50_consent_export(client, w):
    await _accept(w.player["id"])
    body = ok(await client.post("/v1/academy/consent/export", headers=w.owner["headers"], json={"format": "csv"}),
              201).json()
    conforms(body, {"export": {"id": U, "status": E("ready"), "url": S, "expires_at": TS, "filename": S}})
    assert body["export"]["filename"].endswith(".csv")


# ---------------------------------------------------------------------------------------------------------------
# Error envelope (spec 4.1)
# ---------------------------------------------------------------------------------------------------------------

async def test_error_envelopes(client, w):
    missing = await client.get(f"/v1/threads/{uuid.uuid4()}", headers=w.player["headers"])
    ok(missing, 404)
    conforms(missing.json(), {"error": {"code": S, "message": S}})
    assert missing.headers.get("X-Request-ID")
    unauth = ok(await client.get("/v1/notifications"), 401)
    conforms(unauth.json(), {"error": {"code": E("UNAUTHENTICATED"), "message": S}})
    bad = ok(await client.post("/v1/me/arm-care/outings", headers=w.player["headers"], json={"pitches": 0}), 400)
    conforms(bad.json(), {"error": {"code": E("VALIDATION"), "message": S, "fields": M(S)}})
    stale = ok(await client.patch("/v1/me/settings", headers=w.player["headers"],
                                  json={"private_links": True, "expected_version": 9}), 409)
    conforms(stale.json(), {"error": {"code": E("STALE_VERSION"), "message": S}})
    forbidden = ok(await client.get("/v1/academy/staff-codes", headers=w.player["headers"]), 403)
    conforms(forbidden.json(), {"error": {"code": E("FORBIDDEN"), "message": S}})