File size: 62,687 Bytes
af70f62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
from __future__ import annotations
from core.clip_writer import format_duration
from datetime import datetime
import json
from pathlib import Path
import shutil
import sqlite3
from typing import Any, Optional
import uuid
import numpy as np


class DatabaseRepository:
    """3NF SQLite repository for ClassPulse Edge (13-table schema + dashboard management)."""

    def __init__(self, db_path: str | Path = "data/classroom.db") -> None:
        self.db_path = Path(db_path)
        self.db_path.parent.mkdir(parents=True, exist_ok=True)
        self._migrate_legacy_if_needed()
        self.init_db()

    def connect(self) -> sqlite3.Connection:
        conn = sqlite3.connect(self.db_path)
        conn.row_factory = sqlite3.Row
        conn.execute("PRAGMA foreign_keys = ON;")
        return conn

    def _migrate_legacy_if_needed(self) -> None:
        """Backs up an older pre-3NF classroom.db if detected so the 13-table schema initializes cleanly."""
        if not self.db_path.exists():
            return
        try:
            conn = sqlite3.connect(self.db_path)
            cols = [r[1] for r in conn.execute("PRAGMA table_info(students)").fetchall()]
            tables = {
                r[0]
                for r in conn.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()
            }
            conn.close()
            if (cols and "student_name" not in cols) or ("sessions" in tables and "class_sessions" not in tables):
                stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
                backup = self.db_path.with_name(f"classroom_legacy_{stamp}.db.bak")
                shutil.move(str(self.db_path), str(backup))
        except sqlite3.Error:
            pass

    def init_db(self) -> None:
        with self.connect() as conn:
            conn.executescript(
                """

                PRAGMA foreign_keys = ON;



                -- 1. CORE ACADEMIC & BIOMETRIC REGISTRY

                CREATE TABLE IF NOT EXISTS courses (

                    course_code VARCHAR(20) PRIMARY KEY,

                    course_name VARCHAR(100) NOT NULL

                );



                CREATE TABLE IF NOT EXISTS lecturers (

                    lecturer_id VARCHAR(36) PRIMARY KEY,

                    name VARCHAR(100) NOT NULL,

                    email VARCHAR(100) NOT NULL UNIQUE

                );



                CREATE TABLE IF NOT EXISTS students (

                    student_id VARCHAR(50) PRIMARY KEY,

                    student_name VARCHAR(100) NOT NULL

                );



                CREATE TABLE IF NOT EXISTS course_enrollments (

                    course_code VARCHAR(20) NOT NULL,

                    student_id VARCHAR(50) NOT NULL,

                    enrolled_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,

                    PRIMARY KEY (course_code, student_id),

                    FOREIGN KEY (course_code) REFERENCES courses (course_code) ON DELETE CASCADE,

                    FOREIGN KEY (student_id) REFERENCES students (student_id) ON DELETE CASCADE

                );



                CREATE TABLE IF NOT EXISTS enrolled_face_profiles (

                    profile_id VARCHAR(36) PRIMARY KEY,

                    student_id VARCHAR(50) NOT NULL,

                    embedding_vector TEXT NOT NULL,

                    source_image VARCHAR(150) NOT NULL,

                    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,

                    UNIQUE (student_id, source_image),

                    FOREIGN KEY (student_id) REFERENCES students (student_id) ON DELETE CASCADE

                );



                -- 2. SESSION EXECUTION & PRE-BRANCH TRACKING

                CREATE TABLE IF NOT EXISTS class_sessions (

                    session_id VARCHAR(36) PRIMARY KEY,

                    course_code VARCHAR(20) NOT NULL,

                    lecturer_id VARCHAR(36) NOT NULL,

                    room_number VARCHAR(20) NOT NULL,

                    sampling_interval_sec FLOAT NOT NULL DEFAULT 3.0 CHECK (sampling_interval_sec > 0),

                    start_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,

                    end_time TIMESTAMP,

                    is_active BOOLEAN NOT NULL DEFAULT TRUE,

                    FOREIGN KEY (course_code) REFERENCES courses (course_code) ON DELETE CASCADE,

                    FOREIGN KEY (lecturer_id) REFERENCES lecturers (lecturer_id) ON DELETE RESTRICT

                );



                CREATE TABLE IF NOT EXISTS frame_sightings (

                    sighting_id VARCHAR(36) PRIMARY KEY,

                    session_id VARCHAR(36) NOT NULL,

                    tracking_id INT NOT NULL,

                    timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,

                    FOREIGN KEY (session_id) REFERENCES class_sessions (session_id) ON DELETE CASCADE

                );



                -- 3. FACE BRANCH, BEHAVIOR BRANCH & HUMAN-IN-THE-LOOP QUEUES

                CREATE TABLE IF NOT EXISTS attendance_sightings (

                    match_id VARCHAR(36) PRIMARY KEY,

                    session_id VARCHAR(36) NOT NULL,

                    student_id VARCHAR(50) NOT NULL,

                    tracking_id INT NOT NULL,

                    timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,

                    confidence_score FLOAT NOT NULL CHECK (confidence_score >= 0.0 AND confidence_score <= 1.0),

                    FOREIGN KEY (session_id) REFERENCES class_sessions (session_id) ON DELETE CASCADE,

                    FOREIGN KEY (student_id) REFERENCES students (student_id) ON DELETE CASCADE

                );



                CREATE TABLE IF NOT EXISTS attendance_logs (

                    attendance_id VARCHAR(36) PRIMARY KEY,

                    session_id VARCHAR(36) NOT NULL,

                    student_id VARCHAR(50) NOT NULL,

                    sighting_count INT NOT NULL DEFAULT 0 CHECK (sighting_count >= 0),

                    first_seen_timestamp TIMESTAMP,

                    status VARCHAR(20) NOT NULL DEFAULT 'Absent' CHECK (status IN ('Present', 'Absent')),

                    is_manual_override BOOLEAN NOT NULL DEFAULT FALSE,

                    confidence_score FLOAT,

                    UNIQUE (session_id, student_id),

                    CHECK (

                        is_manual_override = 1

                        OR (status = 'Present' AND sighting_count >= 3 AND first_seen_timestamp IS NOT NULL)

                        OR (status = 'Absent' AND sighting_count < 3)

                    ),

                    FOREIGN KEY (session_id) REFERENCES class_sessions (session_id) ON DELETE CASCADE,

                    FOREIGN KEY (student_id) REFERENCES students (student_id) ON DELETE CASCADE

                );



                CREATE TABLE IF NOT EXISTS unknown_faces (

                    unknown_id VARCHAR(36) PRIMARY KEY,

                    session_id VARCHAR(36) NOT NULL,

                    tracking_id INT NOT NULL,

                    timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,

                    crop_file_path VARCHAR(255) NOT NULL,

                    assigned_student_id VARCHAR(50),

                    status VARCHAR(20) NOT NULL DEFAULT 'Pending' CHECK (status IN ('Pending', 'Assigned', 'Dismissed')),

                    reviewed_at TIMESTAMP,

                    UNIQUE (session_id, tracking_id),

                    FOREIGN KEY (session_id) REFERENCES class_sessions (session_id) ON DELETE CASCADE,

                    FOREIGN KEY (assigned_student_id) REFERENCES students (student_id) ON DELETE SET NULL

                );



                CREATE TABLE IF NOT EXISTS attention_logs (

                    attention_id VARCHAR(36) PRIMARY KEY,

                    session_id VARCHAR(36) NOT NULL,

                    student_id VARCHAR(50) NOT NULL,

                    timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,

                    yaw_angle FLOAT NOT NULL,

                    pitch_angle FLOAT NOT NULL,

                    expression_state VARCHAR(20) NOT NULL DEFAULT 'Not Evaluated'

                        CHECK (expression_state IN ('Alert', 'Drowsy', 'Yawning', 'Not Evaluated')),

                    attention_state VARCHAR(20) NOT NULL

                        CHECK (attention_state IN ('Attentive', 'Low Engagement', 'Looking Away')),

                    FOREIGN KEY (session_id) REFERENCES class_sessions (session_id) ON DELETE CASCADE,

                    FOREIGN KEY (student_id) REFERENCES students (student_id) ON DELETE CASCADE

                );



                CREATE TABLE IF NOT EXISTS behavior_logs (

                    log_id VARCHAR(36) PRIMARY KEY,

                    session_id VARCHAR(36) NOT NULL,

                    student_id VARCHAR(50) NOT NULL,

                    timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,

                    last_updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,

                    behavior_type VARCHAR(30) NOT NULL DEFAULT 'Phone Use'

                        CHECK (behavior_type IN ('Phone Use')),

                    sample_count INT NOT NULL DEFAULT 3 CHECK (sample_count >= 3),

                    UNIQUE (session_id, student_id, behavior_type),

                    FOREIGN KEY (session_id) REFERENCES class_sessions (session_id) ON DELETE CASCADE,

                    FOREIGN KEY (student_id) REFERENCES students (student_id) ON DELETE CASCADE

                );



                CREATE TABLE IF NOT EXISTS flagged_events (

                    event_id VARCHAR(36) PRIMARY KEY,

                    session_id VARCHAR(36) NOT NULL,

                    student_id VARCHAR(50),

                    tracking_id INT,

                    flag_type VARCHAR(30) NOT NULL

                        CHECK (flag_type IN ('Drinking Flag', 'Smoking Flag')),

                    clip_file_path VARCHAR(255),

                    confidence_score FLOAT,

                    status VARCHAR(20) NOT NULL DEFAULT 'Unconfirmed'

                        CHECK (status IN ('Unconfirmed', 'Confirmed', 'Dismissed')),

                    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,

                    reviewed_at TIMESTAMP,

                    CHECK (status = 'Dismissed' OR clip_file_path IS NOT NULL),

                    FOREIGN KEY (session_id) REFERENCES class_sessions (session_id) ON DELETE CASCADE,

                    FOREIGN KEY (student_id) REFERENCES students (student_id) ON DELETE SET NULL

                );



                -- 4. PERFORMANCE INDEXES

                CREATE INDEX IF NOT EXISTS idx_profiles_student ON enrolled_face_profiles (student_id);

                CREATE INDEX IF NOT EXISTS idx_sessions_course ON class_sessions (course_code, start_time);

                CREATE INDEX IF NOT EXISTS idx_frame_sightings_session ON frame_sightings (session_id, timestamp);

                CREATE INDEX IF NOT EXISTS idx_att_sightings_session_student ON attendance_sightings (session_id, student_id);

                CREATE INDEX IF NOT EXISTS idx_unknown_faces_session_status ON unknown_faces (session_id, status);

                CREATE INDEX IF NOT EXISTS idx_attention_logs_session_student ON attention_logs (session_id, student_id);

                CREATE INDEX IF NOT EXISTS idx_behavior_logs_session_student ON behavior_logs (session_id, student_id);

                CREATE INDEX IF NOT EXISTS idx_flagged_events_session_status ON flagged_events (session_id, status);

                """
            )

    @staticmethod
    def _normalize_timestamp(ts: Optional[str]) -> Optional[str]:
        if not ts or not ts.strip():
            return None
        val = ts.strip().replace("T", " ")
        if len(val) == 16:  # YYYY-MM-DD HH:MM
            val += ":00"
        return val

    # ------------------------------------------------------------------
    # COURSES, LECTURERS & COURSE ENROLLMENTS
    # ------------------------------------------------------------------
    def upsert_course(self, course_code: str, course_name: str) -> dict[str, str]:
        code = course_code.strip().upper()
        name = course_name.strip()
        with self.connect() as conn:
            conn.execute(
                """

                INSERT INTO courses (course_code, course_name)

                VALUES (?, ?)

                ON CONFLICT(course_code) DO UPDATE SET course_name = excluded.course_name

                """,
                (code, name),
            )
        return {"course_code": code, "course_name": name}

    def list_courses(self) -> list[dict[str, Any]]:
        with self.connect() as conn:
            rows = conn.execute(
                """

                SELECT c.course_code, c.course_name,

                       COUNT(DISTINCT ce.student_id) AS enrolled_count,

                       COUNT(DISTINCT cs.session_id) AS session_count

                FROM courses c

                LEFT JOIN course_enrollments ce ON c.course_code = ce.course_code

                LEFT JOIN class_sessions cs ON c.course_code = cs.course_code

                GROUP BY c.course_code, c.course_name

                ORDER BY c.course_code

                """
            ).fetchall()
        return [dict(r) for r in rows]

    def delete_course(self, course_code: str) -> dict[str, Any]:
        code = course_code.strip().upper()
        with self.connect() as conn:
            exists = conn.execute(
                "SELECT 1 FROM courses WHERE course_code = ?",
                (code,),
            ).fetchone()
            if not exists:
                return {"deleted": False, "removed_session_ids": []}

            session_rows = conn.execute(
                "SELECT session_id FROM class_sessions WHERE course_code = ?",
                (code,),
            ).fetchall()
            removed_ids = [r["session_id"] for r in session_rows]

            # Remove child rows explicitly so legacy DBs with ON DELETE RESTRICT also delete cleanly
            conn.execute("DELETE FROM class_sessions WHERE course_code = ?", (code,))
            conn.execute("DELETE FROM course_enrollments WHERE course_code = ?", (code,))
            conn.execute("DELETE FROM courses WHERE course_code = ?", (code,))

        return {"deleted": True, "removed_session_ids": removed_ids}

    def upsert_lecturer(self, lecturer_id: str, name: str, email: str) -> dict[str, str]:
        lid = lecturer_id.strip()
        with self.connect() as conn:
            conn.execute(
                """

                INSERT INTO lecturers (lecturer_id, name, email)

                VALUES (?, ?, ?)

                ON CONFLICT(lecturer_id) DO UPDATE SET

                    name = excluded.name,

                    email = excluded.email

                """,
                (lid, name.strip(), email.strip()),
            )
        return {"lecturer_id": lid, "name": name.strip(), "email": email.strip()}

    def list_lecturers(self) -> list[dict[str, Any]]:
        with self.connect() as conn:
            rows = conn.execute("SELECT lecturer_id, name, email FROM lecturers ORDER BY name").fetchall()
        return [dict(r) for r in rows]

    def enroll_student_in_course(self, course_code: str, student_id: str) -> None:
        code = course_code.strip().upper()
        sid = student_id.strip()
        now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        with self.connect() as conn:
            conn.execute(
                """

                INSERT INTO course_enrollments (course_code, student_id, enrolled_at)

                VALUES (?, ?, ?)

                ON CONFLICT(course_code, student_id) DO NOTHING

                """,
                (code, sid, now),
            )
            active_sessions = conn.execute(
                "SELECT session_id FROM class_sessions WHERE course_code = ? AND is_active = 1",
                (code,),
            ).fetchall()
            for s in active_sessions:
                conn.execute(
                    """

                    INSERT OR IGNORE INTO attendance_logs

                        (attendance_id, session_id, student_id, sighting_count, status, is_manual_override)

                    VALUES (?, ?, ?, 0, 'Absent', 0)

                    """,
                    (str(uuid.uuid4()), s["session_id"], sid),
                )

    def unenroll_student_from_course(self, course_code: str, student_id: str) -> None:
        with self.connect() as conn:
            conn.execute(
                "DELETE FROM course_enrollments WHERE course_code = ? AND student_id = ?",
                (course_code.strip().upper(), student_id.strip()),
            )

    # ------------------------------------------------------------------
    # STUDENTS & MULTI-PROFILE FACE EMBEDDINGS
    # ------------------------------------------------------------------
    def upsert_student(

        self,

        student_id: str,

        student_name: str,

        course_code: Optional[str] = None,

    ) -> dict[str, str]:
        sid = student_id.strip()
        sname = student_name.strip()
        with self.connect() as conn:
            conn.execute(
                """

                INSERT INTO students (student_id, student_name)

                VALUES (?, ?)

                ON CONFLICT(student_id) DO UPDATE SET student_name = excluded.student_name

                """,
                (sid, sname),
            )
        if course_code:
            self.enroll_student_in_course(course_code, sid)
        return {"student_id": sid, "student_name": sname}

    def get_student(self, student_id: str) -> Optional[dict[str, Any]]:
        with self.connect() as conn:
            row = conn.execute(
                "SELECT student_id, student_name FROM students WHERE student_id = ?",
                (student_id.strip(),),
            ).fetchone()
        return dict(row) if row else None

    def delete_student(self, student_id: str) -> bool:
        sid = student_id.strip()
        with self.connect() as conn:
            cur = conn.execute("DELETE FROM students WHERE student_id = ?", (sid,))
            return cur.rowcount > 0

    def upsert_face_profile(

        self,

        student_id: str,

        embedding: np.ndarray,

        source_image: str,

    ) -> str:
        sid = student_id.strip()
        vec_json = json.dumps([round(float(x), 6) for x in embedding.astype(np.float32).flatten()])
        now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        pid = str(uuid.uuid4())
        with self.connect() as conn:
            conn.execute(
                """

                INSERT INTO enrolled_face_profiles (profile_id, student_id, embedding_vector, source_image, created_at)

                VALUES (?, ?, ?, ?, ?)

                ON CONFLICT(student_id, source_image) DO UPDATE SET

                    embedding_vector = excluded.embedding_vector,

                    created_at = excluded.created_at

                """,
                (pid, sid, vec_json, source_image, now),
            )
            row = conn.execute(
                "SELECT profile_id FROM enrolled_face_profiles WHERE student_id = ? AND source_image = ?",
                (sid, source_image),
            ).fetchone()
            return str(row["profile_id"]) if row else pid

    def delete_face_profile(self, profile_id: str) -> Optional[dict[str, str]]:
        with self.connect() as conn:
            row = conn.execute(
                """

                SELECT p.profile_id, p.student_id, p.source_image, s.student_name

                FROM enrolled_face_profiles p

                JOIN students s ON p.student_id = s.student_id

                WHERE p.profile_id = ?

                """,
                (profile_id,),
            ).fetchone()
            if not row:
                return None
            info = dict(row)
            conn.execute("DELETE FROM enrolled_face_profiles WHERE profile_id = ?", (profile_id,))
            return info

    def list_students_with_profiles(self) -> list[dict[str, Any]]:
        with self.connect() as conn:
            students = conn.execute(
                "SELECT student_id, student_name FROM students ORDER BY student_id"
            ).fetchall()
            result: list[dict[str, Any]] = []
            for s in students:
                sid = s["student_id"]
                courses = [
                    dict(c)
                    for c in conn.execute(
                        """

                        SELECT c.course_code, c.course_name

                        FROM course_enrollments ce

                        JOIN courses c ON ce.course_code = c.course_code

                        WHERE ce.student_id = ?

                        ORDER BY c.course_code

                        """,
                        (sid,),
                    ).fetchall()
                ]
                profiles = [
                    dict(p)
                    for p in conn.execute(
                        """

                        SELECT profile_id, source_image, created_at

                        FROM enrolled_face_profiles

                        WHERE student_id = ?

                        ORDER BY created_at

                        """,
                        (sid,),
                    ).fetchall()
                ]
                result.append(
                    {
                        "student_id": sid,
                        "student_name": s["student_name"],
                        "courses": courses,
                        "profiles": profiles,
                        "photo_count": len(profiles),
                    }
                )
            return result

    def load_enrolled_profiles(self, course_code: Optional[str] = None) -> list[dict[str, Any]]:
        with self.connect() as conn:
            rows = []
            if course_code:
                rows = conn.execute(
                    """

                    SELECT p.profile_id, s.student_id, s.student_name, p.embedding_vector, p.source_image

                    FROM enrolled_face_profiles p

                    JOIN students s ON p.student_id = s.student_id

                    JOIN course_enrollments ce ON s.student_id = ce.student_id

                    WHERE ce.course_code = ?

                    ORDER BY s.student_id, p.created_at

                    """,
                    (course_code.strip().upper(),),
                ).fetchall()
            if not rows:
                rows = conn.execute(
                    """

                    SELECT p.profile_id, s.student_id, s.student_name, p.embedding_vector, p.source_image

                    FROM enrolled_face_profiles p

                    JOIN students s ON p.student_id = s.student_id

                    ORDER BY s.student_id, p.created_at

                    """
                ).fetchall()

        profiles: list[dict[str, Any]] = []
        for r in rows:
            vec = np.array(json.loads(r["embedding_vector"]), dtype=np.float32)
            profiles.append(
                {
                    "profile_id": r["profile_id"],
                    "student_id": r["student_id"],
                    "student_name": r["student_name"],
                    "full_name": r["student_name"],
                    "source_image": r["source_image"],
                    "embedding": vec,
                }
            )
        return profiles

    # ------------------------------------------------------------------
    # CLASS SESSIONS
    # ------------------------------------------------------------------
    def create_session(

        self,

        course_code: str,

        lecturer_id: str = "LEC001",

        room_number: str = "Room 101",

        sampling_interval_sec: float = 3.0,

        course_name: Optional[str] = None,

        lecturer_name: str = "Course Lecturer",

        lecturer_email: str = "lecturer@university.edu",

        start_time: Optional[str] = None,

        end_time: Optional[str] = None,

        deactivate_others: bool = True,

    ) -> str:
        code = course_code.strip().upper()
        lid = lecturer_id.strip()
        session_id = str(uuid.uuid4())[:8].upper()
        now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        norm_start = self._normalize_timestamp(start_time) or now
        norm_end = self._normalize_timestamp(end_time)

        with self.connect() as conn:
            conn.execute(
                """

                INSERT INTO courses (course_code, course_name)

                VALUES (?, ?)

                ON CONFLICT(course_code) DO NOTHING

                """,
                (code, (course_name or f"{code} Lecture").strip()),
            )
            conn.execute(
                """

                INSERT INTO lecturers (lecturer_id, name, email)

                VALUES (?, ?, ?)

                ON CONFLICT(lecturer_id) DO NOTHING

                """,
                (lid, lecturer_name.strip(), lecturer_email.strip()),
            )
            if deactivate_others:
                conn.execute(
                    "UPDATE class_sessions SET is_active = 0, end_time = COALESCE(end_time, ?) WHERE is_active = 1",
                    (now,),
                )
            conn.execute(
                """

                INSERT INTO class_sessions

                    (session_id, course_code, lecturer_id, room_number, sampling_interval_sec, start_time, end_time, is_active)

                VALUES (?, ?, ?, ?, ?, ?, ?, 1)

                """,
                (session_id, code, lid, room_number.strip(), float(sampling_interval_sec), norm_start, norm_end),
            )

            enrolled = conn.execute(
                "SELECT student_id FROM course_enrollments WHERE course_code = ?",
                (code,),
            ).fetchall()
            if not enrolled:
                enrolled = conn.execute("SELECT student_id FROM students").fetchall()

            for row in enrolled:
                conn.execute(
                    """

                    INSERT OR IGNORE INTO attendance_logs

                        (attendance_id, session_id, student_id, sighting_count, status, is_manual_override)

                    VALUES (?, ?, ?, 0, 'Absent', 0)

                    """,
                    (str(uuid.uuid4()), session_id, row["student_id"]),
                )

        return session_id

    def delete_session(self, session_id: str) -> bool:
        with self.connect() as conn:
            cur = conn.execute("DELETE FROM class_sessions WHERE session_id = ?", (session_id.strip(),))
            return cur.rowcount > 0

    def list_sessions(self) -> list[dict[str, Any]]:
        with self.connect() as conn:
            rows = conn.execute(
                """

                SELECT cs.session_id, cs.course_code, c.course_name,

                       cs.lecturer_id, l.name AS lecturer_name,

                       cs.room_number, cs.sampling_interval_sec,

                       cs.start_time, cs.end_time, cs.is_active

                FROM class_sessions cs

                JOIN courses c ON cs.course_code = c.course_code

                JOIN lecturers l ON cs.lecturer_id = l.lecturer_id

                ORDER BY cs.start_time DESC

                """
            ).fetchall()
        return [dict(r) for r in rows]

    def finalize_attendance(self, session_id: str, min_sightings: int = 3) -> list[dict[str, Any]]:
        now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        with self.connect() as conn:
            sess = conn.execute(
                "SELECT course_code FROM class_sessions WHERE session_id = ?",
                (session_id,),
            ).fetchone()
            if not sess:
                return []
            code = sess["course_code"]
            conn.execute(
                "UPDATE class_sessions SET end_time = COALESCE(end_time, ?), is_active = 0 WHERE session_id = ?",
                (now, session_id),
            )

            students = conn.execute(
                """

                SELECT s.student_id, s.student_name

                FROM students s

                JOIN course_enrollments ce ON s.student_id = ce.student_id

                WHERE ce.course_code = ?

                ORDER BY s.student_id

                """,
                (code,),
            ).fetchall()
            if not students:
                students = conn.execute("SELECT student_id, student_name FROM students ORDER BY student_id").fetchall()

            report: list[dict[str, Any]] = []
            for s in students:
                sid = s["student_id"]
                stats = conn.execute(
                    """

                    SELECT COUNT(*) AS cnt, MIN(timestamp) AS first_ts, MAX(confidence_score) AS max_conf

                    FROM attendance_sightings

                    WHERE session_id = ? AND student_id = ?

                    """,
                    (session_id, sid),
                ).fetchone()
                cnt = int(stats["cnt"])
                first_ts = stats["first_ts"]
                max_conf = float(stats["max_conf"]) if stats["max_conf"] is not None else None
                status = "Present" if cnt >= min_sightings else "Absent"

                conn.execute(
                    """

                    INSERT INTO attendance_logs

                        (attendance_id, session_id, student_id, sighting_count, first_seen_timestamp, status, is_manual_override, confidence_score)

                    VALUES (?, ?, ?, ?, ?, ?, 0, ?)

                    ON CONFLICT(session_id, student_id) DO UPDATE SET

                        sighting_count = excluded.sighting_count,

                        first_seen_timestamp = excluded.first_seen_timestamp,

                        confidence_score = excluded.confidence_score,

                        status = CASE

                            WHEN attendance_logs.is_manual_override = 1 THEN attendance_logs.status

                            ELSE excluded.status

                        END

                    """,
                    (str(uuid.uuid4()), session_id, sid, cnt, first_ts, status, max_conf),
                )
                report.append(
                    {
                        "student_id": sid,
                        "student_name": s["student_name"],
                        "status": status,
                        "sighting_count": cnt,
                        "first_seen_timestamp": first_ts or "-",
                    }
                )
            return report

    # ------------------------------------------------------------------
    # PIPELINE EVENT PERSISTENCE
    # ------------------------------------------------------------------
    def persist_events(

        self,

        session_id: str,

        events: list[dict[str, Any]],

        min_sightings_present: int = 3,

    ) -> None:
        if not events or not session_id:
            return
        with self.connect() as conn:
            exists = conn.execute(
                "SELECT 1 FROM class_sessions WHERE session_id = ?",
                (session_id,),
            ).fetchone()
            if not exists:
                return

            _cp_persist_extra_events(conn, session_id, events)
            for ev in events:
                etype = ev.get("type")
                if etype == "raw_sighting":
                    conn.execute(
                        """

                        INSERT INTO frame_sightings (sighting_id, session_id, tracking_id, timestamp)

                        VALUES (?, ?, ?, ?)

                        """,
                        (str(uuid.uuid4()), session_id, int(ev.get("track_id", 0)), ev.get("timestamp", "")),
                    )

                elif etype == "attendance_sighting":
                    sid = str(ev["student_id"])
                    ts = str(ev.get("timestamp", ""))
                    sim = max(0.0, min(1.0, float(ev.get("similarity") or ev.get("confidence_score") or 0.0)))
                    tid = int(ev.get("track_id") or ev.get("tracking_id") or 0)

                    conn.execute(
                        """

                        INSERT INTO attendance_sightings

                            (match_id, session_id, student_id, tracking_id, timestamp, confidence_score)

                        VALUES (?, ?, ?, ?, ?, ?)

                        """,
                        (str(uuid.uuid4()), session_id, sid, tid, ts, sim),
                    )
                    conn.execute(
                        """

                        INSERT OR IGNORE INTO attendance_logs

                            (attendance_id, session_id, student_id, sighting_count, status, is_manual_override)

                        VALUES (?, ?, ?, 0, 'Absent', 0)

                        """,
                        (str(uuid.uuid4()), session_id, sid),
                    )
                    conn.execute(
                        """

                        UPDATE attendance_logs

                        SET sighting_count = sighting_count + 1,

                            first_seen_timestamp = COALESCE(first_seen_timestamp, ?),

                            confidence_score = MAX(COALESCE(confidence_score, 0.0), ?),

                            status = CASE

                                WHEN is_manual_override = 1 THEN status

                                WHEN (sighting_count + 1) >= ? THEN 'Present'

                                ELSE 'Absent'

                            END

                        WHERE session_id = ? AND student_id = ?

                        """,
                        (ts, sim, int(min_sightings_present), session_id, sid),
                    )

                elif etype == "unknown_face":
                    conn.execute(
                        """

                        INSERT INTO unknown_faces

                            (unknown_id, session_id, tracking_id, timestamp, crop_file_path, status)

                        VALUES (?, ?, ?, ?, ?, 'Pending')

                        ON CONFLICT(session_id, tracking_id) DO NOTHING

                        """,
                        (
                            str(uuid.uuid4()),
                            session_id,
                            int(ev.get("track_id", 0)),
                            str(ev.get("timestamp", "")),
                            str(ev.get("crop_path") or ev.get("crop_file_path") or ""),
                        ),
                    )

                elif etype == "attention_update" or (
                    etype == "behavior_update"
                    and not ev.get("phone_in_use")
                    and ev.get("behavior_type") != "Phone Use"
                ):
                    sid = ev.get("student_id")
                    if not sid:
                        continue
                    raw_state = str(ev.get("attention_state", "Attentive"))
                    if raw_state == "Low Engage":
                        raw_state = "Low Engagement"
                    if raw_state not in {"Attentive", "Low Engagement", "Looking Away"}:
                        raw_state = "Attentive"

                    expr = str(ev.get("expression_state", "Not Evaluated"))
                    if expr not in {"Alert", "Drowsy", "Yawning", "Not Evaluated"}:
                        expr = "Not Evaluated"

                    conn.execute(
                        """

                        INSERT INTO attention_logs

                            (attention_id, session_id, student_id, timestamp, yaw_angle, pitch_angle, expression_state, attention_state)

                        VALUES (?, ?, ?, ?, ?, ?, ?, ?)

                        """,
                        (
                            str(uuid.uuid4()),
                            session_id,
                            str(sid),
                            str(ev.get("timestamp", "")),
                            float(ev.get("yaw_angle", 0.0)),
                            float(ev.get("pitch_angle", 0.0)),
                            expr,
                            raw_state,
                        ),
                    )

                elif etype in ("behavior_update", "phone_event") and (
                    ev.get("phone_in_use")
                    or ev.get("behavior_type") == "Phone Use"
                    or etype == "phone_event"
                ):
                    sid = ev.get("student_id")
                    if not sid:
                        continue
                    ts = str(ev.get("timestamp", ""))
                    samples = max(3, int(ev.get("sample_count", 3)))
                    conn.execute(
                        """

                        INSERT INTO behavior_logs

                            (log_id, session_id, student_id, timestamp, last_updated_at, behavior_type, sample_count)

                        VALUES (?, ?, ?, ?, ?, 'Phone Use', ?)

                        ON CONFLICT(session_id, student_id, behavior_type) DO UPDATE SET

                            sample_count = behavior_logs.sample_count + 1,

                            last_updated_at = excluded.last_updated_at

                        """,
                        (str(uuid.uuid4()), session_id, str(sid), ts, ts, samples),
                    )

                elif etype == "incident_flag":
                    raw_flag = str(ev.get("flag_type", "Drinking Flag"))
                    if raw_flag == "Drinking":
                        raw_flag = "Drinking Flag"
                    elif raw_flag == "Smoking":
                        raw_flag = "Smoking Flag"
                    conn.execute(
                        """

                        INSERT INTO flagged_events

                            (event_id, session_id, student_id, tracking_id, flag_type, clip_file_path, confidence_score, status, created_at)

                        VALUES (?, ?, ?, ?, ?, ?, ?, 'Unconfirmed', ?)

                        """,
                        (
                            str(uuid.uuid4()),
                            session_id,
                            (None if ev.get("student_id") in (None, "", "None", "Unknown") else str(ev.get("student_id"))),
                            ev.get("track_id"),
                            raw_flag,
                            str(ev.get("clip_path") or ev.get("clip_file_path") or ""),
                            ev.get("confidence_score"),
                            str(ev.get("timestamp", "")),
                        ),
                    )

    # ------------------------------------------------------------------
    # LECTURER ACTIONS & DASHBOARD QUERIES
    # ------------------------------------------------------------------
    def override_attendance(self, session_id: str, student_id: str, status: str) -> None:
        if status not in {"Present", "Absent"}:
            raise ValueError("Status must be Present or Absent")
        with self.connect() as conn:
            conn.execute(
                """

                INSERT INTO attendance_logs

                    (attendance_id, session_id, student_id, sighting_count, status, is_manual_override)

                VALUES (?, ?, ?, 0, ?, 1)

                ON CONFLICT(session_id, student_id) DO UPDATE SET

                    status = excluded.status,

                    is_manual_override = 1

                """,
                (str(uuid.uuid4()), session_id, student_id, status),
            )

    def review_flag(self, event_id: str, action: str) -> Optional[str]:
        if action not in {"Confirmed", "Dismissed"}:
            raise ValueError("Action must be Confirmed or Dismissed")
        now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        with self.connect() as conn:
            row = conn.execute(
                "SELECT clip_file_path FROM flagged_events WHERE event_id = ?",
                (event_id,),
            ).fetchone()
            if not row:
                return None
            clip_path = row["clip_file_path"]
            if action == "Dismissed":
                conn.execute(
                    """

                    UPDATE flagged_events

                    SET status = 'Dismissed', clip_file_path = NULL, reviewed_at = ?

                    WHERE event_id = ?

                    """,
                    (now, event_id),
                )
            else:
                conn.execute(
                    """

                    UPDATE flagged_events

                    SET status = 'Confirmed', reviewed_at = ?

                    WHERE event_id = ?

                    """,
                    (now, event_id),
                )

        if action == "Dismissed" and clip_path:
            Path(clip_path).unlink(missing_ok=True)
        return action

    def assign_unknown(self, unknown_id: str, student_id: str, min_sightings_present: int = 3) -> bool:
        now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        with self.connect() as conn:
            unk = conn.execute(
                "SELECT session_id, tracking_id, timestamp FROM unknown_faces WHERE unknown_id = ?",
                (unknown_id,),
            ).fetchone()
            if not unk:
                return False
            sid_session = unk["session_id"]
            conn.execute(
                """

                UPDATE unknown_faces

                SET assigned_student_id = ?, status = 'Assigned', reviewed_at = ?

                WHERE unknown_id = ?

                """,
                (student_id, now, unknown_id),
            )
            conn.execute(
                """

                INSERT INTO attendance_sightings

                    (match_id, session_id, student_id, tracking_id, timestamp, confidence_score)

                VALUES (?, ?, ?, ?, ?, 1.0)

                """,
                (str(uuid.uuid4()), sid_session, student_id, int(unk["tracking_id"]), unk["timestamp"]),
            )
            conn.execute(
                """

                INSERT OR IGNORE INTO attendance_logs

                    (attendance_id, session_id, student_id, sighting_count, status, is_manual_override)

                VALUES (?, ?, ?, 0, 'Absent', 0)

                """,
                (str(uuid.uuid4()), sid_session, student_id),
            )
            conn.execute(
                """

                UPDATE attendance_logs

                SET sighting_count = sighting_count + 1,

                    first_seen_timestamp = COALESCE(first_seen_timestamp, ?),

                    status = CASE

                        WHEN is_manual_override = 1 THEN status

                        WHEN (sighting_count + 1) >= ? THEN 'Present'

                        ELSE 'Absent'

                    END

                WHERE session_id = ? AND student_id = ?

                """,
                (unk["timestamp"], int(min_sightings_present), sid_session, student_id),
            )
            return True

    def get_session_summary(self, session_id: str) -> Optional[dict[str, Any]]:
        with self.connect() as conn:
            sess = conn.execute(
                """

                SELECT cs.*, c.course_name, l.name AS lecturer_name

                FROM class_sessions cs

                JOIN courses c ON cs.course_code = c.course_code

                JOIN lecturers l ON cs.lecturer_id = l.lecturer_id

                WHERE cs.session_id = ?

                """,
                (session_id,),
            ).fetchone()
            if not sess:
                return None

            code = sess["course_code"]
            enrolled_rows = conn.execute(
                """

                SELECT s.student_id, s.student_name

                FROM students s

                JOIN course_enrollments ce ON s.student_id = ce.student_id

                WHERE ce.course_code = ?

                ORDER BY s.student_id

                """,
                (code,),
            ).fetchall()
            if not enrolled_rows:
                enrolled_rows = conn.execute(
                    "SELECT student_id, student_name FROM students ORDER BY student_id"
                ).fetchall()

            roster: list[dict[str, Any]] = []
            present_count = 0
            tot_att = 0
            tot_low = 0
            tot_away = 0
            tot_phone = 0

            for s in enrolled_rows:
                sid = s["student_id"]
                al = conn.execute(
                    """

                    SELECT *

                    FROM attendance_logs

                    WHERE session_id = ? AND student_id = ?

                    """,
                    (session_id, sid),
                ).fetchone()

                sighting_count = int(al["sighting_count"]) if al else 0
                first_seen = al["first_seen_timestamp"] if al else None
                status = al["status"] if al else "Absent"
                overridden = bool(al["is_manual_override"]) if al else False
                if status == "Present":
                    present_count += 1

                att_rows = conn.execute(
                    "SELECT attention_state FROM attention_logs WHERE session_id = ? AND student_id = ?",
                    (session_id, sid),
                ).fetchall()
                a_cnt = sum(1 for r in att_rows if r["attention_state"] == "Attentive")
                l_cnt = sum(1 for r in att_rows if r["attention_state"] == "Low Engagement")
                w_cnt = sum(1 for r in att_rows if r["attention_state"] == "Looking Away")
                b_tot = a_cnt + l_cnt + w_cnt
                att_pct = round((a_cnt / b_tot) * 100.0, 1) if b_tot else 0.0

                ph_row = conn.execute(
                    """

                    SELECT COALESCE(SUM(sample_count), 0) AS samples, COALESCE(SUM(usage_seconds), 0.0) AS usage_sec, MAX(clip_path) AS clip_path

                    FROM behavior_logs

                    WHERE session_id = ? AND student_id = ? AND behavior_type = 'Phone Use'

                    """,
                    (session_id, sid),
                ).fetchone()
                ph_samples = int(ph_row["samples"]) if ph_row else 0

                tot_att += a_cnt
                tot_low += l_cnt
                tot_away += w_cnt
                tot_phone += ph_samples

                roster.append(
                    {
                        "student_id": sid,
                        "student_name": s["student_name"],
                        "sighting_count": sighting_count,
                        "first_seen_at": first_seen,
                        "status": status,
                        "overridden_by_lecturer": overridden,
                        "attentive_count": a_cnt,
                        "low_engage_count": l_cnt,
                        "looking_away_count": w_cnt,
                        "attention_pct": att_pct,
                        "phone_count": ph_samples,
                        "attentive_seconds": round(float(al["attentive_seconds"] or 0.0), 1) if (al and "attentive_seconds" in al.keys()) else 0.0,
                        "attentive_time_fmt": format_duration(al["attentive_seconds"] if (al and "attentive_seconds" in al.keys()) else 0.0),
                        "phone_usage_seconds": round(float(ph_row["usage_sec"] or 0.0), 1) if (ph_row and "usage_sec" in ph_row.keys()) else 0.0,
                        "phone_usage_fmt": format_duration(ph_row["usage_sec"] if (ph_row and "usage_sec" in ph_row.keys()) else 0.0),
                        "phone_clip_url": f"/clips/{Path(ph_row['clip_path']).name}" if (ph_row and "clip_path" in ph_row.keys() and ph_row["clip_path"]) else None,
                    }
                )

            flags = [
                dict(f)
                for f in conn.execute(
                    """

                    SELECT fe.*, s.student_name

                    FROM flagged_events fe

                    LEFT JOIN students s ON fe.student_id = s.student_id

                    WHERE fe.session_id = ?

                    ORDER BY fe.created_at DESC

                    """,
                    (session_id,),
                ).fetchall()
            ]
            for f in flags:
                clip = f.get("clip_file_path")
                f["clip_url"] = f"/clips/{Path(clip).name}" if clip else None

            unknowns = [
                dict(u)
                for u in conn.execute(
                    """

                    SELECT * FROM unknown_faces

                    WHERE session_id = ?

                    ORDER BY timestamp DESC

                    """,
                    (session_id,),
                ).fetchall()
            ]
            for u in unknowns:
                u["crop_url"] = f"/unknown_faces/{Path(u['crop_file_path']).name}"

            raw_count = conn.execute(
                "SELECT COUNT(*) AS c FROM frame_sightings WHERE session_id = ?",
                (session_id,),
            ).fetchone()["c"]

        _cp_summary = {
            "session": dict(sess),
            "metrics": {
                "enrolled_total": len(roster),
                "present_count": present_count,
                "attentive_samples": tot_att,
                "low_engage_samples": tot_low,
                "looking_away_samples": tot_away,
                "phone_use_samples": tot_phone,
                "pending_flags": sum(1 for f in flags if f["status"] == "Unconfirmed"),
                "unassigned_unknowns": sum(1 for u in unknowns if u["status"] == "Pending"),
                "raw_tracking_sightings": int(raw_count),
            },
            "roster": roster,
            "incident_flags": flags,
            "unknown_faces": unknowns,
        }
        with self.connect() as _cp_c:
            _cp_summary = _cp_enrich_summary(_cp_c, session_id, _cp_summary)
        return _cp_summary

    def get_student_portal(self, student_id: str) -> Optional[dict[str, Any]]:
        sid = student_id.strip()
        with self.connect() as conn:
            st = conn.execute(
                "SELECT student_id, student_name FROM students WHERE student_id = ?",
                (sid,),
            ).fetchone()
            if not st:
                return None

            courses = [
                dict(c)
                for c in conn.execute(
                    """

                    SELECT c.course_code, c.course_name

                    FROM course_enrollments ce

                    JOIN courses c ON ce.course_code = c.course_code

                    WHERE ce.student_id = ?

                    ORDER BY c.course_code

                    """,
                    (sid,),
                ).fetchall()
            ]

            sessions = conn.execute(
                """

                SELECT cs.session_id, cs.course_code, c.course_name, cs.room_number,

                       cs.start_time, cs.end_time, cs.is_active,

                       COALESCE(al.status, 'Absent') AS status,

                       COALESCE(al.sighting_count, 0) AS sighting_count,

                       al.first_seen_timestamp

                FROM class_sessions cs

                JOIN courses c ON cs.course_code = c.course_code

                LEFT JOIN attendance_logs al

                  ON cs.session_id = al.session_id AND al.student_id = ?

                WHERE EXISTS (

                    SELECT 1 FROM course_enrollments ce

                    WHERE ce.course_code = cs.course_code AND ce.student_id = ?

                ) OR al.student_id IS NOT NULL

                ORDER BY cs.start_time DESC

                """,
                (sid, sid),
            ).fetchall()

            session_list: list[dict[str, Any]] = []
            present_sessions = 0
            tot_a = 0
            tot_l = 0
            tot_w = 0
            tot_ph = 0

            for s in sessions:
                sess_id = s["session_id"]
                if s["status"] == "Present":
                    present_sessions += 1

                att_rows = conn.execute(
                    "SELECT attention_state FROM attention_logs WHERE session_id = ? AND student_id = ?",
                    (sess_id, sid),
                ).fetchall()
                a_cnt = sum(1 for r in att_rows if r["attention_state"] == "Attentive")
                l_cnt = sum(1 for r in att_rows if r["attention_state"] == "Low Engagement")
                w_cnt = sum(1 for r in att_rows if r["attention_state"] == "Looking Away")
                b_tot = a_cnt + l_cnt + w_cnt
                att_pct = round((a_cnt / b_tot) * 100.0, 1) if b_tot else 0.0

                ph_row = conn.execute(
                    """

                    SELECT COALESCE(SUM(sample_count), 0) AS samples, COALESCE(SUM(usage_seconds), 0.0) AS usage_sec, MAX(clip_path) AS clip_path

                    FROM behavior_logs

                    WHERE session_id = ? AND student_id = ? AND behavior_type = 'Phone Use'

                    """,
                    (sess_id, sid),
                ).fetchone()
                ph_samples = int(ph_row["samples"]) if ph_row else 0

                tot_a += a_cnt
                tot_l += l_cnt
                tot_w += w_cnt
                tot_ph += ph_samples

                item = dict(s)
                item["attentive_count"] = a_cnt
                item["low_engage_count"] = l_cnt
                item["looking_away_count"] = w_cnt
                item["attention_pct"] = att_pct
                item["phone_count"] = ph_samples
                session_list.append(item)

        tot_sessions = len(session_list)
        tot_beh = tot_a + tot_l + tot_w
        return {
            "student": dict(st),
            "courses": courses,
            "overview": {
                "sessions_present": present_sessions,
                "sessions_total": tot_sessions,
                "attendance_rate_pct": round((present_sessions / tot_sessions) * 100.0, 1) if tot_sessions else 0.0,
                "overall_attention_pct": round((tot_a / tot_beh) * 100.0, 1) if tot_beh else 0.0,
                "total_phone_samples": tot_ph,
            },
            "sessions": session_list,
        }







# _cp_db_enhancements
def _cp_ensure_extra_columns(conn) -> None:
    try:
        tables = {r[0] for r in conn.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()}
        if "attendance_logs" in tables:
            cols = {r[1] for r in conn.execute("PRAGMA table_info(attendance_logs)").fetchall()}
            if "attentive_seconds" not in cols:
                conn.execute("ALTER TABLE attendance_logs ADD COLUMN attentive_seconds REAL DEFAULT 0.0")
        if "behavior_logs" in tables:
            cols = {r[1] for r in conn.execute("PRAGMA table_info(behavior_logs)").fetchall()}
            if "usage_seconds" not in cols:
                conn.execute("ALTER TABLE behavior_logs ADD COLUMN usage_seconds REAL DEFAULT 0.0")
            if "clip_path" not in cols:
                conn.execute("ALTER TABLE behavior_logs ADD COLUMN clip_path TEXT DEFAULT ''")
    except Exception:
        pass


def _cp_persist_extra_events(conn, session_id: str, events: list[dict]) -> None:
    _cp_ensure_extra_columns(conn)
    for ev in events:
        etype = str(ev.get("type", ""))
        if etype == "attention_time" and ev.get("student_id"):
            delta = float(ev.get("delta_seconds", 0.0))
            sid = str(ev["student_id"])
            cur = conn.execute(
                """

                UPDATE attendance_logs

                SET attentive_seconds = COALESCE(attentive_seconds, 0.0) + ?

                WHERE session_id = ? AND student_id = ?

                """,
                (delta, str(session_id), sid),
            )
            if cur.rowcount == 0:
                conn.execute(
                    """

                    INSERT OR IGNORE INTO attendance_logs

                        (attendance_id, session_id, student_id, sighting_count, status, is_manual_override, attentive_seconds)

                    VALUES (lower(hex(randomblob(16))), ?, ?, 0, 'Absent', 0, ?)

                    """,
                    (str(session_id), sid, delta),
                )

        elif etype in ("phone_usage", "phone_usage_update"):
            usage_sec = float(ev.get("usage_seconds", 0.0))
            clip_path = str(ev.get("clip_path", "") or "")
            sid = ev.get("student_id")
            sid_val = None if sid in (None, "", "None", "Unknown") else str(sid)
            ts = str(ev.get("timestamp", ""))
            if not sid_val:
                continue

            if etype == "phone_usage":
                conn.execute(
                    """

                    INSERT INTO behavior_logs

                        (log_id, session_id, student_id, timestamp, last_updated_at, behavior_type, sample_count, usage_seconds, clip_path)

                    VALUES (lower(hex(randomblob(16))), ?, ?, ?, ?, 'Phone Use', 3, ?, ?)

                    ON CONFLICT(session_id, student_id, behavior_type) DO UPDATE SET

                        sample_count = behavior_logs.sample_count + 1,

                        last_updated_at = excluded.last_updated_at,

                        usage_seconds = COALESCE(behavior_logs.usage_seconds, 0.0) + excluded.usage_seconds,

                        clip_path = CASE WHEN excluded.clip_path != '' THEN excluded.clip_path ELSE behavior_logs.clip_path END

                    """,
                    (str(session_id), sid_val, ts, ts, usage_sec, clip_path),
                )
            elif etype == "phone_usage_update":
                conn.execute(
                    """

                    UPDATE behavior_logs

                    SET last_updated_at = ?,

                        usage_seconds = MAX(COALESCE(usage_seconds, 0.0), ?),

                        clip_path = CASE WHEN ? != '' THEN ? ELSE clip_path END

                    WHERE session_id = ? AND student_id = ? AND behavior_type = 'Phone Use'

                    """,
                    (ts, usage_sec, clip_path, clip_path, str(session_id), sid_val),
                )


def _cp_enrich_summary(conn, session_id: str, summary: dict) -> dict:
    if not summary or "roster" not in summary:
        return summary
    _cp_ensure_extra_columns(conn)
    sess = summary.get("session") or {}
    is_active = bool(sess.get("is_active", 0))
    sample_sec = float(sess.get("sampling_interval_sec") or 2.0)
    stale_cutoff = max(5.0, sample_sec * 3.0)

    att_sec_map: dict[str, float] = {}
    try:
        for r in conn.execute(
            "SELECT student_id, COALESCE(attentive_seconds, 0.0) AS sec FROM attendance_logs WHERE session_id = ?",
            (str(session_id),),
        ).fetchall():
            att_sec_map[str(r["student_id"])] = float(r["sec"] or 0.0)
    except Exception:
        pass

    live_att_map: dict[str, bool] = {}
    if is_active:
        try:
            from datetime import datetime
            now_dt = datetime.now()
            for r in conn.execute(
                """

                SELECT student_id, attention_state, timestamp

                FROM attention_logs

                WHERE session_id = ?

                ORDER BY rowid DESC

                """,
                (str(session_id),),
            ).fetchall():
                sid = str(r["student_id"])
                if sid in live_att_map:
                    continue
                is_att_state = str(r["attention_state"] or "").strip().lower() == "attentive"
                fresh = False
                ts_raw = r["timestamp"]
                if ts_raw:
                    try:
                        ts_dt = datetime.fromisoformat(str(ts_raw).replace(" ", "T")).replace(tzinfo=None)
                        fresh = (now_dt - ts_dt).total_seconds() <= stale_cutoff
                    except Exception:
                        fresh = True
                live_att_map[sid] = bool(is_att_state and fresh)
        except Exception:
            pass

    phone_map: dict[str, dict] = {}
    try:
        for r in conn.execute(
            """

            SELECT student_id, COALESCE(SUM(usage_seconds), 0.0) AS usage_sec, MAX(clip_path) AS clip_path

            FROM behavior_logs

            WHERE session_id = ? AND behavior_type = 'Phone Use'

            GROUP BY student_id

            """,
            (str(session_id),),
        ).fetchall():
            cp = str(r["clip_path"] or "")
            phone_map[str(r["student_id"])] = {
                "usage_sec": float(r["usage_sec"] or 0.0),
                "clip_url": f"/clips/{Path(cp).name}" if cp else None,
            }
    except Exception:
        pass

    for item in summary["roster"]:
        sid = str(item.get("student_id", ""))
        sec = att_sec_map.get(sid, float(item.get("attentive_seconds", 0.0)))
        # Fallback estimate if attentive_count > 0 and sec == 0
        if sec <= 0.0 and int(item.get("attentive_count", 0)) > 0:
            sec = round(int(item["attentive_count"]) * sample_sec, 1)
        item["attentive_seconds"] = round(sec, 1)
        item["attentive_time_fmt"] = format_duration(sec)
        item["is_currently_attentive"] = bool(is_active and live_att_map.get(sid, False))

        ph = phone_map.get(sid, {})
        p_sec = float(ph.get("usage_sec", 0.0))
        item["phone_usage_seconds"] = round(p_sec, 1)
        item["phone_usage_fmt"] = format_duration(p_sec)
        item["phone_clip_url"] = ph.get("clip_url")

    return summary