File size: 56,358 Bytes
fe40b87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be69d1e
 
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
"""QA: adversarial authorization / tenancy / integrity checks over the coaching-workflow API delta.

Tests marked xfail(strict=True) are CONFIRMED defects ("QA BUG: ..."): flip them (remove the marker) after the fix.
Everything else pins behaviour that is correct today.
"""

import asyncio
import csv
import io
import uuid
from datetime import UTC, datetime, timedelta

import httpx
import pytest
from sqlalchemy import func, select, update

from app.common.academy_access import normalize_permissions
from app.core.config import get_settings
from app.core.database import get_session_factory
from app.integrations.push import get_push_client
from app.modules.academy.models import AcademyMembership, CoachPlayer
from app.modules.assignments.models import AssignmentSet
from app.modules.goals.models import Goal
from app.modules.notifications.models import Notification
from app.modules.threads.models import Message
from tests.factories import (
    JPEG,
    VIDEO,
    FakePush,
    create_team,
    join,
    make_account,
    make_session,
    make_team_row,
    session_body,
    upload,
)
from tests.integration.test_swing_reports import PAYLOAD

REVIEW = {"cue": "Stay tall.", "drill_id": "hit_01", "verdicts": {}}
GOAL = {"type": "score", "target": 80, "due": "1 week", "weekly": {"practice_days": 3, "drill_sets": 5}}
AUDIO = b"\x00\x00\x00\x18ftypM4A " + b"\x00" * 40


def today() -> str:
    return datetime.now(UTC).date().isoformat()


def tomorrow() -> str:
    return (datetime.now(UTC).date() + timedelta(days=1)).isoformat()


ASSIGN = {"mode": "h", "drill_source": "catalog", "drill_id": "hit_13"}


def assign_body(**extra) -> dict:
    return {**ASSIGN, "due_date": tomorrow(), **extra}


@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)


# ---------- builders ----------

async def academy(players: int = 2):
    """Owner (implicit admin), a team row and `players` players on it."""
    owner = await make_account("coach", name="Owner")
    ps = [await make_account("player", name=f"Player {i}") for i in range(players)]
    team_id = await make_team_row(owner, *ps)
    return owner, team_id, ps


async def staff(team_id, role="coach", *, sees_all=False, status="active", perms=None, joined_with=None,
                name="Staffer", roster_for=()):
    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=status,
                                 sees_all=sees_all, permissions=normalize_permissions(role, perms),
                                 joined_with=joined_with))
        for player in roster_for:
            db.add(CoachPlayer(team_id=team_id, coach_id=account["id"], player_id=player["id"]))
        await db.commit()
    return account


async def set_membership(team_id, account, **values):
    async with get_session_factory()() as db:
        await db.execute(update(AcademyMembership).where(AcademyMembership.team_id == team_id,
                                                         AcademyMembership.account_id == account["id"])
                         .values(**values))
        await db.commit()


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


async def send_text(client, who, thread_id, text="hello"):
    return await client.post(f"/v1/threads/{thread_id}/messages", headers=who["headers"],
                             json={"kind": "text", "text": text})


async def raw_upload(client, who, kind, content_type, data, *, put=True, duration=5):
    body = {"kind": kind, "content_type": content_type, "size_bytes": len(data)}
    if kind in ("video", "audio", "drill_video"):
        body["duration_sec"] = duration
    response = await client.post("/v1/uploads", headers=who["headers"], json=body)
    assert response.status_code == 201, response.text
    target = response.json()
    if put:
        async with httpx.AsyncClient() as s3:
            assert (await s3.put(target["url"], content=data, headers=target["headers"])).status_code == 200
    return target["upload_id"]


async def audio(client, who, **kw):
    return await raw_upload(client, who, "audio", "audio/mp4", AUDIO, **kw)


async def drill_video(client, who, **kw):
    return await raw_upload(client, who, "drill_video", "video/mp4", VIDEO, **kw)


async def sharing(client, player, value: bool):
    response = await client.patch("/v1/me/settings", headers=player["headers"], json={"coach_can_see_sessions": value})
    assert response.status_code == 200, response.text


# ======================================================================================================
# CONFIRMED BUGS (xfail strict)
# ======================================================================================================

async def test_session_media_hidden_when_player_stops_sharing(client):
    owner, _, [player, _] = await academy()
    sid = await make_session(player["id"])
    assert (await client.get(f"/v1/sessions/{sid}", headers=owner["headers"])).status_code == 200
    await sharing(client, player, False)
    response = await client.get(f"/v1/sessions/{sid}", headers=owner["headers"])
    assert response.status_code in (403, 404), response.text


async def test_rostered_staff_coach_can_open_visible_players_session(client):
    owner, team_id, [player, _] = await academy()
    coach = await staff(team_id, "coach", roster_for=[player])
    sid = await make_session(player["id"])
    listed = await client.get(f"/v1/coach/players/{player['id']}/sessions", headers=coach["headers"])
    assert listed.status_code == 200 and listed.json()["items"]
    response = await client.get(f"/v1/sessions/{sid}", headers=coach["headers"])
    assert response.status_code == 200, response.text


async def test_ex_coach_loses_thread_after_player_leaves_team(client):
    owner, _, [player, _] = await academy()
    thread_id = await general_thread(client, owner, player)
    assert (await send_text(client, player, thread_id, "private note about my arm")).status_code == 201
    assert (await client.delete("/v1/me/team", headers=player["headers"])).status_code == 204
    assert (await client.get(f"/v1/threads/{thread_id}", headers=owner["headers"])).status_code == 404
    listed = (await client.get("/v1/threads", headers=owner["headers"])).json()["items"]
    assert thread_id not in [t["id"] for t in listed]
    assert (await send_text(client, owner, thread_id, "still here?")).status_code == 404


async def test_coach_removed_from_roster_loses_existing_thread(client):
    owner, team_id, [player, _] = await academy()
    coach = await staff(team_id, "coach", roster_for=[player])
    thread_id = await general_thread(client, coach, player)
    async with get_session_factory()() as db:
        from sqlalchemy import delete
        await db.execute(delete(CoachPlayer).where(CoachPlayer.coach_id == coach["id"]))
        await db.commit()
    assert (await client.get(f"/v1/threads/{thread_id}", headers=coach["headers"])).status_code == 404


async def test_deleted_session_thread_not_served_to_coach(client):
    owner, _, [player, _] = await academy()
    sid = await make_session(player["id"])
    assert (await client.post(f"/v1/sessions/{sid}/review", headers=owner["headers"], json=REVIEW)).status_code == 201
    assert (await client.delete(f"/v1/sessions/{sid}", headers=player["headers"])).status_code == 204
    response = await client.get(f"/v1/sessions/{sid}/thread", headers=owner["headers"])
    assert response.status_code == 404 or response.json()["thread"]["score"] is None, response.text


async def test_decision_idempotency_key_not_replayed_across_requests(client):
    owner, team_id, _ = await academy()
    code = (await client.post("/v1/academy/staff-codes", headers=owner["headers"], json={
        "role": "coach", "expires_days": 7, "max_uses": 5, "approval": "admin"})).json()["staff_code"]["code"]
    applicants = [await make_account("coach", name=f"App {i}") for i in range(2)]
    for who in applicants:
        assert (await client.post("/v1/me/coach-access", headers=who["headers"],
                                  json={"code": code})).status_code == 201
    pending = (await client.get("/v1/academy/coach-requests?status=pending", headers=owner["headers"])).json()["items"]
    ids = [r["id"] for r in pending]
    headers = {**owner["headers"], "Idempotency-Key": "same-key"}
    body = {"decision": "approve", "role": "coach"}
    first = await client.post(f"/v1/academy/coach-requests/{ids[0]}/decision", headers=headers, json=body)
    second = await client.post(f"/v1/academy/coach-requests/{ids[1]}/decision", headers=headers, json=body)
    assert first.status_code == 200
    assert second.status_code == 409 or second.json()["request"]["id"] == ids[1], second.text


async def test_assistant_cannot_see_colleagues_staff_code(client):
    owner, team_id, _ = await academy()
    await staff(team_id, "coach", name="Other Coach", joined_with="CV-SECR-ET")
    assistant = await staff(team_id, "assistant", name="Asst")
    response = await client.get("/v1/academy/coaches", headers=assistant["headers"])
    assert response.status_code == 200
    others = [c for c in response.json()["items"] if not c["is_me"]]
    assert others and all(c["joined_with"] is None for c in others), response.json()


async def test_library_upload_cannot_be_published_twice(client):
    owner, _, _ = await academy()
    upload_id = await drill_video(client, owner)
    body = {"upload_id": upload_id, "name": "Tee work", "mode": "h", "fault_tags": ["hips"]}
    assert (await client.post("/v1/academy/library", headers=owner["headers"], json=body)).status_code == 201
    second = await client.post("/v1/academy/library", headers=owner["headers"], json={**body, "name": "Copy"})
    assert second.status_code in (409, 422), second.text


async def test_review_voice_upload_cannot_be_reused_in_message(client):
    owner, _, [player, _] = await academy()
    sid = await make_session(player["id"])
    audio_id = await audio(client, owner)
    review = await client.post(f"/v1/sessions/{sid}/review", headers=owner["headers"],
                               json={**REVIEW, "voice_note_upload_id": audio_id, "voice_note_seconds": 5})
    assert review.status_code == 201, review.text
    thread_id = await general_thread(client, owner, player)
    reuse = await client.post(f"/v1/threads/{thread_id}/messages", headers=owner["headers"],
                              json={"kind": "voice", "upload_id": audio_id, "seconds": 5})
    assert reuse.status_code in (409, 422), reuse.text


async def test_one_audio_upload_cannot_back_two_reviews(client):
    owner, _, [p1, p2] = await academy()
    s1, s2 = await make_session(p1["id"]), await make_session(p2["id"])
    audio_id = await audio(client, owner)
    body = {**REVIEW, "voice_note_upload_id": audio_id, "voice_note_seconds": 5}
    assert (await client.post(f"/v1/sessions/{s1}/review", headers=owner["headers"], json=body)).status_code == 201
    second = await client.post(f"/v1/sessions/{s2}/review", headers=owner["headers"], json=body)
    assert second.status_code in (409, 422), second.text


async def test_swing_report_blocked_after_consent_withdrawn(client):
    player = await make_account("player", level=None, bats=None)
    assert (await client.post("/v1/me/consent", headers=player["headers"],
                              json={"version": "1.0", "accepted": True})).status_code == 201
    sid = await make_session(player["id"], analyzed=False)
    assert (await client.delete("/v1/me/consent", headers=player["headers"])).status_code == 204
    response = await client.post(f"/v1/sessions/{sid}/swing-report?queue=false", headers=player["headers"],
                                 json=PAYLOAD)
    assert response.status_code == 403, response.text


async def test_other_staff_reading_does_not_clear_coachs_unread(client):
    owner, team_id, [player, _] = await academy()
    coach = await staff(team_id, "coach", roster_for=[player])
    thread_id = await general_thread(client, coach, player)
    message = (await send_text(client, player, thread_id, "coach, question")).json()["message"]
    assert (await client.get(f"/v1/threads/{thread_id}", headers=coach["headers"])).json()["thread"][
        "unread_for_coach"] is True
    assert (await client.post(f"/v1/threads/{thread_id}/read", headers=owner["headers"],
                              json={"last_message_id": message["id"]})).status_code == 204
    view = (await client.get(f"/v1/threads/{thread_id}", headers=coach["headers"])).json()["thread"]
    assert view["unread_for_coach"] is True


async def test_coach_account_deletion_keeps_players_thread_and_review(client):
    owner, team_id, [player, _] = await academy()
    coach = await staff(team_id, "coach", roster_for=[player])
    sid = await make_session(player["id"])
    assert (await client.post(f"/v1/sessions/{sid}/review", headers=coach["headers"], json=REVIEW)).status_code == 201
    assert (await client.delete("/v1/me", headers=coach["headers"])).status_code == 204
    response = await client.get(f"/v1/sessions/{sid}/thread", headers=player["headers"])
    assert response.status_code == 200, response.text


async def test_outing_with_old_local_date_is_a_clean_result(client):
    player = await make_account("player")
    response = await client.post("/v1/me/arm-care/outings", headers=player["headers"],
                                 json={"pitches": 30, "local_date": "2020-01-01"})
    assert response.status_code == 201 or "local_date" in response.json()["error"]["fields"], response.text


async def test_concurrent_first_reviews_do_not_500(client):
    owner, _, [player, _] = await academy()
    sid = await make_session(player["id"])
    results = await asyncio.gather(*[
        client.post(f"/v1/sessions/{sid}/review", headers=owner["headers"], json=REVIEW) for _ in range(3)],
        return_exceptions=True)
    codes = [r.status_code if isinstance(r, httpx.Response) else repr(r) for r in results]
    assert all(c in (200, 201) for c in codes), codes


async def test_new_academy_staff_cannot_read_old_academy_threads(client):
    a = await make_account("coach", name="Coach A")
    team_a = await create_team(client, a, name="Team A")
    b = await make_account("coach", name="Coach B")
    team_b = await create_team(client, b, name="Team B")
    player = await make_account("player", name="Mover")
    await join(client, player, team_a["code"])
    thread_id = await general_thread(client, a, player)
    assert (await send_text(client, a, thread_id, "A's private coaching history")).status_code == 201
    await join(client, player, team_b["code"])
    assert (await client.get(f"/v1/threads/{thread_id}", headers=b["headers"])).status_code == 404
    assert thread_id not in [t["id"] for t in (await client.get("/v1/threads", headers=b["headers"])).json()["items"]]


async def test_removed_coach_cannot_rejoin_with_auto_code(client):
    owner, team_id, _ = await academy()
    code = (await client.post("/v1/academy/staff-codes", headers=owner["headers"], json={
        "role": "coach", "expires_days": 30, "max_uses": 20, "approval": "auto"})).json()["staff_code"]["code"]
    coach = await make_account("coach")
    assert (await client.post("/v1/me/coach-access", headers=coach["headers"], json={"code": code})).status_code == 201
    assert (await client.delete(f"/v1/academy/coaches/{coach['id']}?reassign_to={owner['id']}",
                                headers=owner["headers"])).status_code == 204
    again = await client.post("/v1/me/coach-access", headers=coach["headers"], json={"code": code})
    me = (await client.get("/v1/me", headers=coach["headers"])).json()
    assert again.status_code >= 400 or me["academy"] is None, me


# ======================================================================================================
# CORRECT BEHAVIOUR (regression pins)
# ======================================================================================================

async def two_academies(client):
    a_owner, a_team, [a_p1, a_p2] = await academy()
    b_owner = await make_account("coach", name="Outsider")
    b_team = await create_team(client, b_owner, name="Other Academy")
    return {"owner": a_owner, "team": a_team, "p1": a_p1, "p2": a_p2, "outsider": b_owner, "b_team": b_team}


async def test_other_academy_coach_gets_404_on_every_player_resource(client):
    ctx = await two_academies(client)
    owner, p1, out = ctx["owner"], ctx["p1"], ctx["outsider"]["headers"]
    sid = await make_session(p1["id"])
    assert (await client.post(f"/v1/sessions/{sid}/review", headers=owner["headers"], json=REVIEW)).status_code == 201
    thread_id = await general_thread(client, owner, p1)
    assign = await client.post(f"/v1/coach/players/{p1['id']}/drill-assignments", headers=owner["headers"],
                               json=assign_body())
    assert assign.status_code == 201, assign.text
    pid = p1["id"]
    calls = [
        ("GET", f"/v1/players/{pid}/goals?mode=h", None, 404),
        ("PUT", f"/v1/players/{pid}/goals/h", GOAL, 404),
        ("GET", f"/v1/players/{pid}/goals/history?mode=h", None, 404),
        ("POST", f"/v1/coach/players/{pid}/drill-assignments", assign_body(), 404),
        ("GET", f"/v1/drill-assignments?mode=h&player_id={pid}", None, 404),
        ("GET", f"/v1/coach/players/{pid}/note", None, 404),
        ("PUT", f"/v1/coach/players/{pid}/note", {"text": "x"}, 404),
        ("GET", f"/v1/coach/players/{pid}/sessions", None, 404),
        ("POST", f"/v1/coach/players/{pid}/thread", {"mode": "h"}, 404),
        ("POST", "/v1/coach/roster/players", {"player_ids": [str(pid)]}, 404),
        ("POST", "/v1/academy/groups", {"name": "x", "focus": "Both", "player_ids": [str(pid)]}, 404),
        ("GET", f"/v1/threads/{thread_id}", None, 404),
        ("GET", f"/v1/sessions/{sid}/thread", None, 404),
        ("POST", f"/v1/threads/{thread_id}/messages", {"kind": "text", "text": "hi"}, 404),
        ("POST", f"/v1/threads/{thread_id}/read", {"last_message_id": None}, 404),
        ("GET", f"/v1/sessions/{sid}", None, 403),
        ("POST", f"/v1/sessions/{sid}/review", REVIEW, 403),
        ("GET", f"/v1/academy/coaches/{ctx['owner']['id']}", None, 404),
        ("PATCH", f"/v1/academy/coaches/{ctx['owner']['id']}", {"status": "paused"}, 409),  # owner of A is not B's
    ]
    failures = []
    for method, url, body, expected in calls:
        response = await client.request(method, url, headers=out, json=body)
        if response.status_code != expected and not (expected == 409 and response.status_code == 404):
            failures.append((method, url, response.status_code, expected))
    assert not failures, failures
    listed = (await client.get("/v1/threads", headers=out)).json()["items"]
    assert listed == []
    assert (await client.get("/v1/drill-assignments?mode=h", headers=out)).json()["items"] == []


async def test_cross_academy_ids_in_academy_admin_calls(client):
    ctx = await two_academies(client)
    a, b = ctx["owner"]["headers"], ctx["outsider"]["headers"]
    code = (await client.post("/v1/academy/staff-codes", headers=a, json={
        "role": "coach", "expires_days": 7, "max_uses": 5, "approval": "admin"})).json()["staff_code"]["code"]
    applicant = await make_account("coach")
    assert (await client.post("/v1/me/coach-access", headers=applicant["headers"],
                              json={"code": code})).status_code == 201
    request_id = (await client.get("/v1/academy/coach-requests", headers=a)).json()["items"][0]["id"]
    member = await staff(ctx["team"], "coach")
    assert (await client.delete(f"/v1/academy/staff-codes/{code}", headers=b)).status_code == 404
    assert (await client.post(f"/v1/academy/coach-requests/{request_id}/decision", headers=b,
                              json={"decision": "approve"})).status_code == 404
    assert (await client.patch(f"/v1/academy/coaches/{member['id']}", headers=b,
                               json={"status": "paused"})).status_code == 404
    assert (await client.get(f"/v1/academy/coaches/{member['id']}", headers=b)).status_code == 404
    assert (await client.delete(f"/v1/academy/coaches/{member['id']}?reassign_to={ctx['outsider']['id']}",
                                headers=b)).status_code == 404
    assert (await client.get("/v1/academy/staff-codes", headers=b)).json()["items"] == []
    assert (await client.get("/v1/academy/coach-requests", headers=b)).json()["items"] == []
    group = (await client.post("/v1/academy/groups", headers=a, json={"name": "A-only", "focus": "Both"})).json()[
        "group"]
    assert (await client.get(f"/v1/academy/consent?group_id={group['id']}", headers=b)).status_code == 404
    assert (await client.post("/v1/academy/consent/export", headers=b,
                              json={"group_id": group["id"]})).status_code == 404
    # B cannot name A's coach or player in its own group
    assert (await client.post("/v1/academy/groups", headers=b, json={
        "name": "x", "focus": "Both", "coach_ids": [str(member["id"])]})).status_code == 404
    assert (await client.post("/v1/coach/roster/players", headers=b, json={
        "player_ids": [str(ctx["p1"]["id"])], "group_id": group["id"]})).status_code == 404


async def test_library_drill_of_other_academy_cannot_be_assigned_or_listed(client):
    ctx = await two_academies(client)
    upload_id = await drill_video(client, ctx["owner"])
    drill = (await client.post("/v1/academy/library", headers=ctx["owner"]["headers"], json={
        "upload_id": upload_id, "name": "Mine", "mode": "h", "fault_tags": ["x"]})).json()["drill"]
    b_player = await make_account("player")
    await join(client, b_player, (await client.get("/v1/me", headers=ctx["outsider"]["headers"])).json()["team"][
        "code"])
    response = await client.post(f"/v1/coach/players/{b_player['id']}/drill-assignments",
                                 headers=ctx["outsider"]["headers"],
                                 json={"mode": "h", "drill_source": "library", "drill_id": drill["id"],
                                       "due_date": tomorrow()})
    assert response.status_code == 404
    assert (await client.get("/v1/academy/library", headers=ctx["outsider"]["headers"])).json()["items"] == []


async def test_player_cannot_touch_other_players_resources_or_staff_endpoints(client):
    ctx = await two_academies(client)
    owner, p1, p2 = ctx["owner"], ctx["p1"], ctx["p2"]
    thread_id = await general_thread(client, owner, p1)
    assert (await send_text(client, owner, thread_id)).status_code == 201
    assignment = (await client.post(f"/v1/coach/players/{p1['id']}/drill-assignments", headers=owner["headers"],
                                    json=assign_body())).json()["assignment"]
    await client.put(f"/v1/players/{p1['id']}/goals/h", headers=owner["headers"], json=GOAL)
    note = (await client.get("/v1/notifications", headers=p1["headers"])).json()["items"][0]
    h = p2["headers"]
    pid = p1["id"]
    checks = [
        ("GET", f"/v1/threads/{thread_id}", None, 404),
        ("POST", f"/v1/threads/{thread_id}/messages", {"kind": "text", "text": "x"}, 404),
        ("POST", f"/v1/threads/{thread_id}/read", {"last_message_id": None}, 404),
        ("GET", f"/v1/players/{pid}/goals?mode=h", None, 404),
        ("GET", f"/v1/drill-assignments?mode=h&player_id={pid}", None, 404),
        ("POST", f"/v1/drill-assignments/{assignment['id']}/sets",
         {"set_number": 1, "reps_done": 3, "day": today()}, 404),
        ("POST", f"/v1/notifications/{note['id']}/read", None, 404),
        ("GET", "/v1/coach/roster", None, 403),
        ("GET", "/v1/coach/queue", None, 403),
        ("GET", f"/v1/coach/players/{pid}/sessions", None, 403),
        ("PUT", f"/v1/players/{pid}/goals/h", GOAL, 403),
        ("POST", f"/v1/coach/players/{pid}/drill-assignments", assign_body(), 403),
        ("GET", f"/v1/coach/players/{pid}/note", None, 403),
        ("POST", f"/v1/coach/players/{pid}/thread", {"mode": "h"}, 403),
        ("GET", "/v1/academy/coaches", None, 403),
        ("GET", "/v1/academy/dashboard", None, 403),
        ("GET", "/v1/academy/consent", None, 403),
        ("GET", "/v1/academy/staff-codes", None, 403),
        ("GET", "/v1/academy/coach-requests", None, 403),
        ("GET", "/v1/academy/library", None, 403),
        ("POST", "/v1/academy/library", {"upload_id": str(uuid.uuid4()), "name": "x", "mode": "h",
                                         "fault_tags": ["x"]}, 403),
        ("GET", "/v1/academy/members", None, 403),
    ]
    failures = []
    for method, url, body, expected in checks:
        response = await client.request(method, url, headers=h, json=body)
        if response.status_code != expected:
            failures.append((method, url, response.status_code, expected))
    assert not failures, failures
    assert (await client.get("/v1/threads", headers=h)).json()["items"] == []
    assert (await client.get("/v1/drill-assignments?mode=h", headers=h)).json()["items"] == []


@pytest.mark.parametrize("status", ["paused", "removed"])
async def test_paused_or_removed_staff_lose_every_academy_path_with_old_token(client, status):
    owner, team_id, [player, other] = await academy()
    coach = await staff(team_id, "coach", sees_all=True, perms={"library": True}, roster_for=[player])
    h = coach["headers"]
    # state created while still active
    thread_id = await general_thread(client, coach, player)
    sid = await make_session(player["id"])
    assert (await client.post(f"/v1/sessions/{sid}/review", headers=h, json=REVIEW)).status_code == 201
    assert (await client.put(f"/v1/coach/players/{player['id']}/note", headers=h,
                             json={"text": "mine"})).status_code == 200
    assign = await client.post(f"/v1/coach/players/{player['id']}/drill-assignments", headers=h, json=assign_body())
    assert assign.status_code == 201
    upload_id = await drill_video(client, coach)
    assert (await client.post("/v1/academy/library", headers=h, json={
        "upload_id": upload_id, "name": "d", "mode": "h", "fault_tags": ["x"]})).status_code == 201
    await set_membership(team_id, coach, status=status)

    pid = player["id"]
    denied = [
        ("GET", f"/v1/threads/{thread_id}", None),
        ("POST", f"/v1/threads/{thread_id}/messages", {"kind": "text", "text": "x"}),
        ("POST", f"/v1/threads/{thread_id}/read", {"last_message_id": None}),
        ("GET", f"/v1/sessions/{sid}/thread", None),
        ("GET", f"/v1/coach/players/{pid}/note", None),
        ("PUT", f"/v1/coach/players/{pid}/note", {"text": "x"}),
        ("GET", f"/v1/players/{pid}/goals?mode=h", None),
        ("PUT", f"/v1/players/{pid}/goals/h", GOAL),
        ("GET", f"/v1/players/{pid}/goals/history?mode=h", None),
        ("POST", f"/v1/coach/players/{pid}/drill-assignments", assign_body()),
        ("GET", f"/v1/drill-assignments?mode=h&player_id={pid}", None),
        ("GET", f"/v1/coach/players/{pid}/sessions", None),
        ("POST", f"/v1/coach/players/{pid}/thread", {"mode": "h"}),
        ("POST", f"/v1/sessions/{sid}/review", REVIEW),
        ("GET", f"/v1/sessions/{sid}", None),
        ("POST", "/v1/coach/roster/players", {"player_ids": [str(other["id"])]}),
        ("GET", "/v1/academy/coaches", None),
        ("POST", "/v1/uploads", {"kind": "drill_video", "content_type": "video/mp4", "size_bytes": 100,
                                 "duration_sec": 5}),
        ("POST", "/v1/academy/library", {"upload_id": upload_id, "name": "x", "mode": "h", "fault_tags": ["x"]}),
    ]
    failures = []
    for method, url, body in denied:
        response = await client.request(method, url, headers=h, json=body)
        if response.status_code not in (403, 404):
            failures.append((method, url, response.status_code))
    assert not failures, failures
    empty = ["/v1/threads", "/v1/coach/roster", "/v1/coach/queue", "/v1/academy/library",
             "/v1/academy/groups", "/v1/academy/members", "/v1/drill-assignments?mode=h"]
    for url in empty:
        response = await client.get(url, headers=h)
        body = response.json()
        assert response.status_code == 403 or (
            response.status_code == 200 and (body.get("items") == [] or body.get("open") == [])), (url, body)
    me = (await client.get("/v1/me", headers=h)).json()
    assert me["academy"] is None and me["capabilities"]["academy_admin"] is False


async def test_paused_player_role_member_gets_no_staff_access(client):
    owner, team_id, [player, other] = await academy()
    dual = await make_account("player", name="Dual")
    async with get_session_factory()() as db:
        db.add(AcademyMembership(team_id=team_id, account_id=dual["id"], role="coach", status="paused",
                                 sees_all=True, permissions=normalize_permissions("coach")))
        await db.commit()
    for url in ("/v1/coach/roster", f"/v1/coach/players/{player['id']}/note", "/v1/academy/coaches"):
        assert (await client.get(url, headers=dual["headers"])).status_code == 403


async def test_assistant_cannot_bypass_drill_goal_library_or_admin_restrictions(client):
    owner, team_id, [player, _] = await academy()
    assistant = await staff(team_id, "assistant", sees_all=True, perms={"drills": True, "goals": True,
                                                                         "library": False})
    h, pid = assistant["headers"], player["id"]
    # even "grants" in the stored row are stripped at read time
    assert (await client.post(f"/v1/coach/players/{pid}/drill-assignments", headers=h,
                              json=assign_body())).status_code == 403
    assert (await client.put(f"/v1/players/{pid}/goals/h", headers=h, json=GOAL)).status_code == 403
    assert (await client.post("/v1/uploads", headers=h, json={
        "kind": "drill_video", "content_type": "video/mp4", "size_bytes": 10, "duration_sec": 3})).status_code == 403
    for method, url, body in [
        ("GET", "/v1/academy/staff-codes", None), ("POST", "/v1/academy/staff-codes", {
            "role": "coach", "expires_days": 7, "max_uses": 5, "approval": "auto"}),
        ("GET", "/v1/academy/coach-requests", None), ("GET", "/v1/academy/dashboard", None),
        ("GET", "/v1/academy/earnings", None), ("GET", "/v1/academy/consent", None),
        ("POST", "/v1/academy/groups", {"name": "g", "focus": "Both"}),
        ("PATCH", f"/v1/academy/coaches/{assistant['id']}", {"role": "admin"}),
        ("GET", f"/v1/academy/coaches/{owner['id']}", None)]:
        assert (await client.request(method, url, headers=h, json=body)).status_code == 403, (method, url)
    # allowed: review and message
    sid = await make_session(player["id"])
    assert (await client.post(f"/v1/sessions/{sid}/review", headers=h, json=REVIEW)).status_code == 201
    thread_id = await general_thread(client, assistant, player)
    assert (await send_text(client, assistant, thread_id)).status_code == 201
    # an admin cannot hand an assistant drills/goals through PATCH either
    patched = await client.patch(f"/v1/academy/coaches/{assistant['id']}", headers=owner["headers"],
                                 json={"permissions": {"drills": True, "goals": True, "library": True}})
    perms = patched.json()["coach"]["permissions"]
    assert perms["drills"] is False and perms["goals"] is False


async def test_coach_without_library_permission_cannot_upload_or_publish(client):
    owner, team_id, _ = await academy()
    coach = await staff(team_id, "coach")
    assert (await client.post("/v1/uploads", headers=coach["headers"], json={
        "kind": "drill_video", "content_type": "video/mp4", "size_bytes": 10, "duration_sec": 3})).status_code == 403
    upload_id = await drill_video(client, owner)
    assert (await client.post("/v1/academy/library", headers=coach["headers"], json={
        "upload_id": upload_id, "name": "x", "mode": "h", "fault_tags": ["x"]})).status_code == 403
    player = await make_account("player")
    assert (await client.post("/v1/uploads", headers=player["headers"], json={
        "kind": "drill_video", "content_type": "video/mp4", "size_bytes": 10, "duration_sec": 3})).status_code == 403


async def test_sharing_off_hides_sessions_but_not_threads_goals_assignments(client):
    owner, team_id, [player, _] = await academy()
    coach = await staff(team_id, "coach", sees_all=True)
    sid = await make_session(player["id"])
    thread_id = await general_thread(client, coach, player)
    await sharing(client, player, False)
    h, pid = coach["headers"], player["id"]
    r = await client.get(f"/v1/coach/players/{pid}/sessions", headers=h)
    assert r.status_code == 403 and r.json()["error"]["code"] == "SESSIONS_PRIVATE"
    assert (await client.post(f"/v1/sessions/{sid}/review", headers=h, json=REVIEW)).status_code == 403
    roster = (await client.get("/v1/coach/roster", headers=h)).json()["items"]
    assert roster[0]["pending_count"] == 0 and roster[0]["last"] == {"h": None, "p": None}
    queue = (await client.get("/v1/coach/queue", headers=h)).json()
    assert queue["open"] == []
    sent = await client.post(f"/v1/threads/{thread_id}/messages", headers=h, json={"kind": "session",
                                                                                   "session_id": str(sid)})
    assert sent.status_code == 403
    r = await client.post(f"/v1/coach/players/{pid}/drill-assignments", headers=h,
                          json=assign_body(source_session_id=str(sid)))
    assert r.status_code == 404
    # goals, plain assignments and threads stay available (decisions doc)
    assert (await client.put(f"/v1/players/{pid}/goals/h", headers=h, json=GOAL)).status_code == 200
    assert (await client.post(f"/v1/coach/players/{pid}/drill-assignments", headers=h,
                              json=assign_body())).status_code == 201
    assert (await send_text(client, coach, thread_id)).status_code == 201


async def test_assignment_source_session_must_belong_to_the_player(client):
    owner, _, [p1, p2] = await academy()
    foreign = await make_session(p2["id"])
    deleted = await make_session(p1["id"], deleted=True)
    for sid in (foreign, deleted, uuid.uuid4()):
        r = await client.post(f"/v1/coach/players/{p1['id']}/drill-assignments", headers=owner["headers"],
                              json=assign_body(source_session_id=str(sid)))
        assert r.status_code == 404, r.text


async def test_thread_session_attachment_must_be_the_threads_players_session(client):
    owner, _, [p1, p2] = await academy()
    thread_id = await general_thread(client, owner, p1)
    foreign = await make_session(p2["id"])
    for who in (owner, p1):
        r = await client.post(f"/v1/threads/{thread_id}/messages", headers=who["headers"],
                              json={"kind": "session", "session_id": str(foreign)})
        assert r.status_code == 404, r.text


async def test_upload_hijack_attempts_are_rejected(client):
    owner, team_id, [player, _] = await academy()
    thread_id = await general_thread(client, owner, player)
    sid = await make_session(player["id"])
    victim_audio = await audio(client, player)
    ghost_audio = await audio(client, owner, put=False)
    video_id = await raw_upload(client, owner, "video", "video/mp4", VIDEO)
    voice = {"kind": "voice", "seconds": 4}
    # another user's audio, an unfinished upload, and the wrong kind
    r = await client.post(f"/v1/threads/{thread_id}/messages", headers=owner["headers"],
                          json={**voice, "upload_id": victim_audio})
    assert r.status_code == 422 and r.json()["error"]["code"] == "INVALID_UPLOAD"
    r = await client.post(f"/v1/threads/{thread_id}/messages", headers=owner["headers"],
                          json={**voice, "upload_id": ghost_audio})
    assert r.status_code == 409 and r.json()["error"]["code"] == "UPLOAD_NOT_READY"
    r = await client.post(f"/v1/threads/{thread_id}/messages", headers=owner["headers"],
                          json={**voice, "upload_id": video_id})
    assert r.status_code == 422
    # review: foreign audio, wrong kind, unfinished
    for upload_id, expected in ((victim_audio, 422), (video_id, 422), (ghost_audio, 409)):
        r = await client.post(f"/v1/sessions/{sid}/review", headers=owner["headers"],
                              json={**REVIEW, "voice_note_upload_id": upload_id, "voice_note_seconds": 4})
        assert r.status_code == expected, (upload_id, r.text)
    # library: another user's drill video, and a non-drill kind
    others_drill = await drill_video(client, await staff(team_id, "coach", perms={"library": True}))
    body = {"name": "x", "mode": "h", "fault_tags": ["x"]}
    assert (await client.post("/v1/academy/library", headers=owner["headers"],
                              json={**body, "upload_id": others_drill})).status_code == 404
    assert (await client.post("/v1/academy/library", headers=owner["headers"],
                              json={**body, "upload_id": video_id})).status_code == 422
    # session creation cannot claim someone else's / an audio upload
    thumb = await upload(client, player["headers"], "thumbnail")
    r = await client.post("/v1/sessions", headers=owner["headers"], json=session_body(video_id, None) | {
        "video_upload_id": victim_audio})
    assert r.status_code == 400
    assert thumb
    # the same audio cannot be sent twice in messages
    good = await audio(client, owner)
    ok = await client.post(f"/v1/threads/{thread_id}/messages", headers=owner["headers"],
                           json={**voice, "upload_id": good})
    assert ok.status_code == 201
    again = await client.post(f"/v1/threads/{thread_id}/messages", headers=owner["headers"],
                              json={**voice, "upload_id": good})
    assert again.status_code == 422 and again.json()["error"]["code"] == "UPLOAD_ALREADY_USED"


async def test_idempotency_keys_do_not_cross_threads_assignments_or_users(client):
    owner, team_id, [p1, p2] = await academy()
    t1, t2 = await general_thread(client, owner, p1), await general_thread(client, owner, p2)
    headers = {**owner["headers"], "Idempotency-Key": "k1"}
    m1 = await client.post(f"/v1/threads/{t1}/messages", headers=headers, json={"kind": "text", "text": "same"})
    m2 = await client.post(f"/v1/threads/{t2}/messages", headers=headers, json={"kind": "text", "text": "same"})
    assert m1.status_code == 201
    assert m2.status_code == 409 and m2.json()["error"]["code"] == "IDEMPOTENCY_KEY_REUSED"  # not replayed
    replay = await client.post(f"/v1/threads/{t1}/messages", headers=headers, json={"kind": "text", "text": "same"})
    assert replay.json()["message"]["id"] == m1.json()["message"]["id"]
    clash = await client.post(f"/v1/threads/{t1}/messages", headers=headers, json={"kind": "text", "text": "diff"})
    assert clash.status_code == 409

    headers = {**owner["headers"], "Idempotency-Key": "k2"}
    a1 = (await client.post(f"/v1/coach/players/{p1['id']}/drill-assignments", headers=headers,
                            json=assign_body())).json()["assignment"]
    a2 = await client.post(f"/v1/coach/players/{p2['id']}/drill-assignments", headers=headers, json=assign_body())
    assert a2.status_code == 409 and a2.json()["error"]["code"] == "IDEMPOTENCY_KEY_REUSED"

    body = {"set_number": 1, "reps_done": 3, "day": today()}
    a1_set = await client.post(f"/v1/drill-assignments/{a1['id']}/sets",
                               headers={**p1["headers"], "Idempotency-Key": "s"}, json=body)
    s1 = a1_set
    other = await make_account("player")  # a different user may use the same key independently
    assert s1.status_code == 201
    assert (await client.post("/v1/me/consent", headers={**other["headers"], "Idempotency-Key": "s"},
                              json={"version": "1.0", "accepted": True})).status_code == 201


async def test_notifications_are_private_to_their_recipient(client):
    owner, _, [p1, p2] = await academy()
    thread_id = await general_thread(client, owner, p1)
    await send_text(client, owner, thread_id)
    mine = (await client.get("/v1/notifications", headers=p1["headers"])).json()["items"]
    assert len(mine) == 1
    assert (await client.get("/v1/notifications", headers=p2["headers"])).json()["items"] == []
    assert (await client.get("/v1/notifications/unread-count", headers=p2["headers"])).json()["count"] == 0
    assert (await client.post(f"/v1/notifications/{mine[0]['id']}/read", headers=p2["headers"])).status_code == 404
    assert (await client.post("/v1/notifications/read-all", headers=p2["headers"])).status_code == 204
    assert (await client.get("/v1/notifications/unread-count", headers=p1["headers"])).json()["count"] == 1
    assert (await client.post(f"/v1/notifications/{mine[0]['id']}/read", headers=owner["headers"])).status_code == 404


async def test_private_notes_are_per_coach(client):
    owner, team_id, [player, _] = await academy()
    a = await staff(team_id, "coach", sees_all=True, name="A")
    b = await staff(team_id, "coach", sees_all=True, name="B")
    url = f"/v1/coach/players/{player['id']}/note"
    assert (await client.put(url, headers=a["headers"], json={"text": "A's secret"})).status_code == 200
    for who in (b, owner, player):
        r = await client.get(url, headers=who["headers"])
        assert r.status_code in (200, 403) and (r.status_code == 403 or r.json()["note"]["text"] == ""), who
    assert (await client.get(url, headers=a["headers"])).json()["note"]["text"] == "A's secret"
    # losing visibility of the player ends access to one's own note too
    async with get_session_factory()() as db:
        await db.execute(update(AcademyMembership).where(AcademyMembership.account_id == a["id"])
                         .values(sees_all=False))
        await db.commit()
    assert (await client.get(url, headers=a["headers"])).status_code == 404


async def test_consent_export_escapes_formulas_and_stays_in_tenant(client):
    owner, team_id, [p1, p2] = await academy()
    evil = ["=HYPERLINK(\"http://x\")", "+1+1", "-2+3", "@SUM(A1)", "\t=1", "\r=1"]
    async with get_session_factory()() as db:
        from app.modules.academy.models import PlayerGroup
        from app.modules.accounts.models import Account
        await db.execute(update(Account).where(Account.id == p1["id"]).values(name=evil[0]))
        await db.execute(update(Account).where(Account.id == p2["id"]).values(name=evil[1]))
        db.add(PlayerGroup(team_id=team_id, name=evil[2], focus="Both"))
        await db.commit()
    other_owner = await make_account("coach")
    other_team = await make_team_row(other_owner, await make_account("player", name="@Foreign"))
    assert other_team
    export = await client.post("/v1/academy/consent/export", headers=owner["headers"], json={})
    assert export.status_code == 201, export.text
    async with httpx.AsyncClient() as http:
        text = (await http.get(export.json()["export"]["url"])).text
    rows = list(csv.reader(io.StringIO(text)))
    cells = [c for row in rows[1:] for c in row]
    assert not [c for c in cells if c and c[0] in "=+-@\t\r"], cells
    assert len(rows) == 3 and "Foreign" not in text
    assert all(str(p["id"]) in text for p in (p1, p2))


async def test_member_search_treats_wildcards_literally(client):
    owner, team_id, _ = await academy(players=0)
    names = ["Zed 100%", "Zed 1000", "Under_score", "UnderXscore", "Back\\slash"]
    async with get_session_factory()() as db:
        from app.modules.accounts.models import Account
        for n in names:
            account = await make_account("player", name=n)
            await db.execute(update(Account).where(Account.id == account["id"]).values(team_id=team_id))
        await db.commit()
    expected = {"%": {"Zed 100%"}, "_": {"Under_score"}, "\\": {"Back\\slash"}, "100%": {"Zed 100%"},
                "d_": set(), "' OR 1=1 --": set()}
    for q, want in expected.items():
        r = await client.get("/v1/academy/members", headers=owner["headers"], params={"q": q})
        assert r.status_code == 200, (q, r.text)
        assert {m["name"] for m in r.json()["items"]} == want, q


async def test_post_sessions_blocked_after_consent_withdrawn_or_when_required(client, monkeypatch):
    player = await make_account("player")
    video_id = await upload(client, player["headers"], "video")
    thumb_id = await upload(client, player["headers"], "thumbnail")
    body = session_body(video_id, thumb_id)
    assert (await client.post("/v1/me/consent", headers=player["headers"],
                              json={"version": "1.0", "accepted": True})).status_code == 201
    assert (await client.delete("/v1/me/consent", headers=player["headers"])).status_code == 204
    blocked = await client.post("/v1/sessions", headers=player["headers"], json=body)
    assert blocked.status_code == 403 and blocked.json()["error"]["code"] == "CONSENT_REQUIRED"
    # toggling an opt-in must not re-open analysis
    await client.patch("/v1/me/settings", headers=player["headers"], json={"help_improve_ai": True})
    assert (await client.post("/v1/sessions", headers=player["headers"], json=body)).status_code == 403
    # re-accept opens it again
    await client.post("/v1/me/consent", headers=player["headers"], json={"version": "1.0", "accepted": True})
    assert (await client.post("/v1/sessions", headers=player["headers"], json=body)).status_code == 201

    monkeypatch.setattr(get_settings(), "require_analysis_consent", True)
    fresh = await make_account("player")
    v2, t2 = await upload(client, fresh["headers"], "video"), await upload(client, fresh["headers"], "thumbnail")
    needs = await client.post("/v1/sessions", headers=fresh["headers"], json=session_body(v2, t2))
    assert needs.status_code == 403 and needs.json()["error"]["code"] == "CONSENT_REQUIRED"
    assert JPEG


async def test_concurrent_set_logging_counts_once(client):
    owner, _, [player, _] = await academy()
    assignment = (await client.post(f"/v1/coach/players/{player['id']}/drill-assignments", headers=owner["headers"],
                                    json=assign_body())).json()["assignment"]
    body = {"set_number": 1, "reps_done": 4, "day": today()}
    url = f"/v1/drill-assignments/{assignment['id']}/sets"
    results = await asyncio.gather(*[client.post(url, headers=player["headers"], json=body) for _ in range(6)])
    assert [r.status_code for r in results] == [201] * 6
    async with get_session_factory()() as db:
        assert await db.scalar(select(func.count()).select_from(AssignmentSet)) == 1
    over = await client.post(url, headers=player["headers"], json={**body, "set_number": 4})
    assert over.status_code == 422
    conflict = await client.post(url, headers=player["headers"], json={**body, "reps_done": 5})
    assert conflict.status_code == 409


async def test_concurrent_first_goal_and_messages_stay_consistent(client):
    owner, team_id, [player, _] = await academy()
    goals = await asyncio.gather(*[
        client.put(f"/v1/players/{player['id']}/goals/h", headers=owner["headers"], json={**GOAL, "note": f"n{i}"})
        for i in range(4)])
    assert {g.status_code for g in goals} <= {200, 409}
    assert any(g.status_code == 200 for g in goals)
    async with get_session_factory()() as db:
        active = await db.scalar(select(func.count()).select_from(Goal).where(Goal.ended_at.is_(None)))
        assert active == 1

    thread_id = await general_thread(client, owner, player)
    sent = await asyncio.gather(*[send_text(client, owner if i % 2 else player, thread_id, f"m{i}")
                                  for i in range(8)])
    assert [s.status_code for s in sent] == [201] * 8
    async with get_session_factory()() as db:
        seqs = sorted((await db.scalars(select(Message.seq).where(Message.thread_id == uuid.UUID(thread_id)))).all())
    assert seqs == list(range(1, 9))


async def test_staff_code_capacity_and_races(client):
    owner, team_id, _ = await academy()
    one = (await client.post("/v1/academy/staff-codes", headers=owner["headers"], json={
        "role": "coach", "expires_days": 1, "max_uses": 1, "approval": "auto"})).json()["staff_code"]["code"]
    people = [await make_account("coach") for _ in range(5)]
    results = await asyncio.gather(*[client.post("/v1/me/coach-access", headers=p["headers"], json={"code": one})
                                     for p in people])
    codes = sorted(r.status_code for r in results)
    assert codes == [201, 409, 409, 409, 409], codes
    listed = (await client.get("/v1/academy/staff-codes", headers=owner["headers"])).json()["items"]
    assert listed[0]["uses"] == 1
    # the same applicant racing against themself consumes one use and creates one membership
    five = (await client.post("/v1/academy/staff-codes", headers=owner["headers"], json={
        "role": "assistant", "expires_days": 1, "max_uses": 5, "approval": "auto"})).json()["staff_code"]["code"]
    solo = await make_account("coach")
    res = await asyncio.gather(*[client.post("/v1/me/coach-access", headers=solo["headers"], json={"code": five})
                                 for _ in range(3)])
    assert sorted(r.status_code for r in res).count(201) == 1
    async with get_session_factory()() as db:
        n = await db.scalar(select(func.count()).select_from(AcademyMembership).where(
            AcademyMembership.account_id == solo["id"]))
    assert n == 1
    # revoked code stops new applications
    assert (await client.delete(f"/v1/academy/staff-codes/{five}", headers=owner["headers"])).status_code == 204
    late = await make_account("coach")
    assert (await client.post("/v1/me/coach-access", headers=late["headers"], json={"code": five})).status_code == 409


async def test_deleting_staff_does_not_break_reads_for_players_and_academy(client):
    owner, team_id, [player, _] = await academy()
    coach = await staff(team_id, "coach", sees_all=True, perms={"library": True}, name="Leaver")
    h = coach["headers"]
    pid = player["id"]
    assert (await client.post(f"/v1/coach/players/{pid}/drill-assignments", headers=h,
                              json=assign_body())).status_code == 201
    assert (await client.put(f"/v1/players/{pid}/goals/h", headers=h, json=GOAL)).status_code == 200
    assert (await client.put(f"/v1/coach/players/{pid}/note", headers=h, json={"text": "n"})).status_code == 200
    upload_id = await drill_video(client, coach)
    assert (await client.post("/v1/academy/library", headers=h, json={
        "upload_id": upload_id, "name": "d", "mode": "h", "fault_tags": ["x"]})).status_code == 201
    thread_id = await general_thread(client, coach, player)
    await send_text(client, player, thread_id, "hi coach")
    assert (await client.delete("/v1/me", headers=h)).status_code == 204

    assignments = await client.get("/v1/drill-assignments?mode=h", headers=player["headers"])
    assert assignments.status_code == 200 and assignments.json()["items"][0]["assigned_by"] is None
    goal = await client.get(f"/v1/players/{pid}/goals?mode=h", headers=player["headers"])
    assert goal.status_code == 200 and goal.json()["goal"]["set_by"] is None
    library = await client.get("/v1/academy/library", headers=owner["headers"])
    assert library.status_code == 200 and library.json()["items"][0]["by"] is None
    assert (await client.get("/v1/threads", headers=player["headers"])).status_code == 200
    assert (await client.get("/v1/academy/coaches", headers=owner["headers"])).status_code == 200
    assert (await client.get("/v1/coach/roster", headers=owner["headers"])).status_code == 200
    assert (await client.get("/v1/academy/dashboard", headers=owner["headers"])).status_code == 200


async def test_deleting_a_player_does_not_break_coach_reads(client):
    owner, team_id, [player, other] = await academy()
    thread_id = await general_thread(client, owner, player)
    await send_text(client, player, thread_id)
    await client.post(f"/v1/coach/players/{player['id']}/drill-assignments", headers=owner["headers"],
                      json=assign_body())
    assert (await client.delete("/v1/me", headers=player["headers"])).status_code == 204
    assert (await client.get(f"/v1/threads/{thread_id}", headers=owner["headers"])).status_code == 404
    for url in ("/v1/threads", "/v1/coach/roster", "/v1/coach/queue", "/v1/drill-assignments?mode=h",
                "/v1/academy/members", "/v1/academy/consent", "/v1/academy/dashboard"):
        assert (await client.get(url, headers=owner["headers"])).status_code == 200, url


async def test_unauthenticated_and_foreign_token_requests_are_rejected(client):
    owner, _, [player, _] = await academy()
    sid = await make_session(player["id"])
    for method, url in [("GET", "/v1/threads"), ("GET", "/v1/notifications"), ("GET", "/v1/me/settings"),
                        ("GET", "/v1/academy/coaches"), ("GET", f"/v1/sessions/{sid}/thread"),
                        ("GET", f"/v1/players/{player['id']}/goals?mode=h"), ("GET", "/v1/me/arm-care")]:
        assert (await client.request(method, url)).status_code == 401, url
        bad = await client.request(method, url, headers={"Authorization": "Bearer nope"})
        assert bad.status_code == 401, url


async def test_review_requires_visibility_review_permission_and_sharing(client):
    owner, team_id, [p1, p2] = await academy()
    coach = await staff(team_id, "coach", roster_for=[p1])
    no_review = await staff(team_id, "coach", sees_all=True, perms={"review": False})
    s1, s2 = await make_session(p1["id"]), await make_session(p2["id"])
    assert (await client.post(f"/v1/sessions/{s2}/review", headers=coach["headers"], json=REVIEW)).status_code == 403
    assert (await client.post(f"/v1/sessions/{s1}/review", headers=no_review["headers"],
                              json=REVIEW)).status_code == 403
    assert (await client.post(f"/v1/sessions/{s1}/review", headers=p1["headers"], json=REVIEW)).status_code == 403
    assert (await client.post(f"/v1/sessions/{s1}/review", headers=coach["headers"], json=REVIEW)).status_code == 201
    thread = (await client.get(f"/v1/sessions/{s1}/thread", headers=p1["headers"])).json()["thread"]
    assert thread["coach_id"] == str(coach["id"])
    assert (await client.get(f"/v1/sessions/{s1}/thread", headers=p2["headers"])).status_code == 404
    # a no-review staffer who can see the player may read but not post
    t = thread["id"]
    assert (await client.get(f"/v1/threads/{t}", headers=no_review["headers"])).status_code == 200
    assert (await send_text(client, no_review, t)).status_code == 403


async def test_notification_rows_are_not_created_for_other_recipients(client):
    owner, team_id, [p1, p2] = await academy()
    sid = await make_session(p1["id"])
    await client.post(f"/v1/sessions/{sid}/review", headers=owner["headers"], json=REVIEW)
    async with get_session_factory()() as db:
        recipients = set((await db.scalars(select(Notification.recipient_id))).all())
    assert recipients == {p1["id"]}
    assert p2["id"] not in recipients and uuid.UUID(str(owner["id"])) not in recipients


async def test_team_code_join_flow_keeps_isolation(client):
    # sanity: players that join through the public flow are only visible to their own academy
    a = await make_account("coach")
    b = await make_account("coach")
    ta, tb = await create_team(client, a, name="Team A"), await create_team(client, b, name="Team B")
    pa, pb = await make_account("player"), await make_account("player")
    await join(client, pa, ta["code"])
    await join(client, pb, tb["code"])
    roster_a = (await client.get("/v1/coach/roster", headers=a["headers"])).json()["items"]
    assert [r["id"] for r in roster_a] == [str(pa["id"])]