File size: 58,760 Bytes
cf9e1bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95be3b8
cf9e1bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95be3b8
cf9e1bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95be3b8
 
cf9e1bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95be3b8
cf9e1bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95be3b8
cf9e1bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
756f8b1
 
 
 
 
 
 
cf9e1bd
 
 
 
 
 
 
756f8b1
00466c9
cf9e1bd
 
 
 
 
 
 
 
 
 
95be3b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf9e1bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
00466c9
cf9e1bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
756f8b1
cf9e1bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
756f8b1
cf9e1bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
"""StepWise Self-Checks — Hugging Face Space backend.

Serves the self-check page, stores students and attempts durably in a private
Hugging Face dataset, and exports results as CSV for the parent.

Environment (set as Space secrets / variables):
    HF_TOKEN       token with write access to RESULTS_REPO (required on the Space)
    RESULTS_REPO   private dataset holding results, e.g. "Ashish-K/stepwise-results"
    ANTHROPIC_API_KEY   the Claude tutor

Without HF_TOKEN the app runs locally and keeps data in ./localdata.
"""
from __future__ import annotations

import csv
import io
import json
import os
import re
import secrets
import threading
import time
import uuid
from datetime import datetime, timedelta, timezone
from pathlib import Path

from fastapi import APIRouter, Depends, FastAPI, Header, HTTPException, Query, Request

import auth
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, RedirectResponse, Response
from pydantic import BaseModel, Field

HERE = Path(__file__).parent
SETS_DIR = HERE / "data" / "sets"
HF_TOKEN = os.environ.get("HF_TOKEN")
RESULTS_REPO = os.environ.get("RESULTS_REPO", "")
LOCAL = HERE / "localdata"

app = FastAPI(title="StepWise Self-Checks", docs_url=None, redoc_url=None, openapi_url=None)
# The app used to live under a secret link /s/<ACCESS_KEY>/. Logins replaced it on 20 Nov 2026; old links
# redirect to the root (see old_link below). ACCESS_KEY is still read by auth.py to sign login tokens, so keep it set.


# Pages and files anyone with the link may load; every other route needs a login.
PUBLIC = {"/", "/api/login", "/sw.js", "/manifest.webmanifest", "/icon-192.png", "/icon-512.png"}


def require_login(request: Request) -> None:
    rest = request.url.path
    if rest in PUBLIC or rest.startswith("/visuals/"):
        return
    h = request.headers.get("authorization", "")
    token = h[7:] if h.lower().startswith("bearer ") else request.query_params.get("t", "") if rest.startswith("/api/export/") else ""
    data = auth.read_token(token) if token else None
    u = STORE.users.get(data["u"]) if data else None
    if not u or u.get("disabled") or u.get("version", 0) != data.get("v"):
        raise HTTPException(401, "Please log in.")
    request.state.user = {**u, "id": data["u"]}


router = APIRouter(dependencies=[Depends(require_login)])


def user_of(request: Request) -> dict:
    return request.state.user


def allowed(u: dict) -> set[str]:
    """Student records this login may see: admin all, parent their children, child themself."""
    if u["role"] == "admin":
        return set(STORE.students)
    if u["role"] == "parent":
        linked = {sid for sid, fam in STORE.family.items() if u["id"] in fam}
        return {c for c in set(u.get("children", [])) | linked if c in STORE.students}
    return {u["studentId"]} if u.get("studentId") in STORE.students else set()


def need_student(request: Request, student_id: str) -> dict:
    u = user_of(request)
    if student_id not in allowed(u):
        raise HTTPException(404, "That student is not on your list.")
    return u


def need_role(request: Request, *roles: str) -> dict:
    u = user_of(request)
    if u["role"] not in roles:
        raise HTTPException(403, "Only a parent or the admin can do that." if "parent" in roles else "Only the admin can do that.")
    return u


def student_view(sid: str) -> dict:
    """A student record for the page: effective subjects, plus which come from classes and which were ticked."""
    v = STORE.students[sid]
    subs = subjects_of(sid)
    cls = [cl for cl in STORE.classes.values() if sid in cl.get("students", [])]
    return {"id": sid, **{k: x for k, x in v.items() if k != "subjects"}, **({"subjects": subs} if subs is not None else {}),
            "ownSubjects": v.get("subjects", []), "classCourses": list(dict.fromkeys(c for cl in cls for c in cl.get("courses", []))),
            "classes": [cl["name"] for cl in cls]}


def courses_of(sid: str) -> list[str]:
    """The course codes a student studies; with no class and no ticks, the page's default (every IGCSE subject)."""
    subs = subjects_of(sid)
    return subs if subs is not None else [c["code"] for c in CATALOG["subjects"] if c.get("board") == "igcse"]


def subjects_of(sid: str) -> list[str] | None:
    """A child's courses: those of every class they are in, plus any extra subjects ticked for them."""
    out = [c for cl in STORE.classes.values() if sid in cl.get("students", []) for c in cl.get("courses", [])]
    own = STORE.students.get(sid, {}).get("subjects")
    if own:
        out += own
    return list(dict.fromkeys(out)) if (out or own is not None) else None


# ---------------------------------------------------------------- storage
class Store:
    """Students and attempts in memory, mirrored to a private HF dataset.

    Layout in the dataset (and in ./localdata when running locally):
        students.json            {"<id>": {"name": ..., "createdAt": ...}}
        attempts/<id>.json       one file per saved attempt (never rewritten)
    """

    def __init__(self) -> None:
        self.lock = threading.Lock()
        self.students: dict[str, dict] = {}
        self.attempts: list[dict] = []
        self.mastery: dict[str, dict] = {}   # student id -> atom id -> state
        self.chats: dict[str, dict] = {}     # session id -> session
        self.feedback: dict[str, dict] = {}  # feedback id -> item
        self.progress: dict[str, dict] = {}  # student id -> {"chunks": {"<chapter>/<chunk>": {status, at, session}}}
        self.settings: dict = {"tutorRouting": "opus"}
        self.users: dict[str, dict] = {}     # user id -> {username, name, role, pw, version, studentId | children}
        self.classes: dict[str, dict] = {}   # class id -> {name, courses: [subject codes], students: [student ids]}
        self.family: dict[str, dict] = {}    # student id -> {user id: "Mom" | "Dad" | ...}
        self.coach: dict[str, dict] = {}     # Report coach conversations (for costs and the parent's view)
        self.reports: dict[str, dict] = {}   # reports a child shared with a parent
        self.notes: dict[str, dict] = {}     # words of encouragement from a parent to a child
        self.push: dict[str, dict] = {}      # login id -> {"subs": [web push subscriptions]}
        self.dirty: dict[str, dict] = {}     # path in repo -> object, flushed in batches
        self.dirty_lock = threading.Lock()
        self.api = None
        if HF_TOKEN and RESULTS_REPO:
            from huggingface_hub import HfApi

            self.api = HfApi(token=HF_TOKEN)
            self.api.create_repo(RESULTS_REPO, repo_type="dataset", private=True, exist_ok=True)
        self._load()
        threading.Thread(target=self._flusher, daemon=True).start()

    def queue_write(self, path_in_repo: str, obj: dict) -> None:
        """Chats and idea levels change every message; save them in one commit per minute."""
        with self.dirty_lock:
            self.dirty[path_in_repo] = obj

    def flush(self) -> int:
        with self.dirty_lock:
            batch, self.dirty = self.dirty, {}
        if not batch:
            return 0
        try:
            if self.api:
                from huggingface_hub import CommitOperationAdd

                ops = [CommitOperationAdd(path_in_repo=p, path_or_fileobj=json.dumps(o, ensure_ascii=False).encode("utf-8"))
                       for p, o in batch.items()]
                self.api.create_commit(RESULTS_REPO, operations=ops, repo_type="dataset",
                                       commit_message=f"Save {len(ops)} chat/level files")
            else:
                for p, o in batch.items():
                    f = LOCAL / p
                    f.parent.mkdir(parents=True, exist_ok=True)
                    f.write_text(json.dumps(o, ensure_ascii=False), encoding="utf-8")
        except Exception:
            with self.dirty_lock:  # keep anything newer, put the failed batch back
                for p, o in batch.items():
                    self.dirty.setdefault(p, o)
            return -1
        return len(batch)

    def _flusher(self) -> None:
        while True:
            time.sleep(60)
            self.flush()

    def _load(self) -> None:
        if self.api:
            from huggingface_hub import snapshot_download

            root = Path(snapshot_download(RESULTS_REPO, repo_type="dataset", token=HF_TOKEN))
        else:
            root = LOCAL
            (root / "attempts").mkdir(parents=True, exist_ok=True)
        st = root / "settings.json"
        if st.exists():
            self.settings.update(json.loads(st.read_text(encoding="utf-8")))
        sp = root / "students.json"
        if sp.exists():
            self.students = json.loads(sp.read_text(encoding="utf-8"))
        for name, attr in (("users.json", "users"), ("classes.json", "classes"), ("family.json", "family")):
            f = root / name
            if f.exists():
                setattr(self, attr, json.loads(f.read_text(encoding="utf-8")))
        for sub, sink in (("attempts", None), ("mastery", self.mastery), ("chats", self.chats), ("feedback", self.feedback), ("progress", self.progress),
                          ("coach", self.coach), ("reports", self.reports), ("notes", self.notes),
                          ("push", self.push)):
            folder = root / sub
            for f in sorted(folder.glob("*.json")) if folder.exists() else []:
                try:
                    obj = json.loads(f.read_text(encoding="utf-8"))
                except json.JSONDecodeError:
                    continue
                if sink is None:
                    key = (obj.get("studentId"), obj.get("setId"), obj.get("startedAt"))
                    if not any((x.get("studentId"), x.get("setId"), x.get("startedAt")) == key for x in self.attempts):
                        self.attempts.append(obj)   # a second save of the same quiz run is ignored
                else:
                    if sub == "chats":   # chats from before Oct 2026 have only setId
                        obj.setdefault("chapterId", obj.get("setId"))
                    sink[f.stem] = obj

    def _write(self, path_in_repo: str, obj: dict, message: str) -> None:
        data = json.dumps(obj, ensure_ascii=False, indent=1).encode("utf-8")
        if self.api:
            # retry once on a transient hub error; the attempt is already in memory
            for i in range(2):
                try:
                    self.api.upload_file(
                        path_or_fileobj=data, path_in_repo=path_in_repo,
                        repo_id=RESULTS_REPO, repo_type="dataset", commit_message=message,
                    )
                    return
                except Exception:
                    if i:
                        raise
                    time.sleep(2)
        else:
            p = LOCAL / path_in_repo
            p.parent.mkdir(parents=True, exist_ok=True)
            p.write_bytes(data)

    def add_student(self, name: str, test: bool = False) -> dict:
        with self.lock:
            if any(s["name"].lower() == name.lower() for s in self.students.values()):
                raise HTTPException(409, f"{name} is already on the list")
            sid = re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-") + "-" + secrets.token_hex(2)
            self.students[sid] = {"name": name, "createdAt": now(), **({"test": True} if test else {})}
            self._write("students.json", self.students, f"Add student {sid}")
            return {"id": sid, **self.students[sid]}

    def find_attempt(self, student_id: str, set_id: str, started_at: str) -> dict | None:
        return next((x for x in self.attempts if x.get("studentId") == student_id and x.get("setId") == set_id
                     and x.get("startedAt") == started_at), None)

    def add_attempt(self, attempt: dict) -> dict:
        with self.lock:
            same = self.find_attempt(attempt["studentId"], attempt["setId"], attempt["startedAt"])
            if same:   # the same quiz run sent twice (double tap, or a retry after a slow save)
                return {**same, "duplicate": True}
            attempt["id"] = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S") + "-" + uuid.uuid4().hex[:6]
            attempt["savedAt"] = now()
            self.attempts.append(attempt)
            self._write(f"attempts/{attempt['id']}.json", attempt, f"Attempt {attempt['studentId']} {attempt['setId']}")
            return attempt


def now() -> str:
    return datetime.now(timezone.utc).isoformat(timespec="seconds")


def load_sets() -> dict[str, dict]:
    out = {}
    for f in sorted(SETS_DIR.glob("*.json")):
        d = json.loads(f.read_text(encoding="utf-8"))
        out[d["id"]] = d
    return out


SETS = load_sets()
STORE = Store()


@app.on_event("shutdown")
def _save_on_shutdown() -> None:
    """A restart (e.g. a new deploy) must not lose the last minute of chat messages."""
    STORE.flush()
# Board -> subject -> syllabus unit -> chapter, for the student home (data/catalog.json).
CATALOG = json.loads((HERE / "data" / "catalog.json").read_text(encoding="utf-8"))
SUBJECT_CODES = {s["code"] for s in CATALOG["subjects"]}


def _anthropic_client():
    import anthropic

    return anthropic.Anthropic(max_retries=3, timeout=180.0)


from push import Push  # noqa: E402
from tutor import CHAPTERS, DAILY_CAP_USD, PRICES, ROUTING_MODES, TOPICS, CapReached, Tutor, apply_selfcheck, chapter_of, spent_today  # noqa: E402

def quiz_mistakes(att: dict) -> list:
    """The questions a student lost marks on in one quiz attempt: question, their answer, the right answer."""
    quiz = SETS.get(att["setId"])
    out = []
    for q in (quiz or {}).get("questions", []):
        a = att["answers"].get(q["id"])
        if a is None or a["got"] >= a["max"] or a.get("notLearnt"):
            continue
        try:
            resp = a.get("response")
            if q["type"] == "mcq" and resp is not None and q.get("options"):
                resp = f"{chr(65 + int(resp))}. {q['options'][int(resp)]}"
            elif q["type"] == "multi" and isinstance(resp, list):
                resp = ", ".join(chr(65 + int(i)) for i in resp)
            correct = (f"{chr(65 + int(q['answer']))}. {q['options'][int(q['answer'])]}" if q["type"] == "mcq"
                       else ", ".join(chr(65 + int(i)) for i in q["answer"]) if q["type"] == "multi"
                       else f"{q['answer']} {q.get('unit', '')}".strip() if q["type"] == "numeric" else q.get("mark_scheme", ""))
        except (ValueError, IndexError, TypeError, KeyError):
            continue
        out.append({"prompt": q["prompt"], "options": q.get("options"), "response": resp if resp not in (None, "") else "(no answer)",
                    "correct": correct, "mark_scheme": q.get("mark_scheme", ""), "atom_ids": q.get("atom_ids", [])})
    return out


TUTOR = Tutor(STORE, STORE.students, _anthropic_client)
TUTOR.quiz_mistakes = quiz_mistakes
TUTOR.quiz_title = lambda set_id: (SETS.get(set_id) or {}).get("title", set_id)
TUTOR_ON = bool(os.environ.get("ANTHROPIC_API_KEY"))
PUSH = Push(STORE, lambda sid: STORE.chats.get(sid))


# ---------------------------------------------------------------- api
class StudentIn(BaseModel):
    name: str = Field(min_length=1, max_length=40)
    test: bool = False


class AnswerIn(BaseModel):
    response: object = None
    got: float
    max: float
    auto: bool
    notLearnt: bool = False     # "I haven't learnt this yet": scores 0, kept apart from wrong answers


class FocusIn(BaseModel):
    """Counted in the browser while a quiz or chat is open: on screen and in use, away, and times switched away."""
    activeSec: int = Field(ge=0, le=6 * 3600)
    awaySec: int = Field(ge=0, le=24 * 3600)
    switches: int = Field(ge=0, le=1000)


class AttemptIn(BaseModel):
    studentId: str
    setId: str
    startedAt: str
    submittedAt: str
    durationSec: int = Field(ge=0, le=6 * 3600)
    answers: dict[str, AnswerIn]
    focus: FocusIn | None = None
    leftQuiz: bool = False      # submitted automatically because she switched away from the quiz


@router.get("/")
def index() -> FileResponse:
    return FileResponse(HERE / "static" / "index.html", headers={"Cache-Control": "no-cache"})


VISUALS_DIR = HERE / "static" / "visuals"


@router.get("/sw.js")
def service_worker() -> FileResponse:
    return FileResponse(HERE / "static" / "sw.js", media_type="text/javascript",
                        headers={"Cache-Control": "no-cache", "Service-Worker-Allowed": "/"})


@router.get("/manifest.webmanifest")
def manifest() -> FileResponse:
    return FileResponse(HERE / "static" / "manifest.webmanifest", media_type="application/manifest+json")


@router.get("/icon-{size}.png")
def icon(size: int) -> FileResponse:
    if size not in (192, 512):
        raise HTTPException(404, "No such icon.")
    return FileResponse(HERE / "static" / f"icon-{size}.png", media_type="image/png", headers={"Cache-Control": "max-age=86400"})


# ---------------------------------------------------------------- notifications
class SubIn(BaseModel):
    endpoint: str = Field(min_length=10, max_length=1000)
    keys: dict[str, str]
    expirationTime: float | None = None


class AwayIn(BaseModel):
    kind: str = Field(pattern="^(quiz|chat|back)$")
    sessionId: str | None = None
    dueInMs: int = Field(default=0, ge=0, le=3600 * 1000)


@router.get("/api/push/key")
def push_key(request: Request) -> dict:
    u = user_of(request)
    return {"key": PUSH.public, "on": PUSH.has(u["id"])}


@router.post("/api/push/subscribe")
def push_subscribe(body: SubIn, request: Request) -> dict:
    u = user_of(request)
    if not body.endpoint.startswith("https://") or not {"p256dh", "auth"} <= set(body.keys):
        raise HTTPException(422, "That browser subscription looks wrong.")
    return {"devices": PUSH.subscribe(u["id"], body.model_dump(exclude_none=True))}


@router.post("/api/push/unsubscribe")
def push_unsubscribe(body: SubIn, request: Request) -> dict:
    PUSH.unsubscribe(user_of(request)["id"], body.endpoint)
    return {"ok": True}


@router.post("/api/push/test")
def push_test(request: Request) -> dict:
    u = user_of(request)
    n = PUSH.send(u["id"], "🔔 Reminders are on", "This is how StepWise will call you back to a quiz or the tutor.", "/", "test")
    if not n:
        raise HTTPException(503, "Couldn't send a test notification to this device.")
    return {"sent": n}


@router.post("/api/away")
def away(body: AwayIn, request: Request) -> dict:
    u = user_of(request)
    if u["role"] != "child":
        return {"ok": True}
    if body.kind == "chat" and (not body.sessionId or (STORE.chats.get(body.sessionId) or {}).get("studentId") != u.get("studentId")):
        raise HTTPException(404, "That chat isn't yours.")
    PUSH.away(u["id"], body.kind, body.sessionId, body.dueInMs)
    return {"ok": True}


@router.get("/visuals/{name}")
def visual_module(name: str) -> FileResponse:
    f = (VISUALS_DIR / name).resolve()
    if f.parent != VISUALS_DIR.resolve() or f.suffix != ".js" or not f.is_file():
        raise HTTPException(404, "No such file.")
    return FileResponse(f, media_type="text/javascript", headers={"Cache-Control": "no-cache"})


@router.get("/api/state")
def state(request: Request) -> JSONResponse:
    u = user_of(request)
    ok = allowed(u)
    students = [student_view(k) for k in STORE.students if k in ok]
    codes = None if u["role"] == "admin" else set().union(*[set(courses_of(k)) for k in ok])
    sets = [x for x in SETS.values() if codes is None or x.get("code") in codes]
    return JSONResponse({"sets": sets, "students": students,
                         "attempts": [a for a in STORE.attempts if a["studentId"] in ok],
                         "feedback": [f for f in STORE.feedback.values() if feedback_visible(u, f)], "catalog": CATALOG,
                         "me": public_user(u), "notes": [n for n in STORE.notes.values() if n["studentId"] in ok],
                         "family": {k: family_of(k) for k in ok},
                         "reportsUnread": sum(1 for r in STORE.reports.values() if u["id"] in r.get("sharedWith", []) and u["id"] not in r.get("seenBy", {}))})


class ProfileIn(BaseModel):
    subjects: list[str] = Field(max_length=30)


@router.post("/api/students/{student_id}/profile")
def set_profile(student_id: str, body: ProfileIn, request: Request) -> dict:
    """Extra subjects a child sees on their home screen, on top of their classes' courses (set by a parent)."""
    need_student(request, student_id)
    need_role(request, "admin", "parent")
    with STORE.lock:
        st = STORE.students.get(student_id)
        if not st:
            raise HTTPException(404, "That student is not on the list any more.")
        st["subjects"] = [c for c in dict.fromkeys(body.subjects) if c in SUBJECT_CODES]
        STORE._write("students.json", STORE.students, f"Set subjects for {student_id}")
        return student_view(student_id)


@router.post("/api/students")
def add_student(body: StudentIn, request: Request) -> dict:
    need_role(request, "admin")
    name = re.sub(r"\s+", " ", body.name).strip()
    if not name:
        raise HTTPException(422, "Type a name first.")
    return STORE.add_student(name, body.test)


@router.post("/api/attempts")
def add_attempt(body: AttemptIn, request: Request) -> dict:
    need_student(request, body.studentId)
    s = SETS.get(body.setId)
    if not s:
        raise HTTPException(404, "That self-check is not available.")
    # Recompute totals and atom scores on the server from the set definition, so the
    # stored record is consistent whatever the browser sent.
    qmax = {q["id"]: float(q.get("marks", 1)) for q in s["questions"]}
    answers, atoms, score, total, not_learnt = {}, {}, 0.0, 0.0, []
    for q in s["questions"]:
        a = body.answers.get(q["id"])
        nl = bool(a and a.notLearnt)
        got = 0.0 if nl else max(0.0, min(float(a.got), qmax[q["id"]])) if a else 0.0
        answers[q["id"]] = {"response": None if nl else a.response if a else None, "got": got, "max": qmax[q["id"]],
                            "auto": True if nl else a.auto if a else q["type"] != "short", **({"notLearnt": True} if nl else {})}
        score += got
        total += qmax[q["id"]]
        if nl:   # not a mistake: leave these ideas' levels alone, and list them for a Learn session
            not_learnt += [at for at in q.get("atom_ids", []) if at not in not_learnt]
            continue
        for at in q.get("atom_ids", []):
            g, m = atoms.get(at, [0.0, 0.0])
            atoms[at] = [g + got, m + qmax[q["id"]]]
    rec = {
        "studentId": body.studentId, "setId": body.setId, "subject": s.get("subject", ""),
        "code": s.get("code", ""), "chapter": s.get("chapter", ""), "startedAt": body.startedAt,
        "submittedAt": body.submittedAt, "durationSec": body.durationSec,
        "score": score, "max": total, "answers": answers, "atoms": atoms, "notLearnt": not_learnt,
        **({"focus": body.focus.model_dump()} if body.focus else {}), **({"leftQuiz": True} if body.leftQuiz else {}),
    }
    try:
        saved = STORE.add_attempt(rec)
    except Exception as e:  # hub write failed twice
        raise HTTPException(502, "Couldn't save to the results store just now. Try again in a minute.") from e
    if saved.pop("duplicate", False):
        return saved   # already counted; don't move idea levels a second time
    m = STORE.mastery.setdefault(body.studentId, {})
    apply_selfcheck(m, body.setId, saved)
    STORE.queue_write(f"mastery/{body.studentId}.json", m)
    return saved


# ---------------------------------------------------------------- tutor
class TutorStart(BaseModel):
    studentId: str
    chapterId: str
    kind: str = Field(pattern="^(learn|ask|fix|review)$")
    topicId: str | None = None
    chunkId: str | None = None
    attemptId: str | None = None


class TutorMsg(BaseModel):
    sessionId: str
    text: str = Field(min_length=1, max_length=2000)
    confidence: str | None = Field(default=None, pattern="^(guess|think so|sure)$")
    focus: FocusIn | None = None   # since the tutor's last reply


def _tutor_call(fn, *a):
    import anthropic

    try:
        return fn(*a)
    except CapReached as e:
        raise HTTPException(429, f"That's today's tutor time used up (the daily limit is ${DAILY_CAP_USD:.0f}). Quizzes still work, and the tutor is back tomorrow.") from e
    except ValueError as e:
        raise HTTPException(422, {"unknown topic": "Pick a topic first.", "nothing to review yet": "Nothing to review yet. Do a Learn session or a quiz first."}.get(str(e), "That session can't start.")) from e
    except anthropic.RateLimitError as e:
        raise HTTPException(429, "The tutor is busy. Wait a minute and try again.") from e
    except anthropic.APIConnectionError as e:
        print(f"tutor: API connection error: {e}", flush=True)
        raise HTTPException(502, "The tutor can't be reached right now. Check the connection and try again.") from e
    except anthropic.APIStatusError as e:
        print(f"tutor: API error {e.status_code}: {str(e)[:300]}", flush=True)   # e.g. bad key or no credit
        raise HTTPException(502, "The tutor hit a problem. Try again in a moment.") from e


@router.get("/api/tutor/status")
def tutor_status() -> dict:
    return {"enabled": TUTOR_ON, "chapters": list(CHAPTERS), "dailyCap": DAILY_CAP_USD}


@router.get("/api/topics")
def topics() -> dict:
    return TOPICS


@router.get("/api/mastery/{student_id}")
def mastery(student_id: str, request: Request) -> dict:
    need_student(request, student_id)
    m = STORE.mastery.get(student_id, {})
    t = datetime.now(timezone.utc)
    out = {}
    for cid, ch in CHAPTERS.items():
        levels = [m.get(a["id"], {}).get("level", 0) for a in ch["atoms"]]
        due = [a["id"] for a in ch["atoms"] if m.get(a["id"], {}).get("level", 0) > 0 and m.get(a["id"], {}).get("due")
               and datetime.fromisoformat(m[a["id"]]["due"]) <= t]
        seen = sum(1 for a in ch["atoms"] if m.get(a["id"], {}).get("seen"))
        out[cid] = {"atoms": len(levels), "byLevel": [levels.count(i) for i in range(5)], "due": len(due), "seen": seen}
    return {"chapters": out, "levels": {k: v.get("level", 0) for k, v in m.items()},
            "chunks": STORE.progress.get(student_id, {}).get("chunks", {})}


@router.post("/api/tutor/start")
def tutor_start(body: TutorStart, request: Request) -> dict:
    need_student(request, body.studentId)
    if not TUTOR_ON:
        raise HTTPException(503, "The tutor isn't switched on yet.")
    if body.studentId not in STORE.students or body.chapterId not in CHAPTERS:
        raise HTTPException(404, "Pick your name and a chapter first.")
    fix_items = None
    if body.kind == "fix":
        att = next((a for a in STORE.attempts if a.get("id") == body.attemptId and a["studentId"] == body.studentId), None)
        if not att or not SETS.get(att["setId"]):
            raise HTTPException(404, "That quiz result wasn't found.")
        fix_items = quiz_mistakes(att)
        if not fix_items:
            raise HTTPException(422, "No mistakes to fix in that quiz. Nice work!")
    return _tutor_call(TUTOR.start, body.studentId, body.chapterId, body.kind, body.topicId, body.attemptId, fix_items, body.chunkId)


@router.get("/api/tutor/budget/{student_id}")
def tutor_budget(student_id: str, request: Request) -> dict:
    need_student(request, student_id)
    used = spent_today(STORE, student_id)
    return {"usedToday": round(used, 2), "cap": DAILY_CAP_USD, "left": round(max(0.0, DAILY_CAP_USD - used), 2)}


@router.get("/api/tutor/sessions/{student_id}")
def tutor_sessions(student_id: str, request: Request, chapterId: str | None = None) -> list:
    need_student(request, student_id)
    return TUTOR.sessions_for(student_id, chapterId) if TUTOR_ON else []


@router.get("/api/tutor/session/{sid}")
def tutor_open(sid: str, studentId: str, request: Request) -> dict:
    need_student(request, studentId)
    if not TUTOR_ON:
        raise HTTPException(503, "The tutor isn't switched on yet.")
    try:
        return TUTOR.open_session(sid, studentId)
    except KeyError as e:
        raise HTTPException(404, "That chat wasn't found.") from e


@router.post("/api/tutor/message")
def tutor_message(body: TutorMsg, request: Request) -> dict:
    if body.sessionId not in STORE.chats:
        raise HTTPException(404, "That chat has ended. Start a new one.")
    need_student(request, STORE.chats[body.sessionId]["studentId"])
    return _tutor_call(TUTOR.message, body.sessionId, body.text.strip(), body.confidence, body.focus.model_dump() if body.focus else None)


# ---------------------------------------------------------------- feedback
FEEDBACK_TAGS = {"wrong answer", "unclear", "too hard", "too easy", "typo", "off topic", "helpful", "great question", "other",
                 "confusing", "hard to find", "looks wrong", "too slow", "bug", "idea", "love it",
                 "in syllabus", "not taught yet", "not in syllabus", "just right",
                 "feeling lost", "feeling repetitive", "got insight", "gaining confidence"}


class FeedbackIn(BaseModel):
    by: str                                   # a student id, or "parent"
    targetType: str = Field(pattern="^(question|set|tutor_message|tutor_session|app)$")
    setId: str = "app"
    questionId: str | None = None
    sessionId: str | None = None
    excerpt: str | None = Field(default=None, max_length=600)   # the tutor text being rated
    tags: list[str] = Field(default_factory=list, max_length=6)
    text: str = Field(default="", max_length=2000)


class FeedbackStatus(BaseModel):
    status: str = Field(pattern="^(open|resolved)$")
    note: str = Field(default="", max_length=1000)


@router.post("/api/feedback")
def add_feedback(body: FeedbackIn, request: Request) -> dict:
    u = user_of(request)
    if body.by == "parent":
        need_role(request, "admin", "parent")
    elif body.by != "visitor":
        need_student(request, body.by)
    tags = [t for t in body.tags if t in FEEDBACK_TAGS]
    if not tags and not body.text.strip():
        raise HTTPException(422, "Pick a reason or write a comment first.")
    fid = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S") + "-" + uuid.uuid4().hex[:6]
    item = {"id": fid, "by": body.by, "targetType": body.targetType, "setId": body.setId,
            "questionId": body.questionId, "sessionId": body.sessionId, "excerpt": body.excerpt,
            "tags": tags, "text": body.text.strip(), "created": now(), "status": "open", "note": "", "byUser": u["id"]}
    STORE.feedback[fid] = item
    STORE.queue_write(f"feedback/{fid}.json", item)
    return item


@router.get("/api/feedback")
def list_feedback(request: Request) -> list:
    u = user_of(request)
    return sorted((f for f in STORE.feedback.values() if feedback_visible(u, f)), key=lambda x: x["created"], reverse=True)


def feedback_visible(u: dict, f: dict) -> bool:
    return u["role"] == "admin" or f.get("by") in allowed(u) or f.get("byUser") == u["id"]


@router.post("/api/feedback/{fid}/status")
def set_feedback_status(fid: str, body: FeedbackStatus, request: Request) -> dict:
    u = need_role(request, "admin", "parent")
    item = STORE.feedback.get(fid)
    if not item or not feedback_visible(u, item):
        raise HTTPException(404, "No such feedback.")
    item["status"], item["note"], item["updated"] = body.status, body.note.strip(), now()
    STORE.queue_write(f"feedback/{fid}.json", item)
    return item


# ---------------------------------------------------------------- activity (counts only, no chat text)
@router.get("/api/activity")
def activity(request: Request) -> dict:
    out: dict[str, dict] = {sid: {"sessions": [], "ideas": {}} for sid in allowed(user_of(request))}
    for s in STORE.chats.values():
        if s["studentId"] not in out:
            continue
        ch = CHAPTERS.get(s["setId"], {})
        try:
            mins = max(1, round((datetime.fromisoformat(s["updated"]) - datetime.fromisoformat(s["started"])).total_seconds() / 60))
        except (KeyError, ValueError):
            mins = 0
        out[s["studentId"]]["sessions"].append({
            "id": s["id"], "chapterId": s["setId"], "subject": ch.get("subject", ""), "chapter": ch.get("chapter", s["setId"]),
            "mode": s["mode"], "kind": s.get("kind", s["mode"]), "topicId": s.get("topicId"), "complete": bool(s.get("complete")),
            "goal": s.get("goal", ""), "started": s["started"], "updated": s["updated"], "minutes": mins,
            "messages": sum(1 for m in s["transcript"] if m["role"] == "student") - 1,
            "attempts": len(s["attempts"]), "correct": sum(1 for a in s["attempts"] if a.get("correct"))})
    for sid, m in STORE.mastery.items():
        if sid not in out:
            continue
        for cid, ch in CHAPTERS.items():
            atoms = [{"id": a["id"], "statement": a["statement"], "level": m.get(a["id"], {}).get("level", 0),
                      "seen": m.get(a["id"], {}).get("seen", 0)} for a in ch["atoms"]]
            if any(a["seen"] for a in atoms):
                out[sid]["ideas"][cid] = {"subject": ch["subject"], "chapter": ch["chapter"],
                                          "byLevel": [sum(1 for a in atoms if a["level"] == i) for i in range(5)],
                                          "atoms": [a for a in atoms if a["seen"]]}
    for v in out.values():
        v["sessions"].sort(key=lambda x: x["updated"], reverse=True)
    return out


# ---------------------------------------------------------------- settings
class SettingsIn(BaseModel):
    tutorRouting: str = Field(pattern="^(auto|opus|fable)$")


@router.get("/api/settings")
def get_settings() -> dict:
    return {**STORE.settings, "modes": list(ROUTING_MODES),
            "prices": {k: {kk: vv for kk, vv in v.items()} for k, v in PRICES.items()}}


@router.post("/api/settings")
def set_settings(body: SettingsIn, request: Request) -> dict:
    need_role(request, "admin")
    STORE.settings["tutorRouting"] = body.tutorRouting
    STORE.queue_write("settings.json", STORE.settings)
    STORE.flush()
    return get_settings()


@router.get("/api/costs")
def costs(request: Request) -> dict:
    ok = allowed(need_role(request, "admin", "parent"))
    by_model: dict[str, dict] = {}
    for s in STORE.chats.values():
        if s["studentId"] not in ok:
            continue
        for m, b in s.get("usage", {}).get("byModel", {}).items():
            agg = by_model.setdefault(m, {"label": PRICES.get(m, {}).get("label", m), "turns": 0, "cost": 0.0, "seconds": 0.0})
            agg["turns"] += b.get("turns", 0)
            agg["cost"] = round(agg["cost"] + b.get("cost", 0.0), 4)
        for t in s.get("transcript", []):
            if t.get("role") == "tutor" and t.get("model") in by_model:
                by_model[t["model"]]["seconds"] += t.get("seconds") or 0
    for v in by_model.values():
        v["avgSeconds"] = round(v["seconds"] / v["turns"], 1) if v["turns"] else 0
        v["avgCost"] = round(v["cost"] / v["turns"], 4) if v["turns"] else 0
    return {"byModel": by_model, "total": round(sum(v["cost"] for v in by_model.values()), 4)}


# ---------------------------------------------------------------- parent
@router.get("/api/parent/chats")
def parent_chats(request: Request) -> list:
    ok = allowed(need_role(request, "admin", "parent"))
    names = {k: v["name"] for k, v in STORE.students.items()}
    out = []
    for s in STORE.chats.values():
        if s["studentId"] not in ok:
            continue
        ch = CHAPTERS.get(s["setId"], {})
        out.append({"id": s["id"], "student": names.get(s["studentId"], s["studentId"]), "studentId": s["studentId"],
                    "subject": ch.get("subject", ""), "chapter": ch.get("chapter", s["setId"]), "mode": s["mode"],
                    "started": s["started"], "updated": s["updated"], "messages": len(s["transcript"]),
                    "attempts": len(s["attempts"]), "correct": sum(1 for a in s["attempts"] if a.get("correct")),
                    "flags": s["flags"], "usage": s["usage"], "cost": s["usage"].get("cost", 0.0),
                    "models": sorted({PRICES.get(t.get("model"), {}).get("label", t.get("model")) for t in s["transcript"] if t.get("model")})})
    return sorted(out, key=lambda x: x["updated"], reverse=True)


@router.get("/api/parent/chats/{sid}")
def parent_chat(sid: str, request: Request) -> dict:
    ok = allowed(need_role(request, "admin", "parent"))
    s = STORE.chats.get(sid)
    if not s or s["studentId"] not in ok:
        raise HTTPException(404, "No such chat.")
    return {k: s[k] for k in ("id", "studentId", "setId", "mode", "started", "updated", "transcript", "attempts", "flags", "usage")}


@router.get("/api/export/{kind}.csv")
def export(kind: str, request: Request) -> Response:
    u = need_role(request, "admin", "parent")
    ok = allowed(u)
    attempts = [a for a in STORE.attempts if a["studentId"] in ok]
    buf = io.StringIO()
    w = csv.writer(buf)
    names = {k: v["name"] for k, v in STORE.students.items()}
    if kind == "attempts":
        w.writerow(["attempt_id", "student", "subject", "code", "chapter", "set_id", "submitted_at", "minutes", "score", "max", "percent"])
        for a in attempts:
            pct = round(100 * a["score"] / a["max"]) if a["max"] else 0
            w.writerow([a["id"], names.get(a["studentId"], a["studentId"]), a["subject"], a["code"], a["chapter"],
                        a["setId"], a["submittedAt"], round(a["durationSec"] / 60), a["score"], a["max"], pct])
    elif kind == "answers":
        w.writerow(["attempt_id", "student", "set_id", "question_id", "question_type", "template_id", "atom_ids", "misconception_id", "response", "got", "max", "auto_marked", "not_learnt_yet"])
        for a in attempts:
            qs = {q["id"]: q for q in SETS.get(a["setId"], {}).get("questions", [])}
            for qid, ans in a["answers"].items():
                q = qs.get(qid, {})
                resp = ans["response"]
                if isinstance(resp, list):
                    resp = ";".join(str(x) for x in resp)
                w.writerow([a["id"], names.get(a["studentId"], a["studentId"]), a["setId"], qid, q.get("type", ""),
                            q.get("template_id", ""), ";".join(q.get("atom_ids", [])), q.get("misconception_id") or "",
                            resp, ans["got"], ans["max"], ans["auto"], bool(ans.get("notLearnt"))])
    elif kind == "atoms":
        w.writerow(["student", "subject", "atom_id", "idea", "marks_got", "marks_max", "percent", "from_latest_attempts"])
        latest: dict[tuple, dict] = {}
        for a in sorted(attempts, key=lambda x: x["submittedAt"]):
            latest[(a["studentId"], a["setId"])] = a
        agg: dict[tuple, list] = {}
        for (sid, set_id), a in latest.items():
            idea = SETS.get(set_id, {}).get("atoms", {})
            for at, (g, m) in a["atoms"].items():
                k = (sid, a["subject"], at)
                cur = agg.setdefault(k, [0.0, 0.0, idea.get(at, ""), 0])
                cur[0] += g
                cur[1] += m
                cur[3] += 1
        for (sid, subj, at), (g, m, idea, n) in sorted(agg.items(), key=lambda kv: (kv[0][0], kv[1][0] / kv[1][1] if kv[1][1] else 0)):
            w.writerow([names.get(sid, sid), subj, at, idea, g, m, round(100 * g / m) if m else 0, n])
    elif kind == "feedback":
        w.writerow(["feedback_id", "created", "by", "target", "set_id", "question_id", "session_id", "tags", "comment", "excerpt", "status", "parent_note"])
        for f in sorted((f for f in STORE.feedback.values() if feedback_visible(u, f)), key=lambda x: x["created"]):
            who = {"parent": "Parent", "visitor": "Visitor"}.get(f["by"]) or names.get(f["by"], f["by"])
            if STORE.students.get(f["by"], {}).get("test"):
                who += " (test)"
            w.writerow([f["id"], f["created"], who, f["targetType"], f["setId"], f.get("questionId") or "", f.get("sessionId") or "",
                        ";".join(f["tags"]), f["text"], f.get("excerpt") or "", f["status"], f.get("note", "")])
    elif kind == "chats":
        w.writerow(["session_id", "student", "subject", "chapter", "mode", "time", "who", "confidence", "model", "effort", "routing_reason", "seconds", "cost_usd", "text"])
        for s in sorted((c for c in STORE.chats.values() if c["studentId"] in ok), key=lambda x: x["started"]):
            ch = CHAPTERS.get(s["setId"], {})
            for m in s["transcript"]:
                w.writerow([s["id"], names.get(s["studentId"], s["studentId"]), ch.get("subject", ""), ch.get("chapter", ""),
                            s["mode"], m["t"], m["role"], m.get("confidence") or "", m.get("model") or "", m.get("effort") or "",
                            m.get("why") or "", m.get("seconds") or "", m.get("cost") if m.get("cost") is not None else "", m["text"]])
    else:
        raise HTTPException(404, "Unknown export.")
    stamp = datetime.now().strftime("%Y-%m-%d")
    return Response(buf.getvalue().encode("utf-8-sig"), media_type="text/csv",
                    headers={"Content-Disposition": f'attachment; filename="stepwise-{kind}-{stamp}.csv"'})


# ---------------------------------------------------------------- report, sharing, encouragement
import report as rpt  # noqa: E402


def family_of(sid: str) -> list[dict]:
    """The parents linked to a child, with the label the child sees (Mom, Dad...)."""
    rel = STORE.family.get(sid, {})
    out = []
    for uid, u in STORE.users.items():
        if u.get("disabled") or u["role"] not in ("parent", "admin"):
            continue
        if uid in rel or (u["role"] == "parent" and sid in u.get("children", [])):
            out.append({"id": uid, "name": u["name"], "relation": rel.get(uid) or "Parent"})
    return sorted(out, key=lambda x: x["relation"])


class ReportQ(BaseModel):
    studentId: str
    period: str = Field(default="week", pattern="^(today|yesterday|week|lastweek|month|30d|custom)$")
    start: str | None = Field(default=None, pattern=r"^\d{4}-\d{2}-\d{2}$")
    end: str | None = Field(default=None, pattern=r"^\d{4}-\d{2}-\d{2}$")
    tz: int = Field(default=0, ge=-840, le=840)     # the browser's getTimezoneOffset()


class CoachIn(ReportQ):
    coachId: str | None = None
    history: list[dict] = Field(default_factory=list, max_length=30)


class ShareIn(ReportQ):
    to: list[str] = Field(min_length=1, max_length=6)   # user ids from the child's family
    commentary: str = Field(default="", max_length=6000)


class NoteIn(BaseModel):
    studentId: str
    text: str = Field(min_length=1, max_length=500)
    reportId: str | None = None


def _bounds(q: ReportQ):
    try:
        return rpt.period_bounds(q.period, q.start, q.end, q.tz)
    except ValueError as e:
        raise HTTPException(422, "Pick a start date before the end date (at most a year).") from e


@router.post("/api/report")
def get_report(body: ReportQ, request: Request) -> dict:
    need_student(request, body.studentId)
    a, b, label = _bounds(body)
    return {"label": label, "stats": rpt.report(STORE, SETS, body.studentId, a, b), "family": family_of(body.studentId)}


@router.post("/api/report/coach")
def report_coach(body: CoachIn, request: Request) -> dict:
    u = need_student(request, body.studentId)
    if not TUTOR_ON:
        raise HTTPException(503, "The coach isn't switched on yet.")
    if spent_today(STORE, body.studentId) >= DAILY_CAP_USD:
        raise HTTPException(429, f"That's today's AI time used up (the daily limit is ${DAILY_CAP_USD:.0f}). Your numbers are all still here.")
    a, b, label = _bounds(body)
    stats = rpt.report(STORE, SETS, body.studentId, a, b)
    child = STORE.students[body.studentId]["name"].split(" ")[0]
    audience = "child" if u["role"] == "child" else "parent"
    rel = {x["id"]: x["relation"] for x in family_of(body.studentId)}.get(u["id"])
    reader = f"{u['name']} ({rel})" if rel else u["name"]
    import anthropic

    try:
        text, cost = rpt.coach_reply(_anthropic_client, audience, child, reader, label, stats, body.history)
    except anthropic.APIError as e:
        print(f"coach: API error: {str(e)[:300]}", flush=True)
        raise HTTPException(502, "The coach can't answer right now. Try again in a moment.") from e
    cid = body.coachId if body.coachId in STORE.coach and STORE.coach[body.coachId]["byUser"] == u["id"] else \
        datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S") + "-" + uuid.uuid4().hex[:6]
    rec = STORE.coach.setdefault(cid, {"id": cid, "studentId": body.studentId, "byUser": u["id"], "audience": audience,
                                       "label": label, "created": now(), "transcript": []})
    if body.history and body.history[-1].get("role") == "user":
        rec["transcript"].append({"role": "reader", "text": str(body.history[-1].get("content", ""))[:2000], "t": now()})
    rec["transcript"].append({"role": "coach", "text": text, "t": now(), "cost": round(cost, 5)})
    STORE.queue_write(f"coach/{cid}.json", rec)
    return {"reply": text, "coachId": cid}


@router.post("/api/report/share")
def report_share(body: ShareIn, request: Request) -> dict:
    u = need_student(request, body.studentId)
    fam = {x["id"]: x for x in family_of(body.studentId)}
    to = [x for x in dict.fromkeys(body.to) if x in fam]
    if not to:
        raise HTTPException(422, "Pick who to share it with.")
    a, b, label = _bounds(body)
    recent = datetime.now(timezone.utc) - timedelta(seconds=90)
    for r in list(STORE.reports.values()):   # a double tap on Both / Mom / Dad
        if (r["studentId"] == body.studentId and r["by"] == u["id"] and r["label"] == label and set(to) <= set(r["sharedWith"])
                and r.get("commentary", "") == body.commentary.strip() and datetime.fromisoformat(r["created"]) >= recent):
            return {"id": r["id"], "sharedWith": [fam[x]["relation"] for x in to]}
    rid = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S") + "-" + uuid.uuid4().hex[:6]
    rec = {"id": rid, "studentId": body.studentId, "by": u["id"], "label": label, "created": now(),
           "stats": rpt.report(STORE, SETS, body.studentId, a, b), "commentary": body.commentary.strip(),
           "sharedWith": to, "seenBy": {}}
    STORE.reports[rid] = rec
    STORE.queue_write(f"reports/{rid}.json", rec)
    STORE.flush()
    return {"id": rid, "sharedWith": [fam[x]["relation"] for x in to]}


def _report_visible(u: dict, r: dict) -> bool:
    return u["role"] == "admin" or u["id"] in r.get("sharedWith", []) or (u["role"] == "child" and r["studentId"] in allowed(u))


@router.get("/api/reports")
def list_reports(request: Request, studentId: str | None = None) -> list:
    u = user_of(request)
    out = [{k: r[k] for k in ("id", "studentId", "label", "created", "sharedWith")} | {"unread": u["id"] in r["sharedWith"] and u["id"] not in r["seenBy"]}
           for r in STORE.reports.values() if _report_visible(u, r) and (not studentId or r["studentId"] == studentId)]
    return sorted(out, key=lambda x: x["created"], reverse=True)


@router.get("/api/reports/{rid}")
def open_report(rid: str, request: Request) -> dict:
    u = user_of(request)
    r = STORE.reports.get(rid)
    if not r or not _report_visible(u, r):
        raise HTTPException(404, "That report isn't shared with you.")
    if u["id"] in r["sharedWith"] and u["id"] not in r["seenBy"]:
        r["seenBy"][u["id"]] = now()
        STORE.queue_write(f"reports/{rid}.json", r)
    fam = {x["id"]: x["relation"] for x in family_of(r["studentId"])}
    return {**r, "student": STORE.students.get(r["studentId"], {}).get("name", ""), "sharedWithNames": [fam.get(x, "Parent") for x in r["sharedWith"]]}


@router.post("/api/notes")
def add_note(body: NoteIn, request: Request) -> dict:
    u = need_student(request, body.studentId)
    if u["role"] == "child":
        raise HTTPException(403, "Only a parent can send encouragement.")
    rel = {x["id"]: x["relation"] for x in family_of(body.studentId)}.get(u["id"], "Parent")
    nid = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S") + "-" + uuid.uuid4().hex[:6]
    n = {"id": nid, "studentId": body.studentId, "fromUser": u["id"], "fromName": u["name"], "relation": rel,
         "text": body.text.strip(), "reportId": body.reportId, "created": now(), "seen": None, "heart": False}
    STORE.notes[nid] = n
    STORE.queue_write(f"notes/{nid}.json", n)
    STORE.flush()
    return n


@router.post("/api/notes/{nid}/seen")
def note_seen(nid: str, request: Request, heart: bool = False) -> dict:
    u = user_of(request)
    n = STORE.notes.get(nid)
    if not n or u["role"] != "child" or n["studentId"] not in allowed(u):
        raise HTTPException(404, "No such message.")
    n["seen"] = n["seen"] or now()
    n["heart"] = n["heart"] or heart
    STORE.queue_write(f"notes/{nid}.json", n)
    return n


class FamilyIn(BaseModel):
    studentId: str
    userId: str
    relation: str | None = Field(default=None, max_length=20)   # None removes the link


@router.post("/api/admin/family")
def admin_family(body: FamilyIn, request: Request) -> dict:
    need_role(request, "admin")
    if body.studentId not in STORE.students or body.userId not in STORE.users:
        raise HTTPException(404, "No such student or user.")
    with STORE.lock:
        fam = STORE.family.setdefault(body.studentId, {})
        if body.relation:
            fam[body.userId] = body.relation.strip()
        else:
            fam.pop(body.userId, None)
        STORE._write("family.json", STORE.family, f"Family link for {body.studentId}")
    return {"family": family_of(body.studentId)}


# ---------------------------------------------------------------- accounts
LIMITER = auth.LoginLimiter()
IP_LIMITER = auth.LoginLimiter(limit=30)
USERNAME = r"^[a-z0-9][a-z0-9._-]{1,29}$"


def public_user(u: dict) -> dict:
    return {"id": u["id"], "username": u["username"], "name": u["name"], "role": u["role"],
            "studentId": u.get("studentId"), "children": u.get("children", []),
            "mustChange": bool(u.get("mustChange")), "disabled": bool(u.get("disabled"))}


def save_users(msg: str) -> None:
    STORE._write("users.json", STORE.users, msg)


class LoginIn(BaseModel):
    username: str = Field(min_length=1, max_length=40)
    password: str = Field(min_length=1, max_length=200)


class PasswordIn(BaseModel):
    old: str = Field(max_length=200)
    new: str = Field(min_length=6, max_length=200)


@router.post("/api/login")
def login(body: LoginIn, request: Request) -> dict:
    name = body.username.strip().lower()
    ip = "ip:" + (request.headers.get("x-forwarded-for", "").split(",")[0].strip() or (request.client.host if request.client else "?"))
    if IP_LIMITER.blocked(ip):
        raise HTTPException(429, "Too many wrong tries from this connection. Wait 15 minutes.")
    if LIMITER.blocked(name):
        raise HTTPException(429, "Too many wrong tries. Wait 15 minutes, or ask the admin to reset your password.")
    uid, u = next(((k, v) for k, v in STORE.users.items() if v["username"] == name), (None, None))
    if not u or u.get("disabled") or not auth.verify_password(body.password, u["pw"]):
        LIMITER.fail(name)
        IP_LIMITER.fail(ip)
        raise HTTPException(401, "That username and password don't match.")
    LIMITER.clear(name)
    return {"token": auth.make_token(uid, u.get("version", 0)), "me": public_user({**u, "id": uid})}


@router.get("/api/me")
def me(request: Request) -> dict:
    return public_user(user_of(request))


@router.post("/api/me/password")
def change_password(body: PasswordIn, request: Request) -> dict:
    u = user_of(request)
    with STORE.lock:
        rec = STORE.users[u["id"]]
        if not auth.verify_password(body.old, rec["pw"]):
            raise HTTPException(403, "Your current password isn't right.")
        rec["pw"], rec["version"], rec["mustChange"] = auth.hash_password(body.new), rec.get("version", 0) + 1, False
        save_users(f"Password changed for {rec['username']}")
    return {"token": auth.make_token(u["id"], rec["version"]), "me": public_user({**rec, "id": u["id"]})}


class UserIn(BaseModel):
    username: str = Field(pattern=USERNAME)
    name: str = Field(min_length=1, max_length=40)
    role: str = Field(pattern="^(admin|parent|child)$")
    password: str = Field(min_length=6, max_length=200)
    children: list[str] = Field(default_factory=list, max_length=20)   # parent: student ids
    studentId: str | None = None                                        # child: link an existing student record


class UserEdit(BaseModel):
    name: str | None = Field(default=None, min_length=1, max_length=40)
    password: str | None = Field(default=None, min_length=6, max_length=200)
    children: list[str] | None = Field(default=None, max_length=20)
    disabled: bool | None = None


class ClassIn(BaseModel):
    name: str = Field(min_length=1, max_length=60)
    courses: list[str] = Field(default_factory=list, max_length=30)
    students: list[str] = Field(default_factory=list, max_length=60)


@router.get("/api/admin")
def admin_overview(request: Request) -> dict:
    need_role(request, "admin")
    return {"users": sorted((public_user({**u, "id": k}) for k, u in STORE.users.items()), key=lambda x: (x["role"], x["name"])),
            "classes": [{"id": k, **v} for k, v in STORE.classes.items()],
            "family": {sid: family_of(sid) for sid in STORE.students},
            "students": [{"id": k, "name": v["name"], "test": bool(v.get("test"))} for k, v in STORE.students.items()],
            "subjects": [{"code": s["code"], "name": s["name"], "board": s.get("board", "")} for s in CATALOG["subjects"]]}


@router.post("/api/admin/users")
def admin_add_user(body: UserIn, request: Request) -> dict:
    need_role(request, "admin")
    with STORE.lock:
        if any(u["username"] == body.username for u in STORE.users.values()):
            raise HTTPException(409, f"The username {body.username} is taken.")
        rec = {"username": body.username, "name": body.name.strip(), "role": body.role, "pw": auth.hash_password(body.password),
               "version": 0, "mustChange": True, "createdAt": now()}
        if body.role == "parent":
            rec["children"] = [c for c in body.children if c in STORE.students]
        if body.role == "child":
            if body.studentId:
                if body.studentId not in STORE.students:
                    raise HTTPException(404, "That student record doesn't exist.")
                if any(u.get("studentId") == body.studentId for u in STORE.users.values()):
                    raise HTTPException(409, "That student already has a login.")
                rec["studentId"] = body.studentId
            else:
                sid = re.sub(r"[^a-z0-9]+", "-", body.name.lower()).strip("-") + "-" + secrets.token_hex(2)
                STORE.students[sid] = {"name": body.name.strip(), "createdAt": now()}
                STORE._write("students.json", STORE.students, f"Add student {sid}")
                rec["studentId"] = sid
        uid = "u-" + secrets.token_hex(4)
        STORE.users[uid] = rec
        save_users(f"Add {body.role} {body.username}")
    return public_user({**rec, "id": uid})


@router.post("/api/admin/users/{uid}")
def admin_edit_user(uid: str, body: UserEdit, request: Request) -> dict:
    me_ = need_role(request, "admin")
    with STORE.lock:
        rec = STORE.users.get(uid)
        if not rec:
            raise HTTPException(404, "No such user.")
        if body.disabled and uid == me_["id"]:
            raise HTTPException(422, "You can't switch off your own login.")
        if body.name is not None:
            rec["name"] = body.name.strip()
            if rec.get("studentId") in STORE.students:
                STORE.students[rec["studentId"]]["name"] = rec["name"]
                STORE._write("students.json", STORE.students, f"Rename {rec['studentId']}")
        if body.password is not None:     # a reset: signs them out everywhere and asks for a new password
            rec["pw"], rec["version"], rec["mustChange"] = auth.hash_password(body.password), rec.get("version", 0) + 1, True
        if body.children is not None and rec["role"] == "parent":
            rec["children"] = [c for c in body.children if c in STORE.students]
        if body.disabled is not None:
            rec["disabled"] = body.disabled
            rec["version"] = rec.get("version", 0) + 1
        save_users(f"Edit user {rec['username']}")
    return public_user({**rec, "id": uid})


def _save_class(cid: str, body: ClassIn) -> dict:
    with STORE.lock:
        STORE.classes[cid] = {"name": body.name.strip(), "courses": [c for c in dict.fromkeys(body.courses) if c in SUBJECT_CODES],
                              "students": [s for s in dict.fromkeys(body.students) if s in STORE.students]}
        STORE._write("classes.json", STORE.classes, f"Save class {cid}")
        return {"id": cid, **STORE.classes[cid]}


@router.post("/api/admin/classes")
def admin_add_class(body: ClassIn, request: Request) -> dict:
    need_role(request, "admin")
    return _save_class("c-" + secrets.token_hex(3), body)


@router.post("/api/admin/classes/{cid}")
def admin_edit_class(cid: str, body: ClassIn, request: Request) -> dict:
    need_role(request, "admin")
    if cid not in STORE.classes:
        raise HTTPException(404, "No such class.")
    return _save_class(cid, body)


@router.delete("/api/admin/classes/{cid}")
def admin_delete_class(cid: str, request: Request) -> dict:
    need_role(request, "admin")
    with STORE.lock:
        if STORE.classes.pop(cid, None) is None:
            raise HTTPException(404, "No such class.")
        STORE._write("classes.json", STORE.classes, f"Delete class {cid}")
    return {"ok": True}


@app.get("/healthz")
def health() -> dict:
    return {"ok": True}


@router.get("/status")
def status() -> dict:
    return {"ok": True, "sets": len(SETS), "students": len(STORE.students), "attempts": len(STORE.attempts),
            "chats": len(STORE.chats), "feedback": len(STORE.feedback), "tutor": TUTOR_ON,
            "storage": "hf-dataset" if STORE.api else "local"}


@app.get("/s/{old:path}", include_in_schema=False)
def old_link(old: str) -> RedirectResponse:
    """Bookmarks of the old secret link land on the login page."""
    return RedirectResponse("/", status_code=301)


app.include_router(router)