File size: 47,361 Bytes
ecbed39
 
 
 
 
 
1b40c1e
 
 
 
ecbed39
67e0289
1b40c1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92277f1
26a0821
92277f1
 
 
 
26a0821
92277f1
 
 
1b40c1e
26a0821
 
1b40c1e
 
 
 
 
92277f1
1b40c1e
 
92277f1
1b40c1e
 
 
 
92277f1
1b40c1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9646da0
1b40c1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
033fa0f
1b40c1e
 
 
 
 
 
 
 
ecbed39
 
 
 
1b40c1e
ecbed39
 
 
 
1b40c1e
ecbed39
1b40c1e
ecbed39
 
 
1b40c1e
 
 
 
 
 
 
 
ecbed39
f7d5782
0a27d28
1b40c1e
 
 
f7d5782
1b40c1e
 
 
 
f7d5782
1b40c1e
 
 
 
f7d5782
1b40c1e
 
 
 
 
 
 
 
 
 
 
 
 
25feff5
1b40c1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f7d5782
ecbed39
1b40c1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f7d5782
1b40c1e
 
 
 
 
 
 
 
 
 
 
f7d5782
1b40c1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26a0821
1b40c1e
26a0821
 
 
 
 
 
 
 
1b40c1e
26a0821
1b40c1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25feff5
f7d5782
 
92277f1
 
 
 
f7d5782
1b40c1e
 
 
 
f7d5782
1b40c1e
f7d5782
1b40c1e
 
 
 
 
 
 
 
 
ecbed39
1b40c1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ecbed39
1b40c1e
 
 
 
 
 
ecbed39
1b40c1e
 
 
 
 
 
 
ecbed39
1b40c1e
 
 
92277f1
1b40c1e
26a0821
1b40c1e
 
ecbed39
1b40c1e
 
 
 
 
 
 
 
 
ecbed39
 
1b40c1e
92277f1
 
 
 
 
 
 
 
ecbed39
1b40c1e
 
 
 
 
 
ecbed39
 
1b40c1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ecbed39
1b40c1e
 
 
 
ecbed39
1b40c1e
 
 
 
 
 
ecbed39
1b40c1e
 
 
 
 
 
 
 
 
ecbed39
1b40c1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26a0821
 
23885ef
 
1b40c1e
 
 
26a0821
1b40c1e
26a0821
 
1b40c1e
23885ef
 
26a0821
23885ef
1b40c1e
26a0821
 
 
b5c62a9
23885ef
26a0821
 
1b40c1e
 
23885ef
26a0821
1b40c1e
92277f1
26a0821
 
 
23885ef
 
 
26a0821
 
 
23885ef
 
 
 
 
 
1b40c1e
 
 
 
23885ef
 
 
 
 
 
 
 
 
1b40c1e
 
23885ef
 
26a0821
23885ef
007cdff
92277f1
26a0821
b4d0b69
23885ef
26a0821
b4d0b69
 
26a0821
 
 
23885ef
26a0821
 
23885ef
26a0821
 
23885ef
 
 
 
 
 
 
26a0821
 
23885ef
26a0821
23885ef
26a0821
 
4f27f2d
26a0821
 
 
23885ef
 
 
 
 
 
 
 
 
 
 
1b40c1e
 
26a0821
 
23885ef
26a0821
 
 
 
 
 
1b40c1e
 
 
26a0821
 
1b40c1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ecbed39
1b40c1e
 
 
 
92277f1
1b40c1e
 
 
 
ecbed39
1b40c1e
 
 
 
 
ecbed39
1b40c1e
 
 
 
 
ecbed39
1b40c1e
 
92277f1
1b40c1e
 
 
 
ecbed39
1b40c1e
 
 
 
 
 
ecbed39
1b40c1e
ecbed39
 
1b40c1e
92277f1
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
import os, json, re, time, math, random, logging
import gradio as gr
from openai import OpenAI
from datetime import datetime, timedelta

# ==================== LOGGING ====================
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(message)s"
)
log = logging.getLogger(__name__)

# ==================== LLM CONFIG ====================
DEEPSEEK_API_KEY  = os.getenv("DEEPSEEK_API_KEY")
DEEPSEEK_BASE_URL = os.getenv("DEEPSEEK_BASE_URL", "https://api.deepseek.com/v1")
DEEPSEEK_MODEL    = os.getenv("DEEPSEEK_MODEL", "deepseek-chat")

OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
OPENAI_MODEL   = os.getenv("OPENAI_MODEL", "gpt-4o-mini")

# ==================== GOOGLE SHEETS / DOC CONFIG ====================
SVC_JSON      = os.getenv("GOOGLE_SERVICE_ACCOUNT_JSON")
SHEET_ID      = os.getenv("SHEETS_SPREADSHEET_ID")
MASTER_DOC_ID = "1IW_XsQsR3AIHpaxY3tJZuEujClC_KIHb0QeYhKLYbUM"

# ==================== RATE LIMITING ====================
# Simple in-memory per-session rate limit: max N LLM calls per rolling window
_rate_store: dict[str, list[float]] = {}
RATE_LIMIT_CALLS = 20       # max calls
RATE_LIMIT_WINDOW = 3600    # per hour (seconds)

def _check_rate_limit(key: str) -> bool:
    """Returns True if allowed, False if rate-limited."""
    now = time.time()
    window_start = now - RATE_LIMIT_WINDOW
    calls = [t for t in _rate_store.get(key, []) if t > window_start]
    if len(calls) >= RATE_LIMIT_CALLS:
        log.warning(f"Rate limit hit for key={key}")
        return False
    calls.append(now)
    _rate_store[key] = calls
    return True

# ==================== PASSAGE FILES ====================
# Check both root and passages/ subfolder so it works regardless of where files are uploaded
PASSAGE_DIR = "passages"

def is_class5(klass: str) -> bool:
    """Return True if the student's class string indicates Class 5 (e.g. '5', '5A', '5B', '5a')."""
    return str(klass).strip().startswith("5")

def load_passage(n: int, klass: str = "") -> str | None:
    if is_class5(klass):
        # Class 5 uses separate passage files: pssgs1class5.txt, pssgs2class5.txt, ...
        fname = f"pssg{n}class5.txt"
    else:
        fname = f"pssg{n}.txt"
    candidates = [
        fname,                              # root of repo
        os.path.join(PASSAGE_DIR, fname),  # passages/ subfolder
    ]
    for path in candidates:
        if os.path.exists(path):
            with open(path, "r", encoding="utf-8") as f:
                return f.read().strip()
    log.info(f"Passage file not found in root or passages/: {fname}")
    return None

def passages_for_level(level: int, klass: str = "") -> list[str]:
    """Count = level + 1, minimum 1."""
    count = max(1, level + 1)
    result = []
    for i in range(1, count + 1):
        p = load_passage(i, klass)
        if p:
            result.append(p)
    return result

def extract_english_only(passage_text: str) -> str:
    """
    Passages have English first, then Bengali below.
    We split on the first Bengali character to extract only English lines.
    """
    lines = passage_text.splitlines()
    english_lines = []
    for line in lines:
        # Stop at first line containing Bengali Unicode range (0x0980-0x09FF)
        if re.search(r'[\u0980-\u09FF]', line):
            break
        english_lines.append(line)
    return "\n".join(english_lines).strip()

# ==================== SVC JSON VALIDATION ====================
def validate_svc_json(raw: str) -> dict:
    """Parse and validate service account JSON structure before use."""
    try:
        data = json.loads(raw)
    except Exception as e:
        raise ValueError(f"GOOGLE_SERVICE_ACCOUNT_JSON is not valid JSON: {e}")
    required_keys = {"type", "project_id", "private_key_id", "private_key", "client_email"}
    missing = required_keys - set(data.keys())
    if missing:
        raise ValueError(f"Service account JSON missing keys: {missing}")
    if data.get("type") != "service_account":
        raise ValueError("Service account JSON 'type' must be 'service_account'")
    return data

def get_svc_creds(scopes: list[str]):
    from google.oauth2.service_account import Credentials
    svc_data = validate_svc_json(SVC_JSON)
    return Credentials.from_service_account_info(svc_data, scopes=scopes)

# ==================== PROMPTS (STANDARD) ====================
RUBRIC_USER_TEXT = """
You are a teacher grading a student's summary.
Step 0: Quality Check.
- Check if the text is "nonsensical" (random arbitrary words, or same sentence repeated).
- If nonsense/repetitive, set "is_nonsense": true; otherwise false.

Step 1: Decide if you KNOW the story.
- If you know it, set "knows_story": true; else false.

Step 2: Scoring.
- If knows_story=true, grade:
  1) Comprehension (1-5)
  2) Expression (1-5)
  3) Reflection/Moral Takeaway (1-5)
  4) Grammar (lenient): identify grammar/spelling/punctuation issues.
- If knows_story=false, set Comprehension to null and still do Expression, Reflection, Grammar.

Grammar issue format: for each issue provide
- "error_excerpt" (short snippet โ‰ค120 chars),
- "correction" (corrected snippet only),
- "explanation" (one short reason),
- "start_index" (0-based char position in ORIGINAL text),
- "end_index" (exclusive char position).

IMPORTANT for start_index/end_index: count characters carefully from the start of the
ORIGINAL text. Verify the excerpt actually appears at those positions.

Also provide "corrected_summary" (light edits only) and "remarks" (1-2 sentences).
"""

JSON_SCHEMA_HINT = """
Return ONLY raw JSON (no markdown fences, no extra text), exactly this structure:
{
  "is_nonsense": true,
  "knows_story": true,
  "scores": {
    "Comprehension": 3,
    "Expression": 4,
    "Reflection/Moral Takeaway": 3
  },
  "grammar_issues": [
    {
      "error_excerpt": "he go to school",
      "correction": "he goes to school",
      "explanation": "Subject-verb agreement",
      "start_index": 12,
      "end_index": 27
    }
  ],
  "corrected_summary": "...",
  "remarks": "..."
}
Rules:
- Comprehension must be null (not a string) if knows_story is false.
- grammar_issues must be [] if none found.
- All numeric scores must be plain integers, not strings.
- No trailing commas anywhere.
"""

# ==================== PASSAGE GRADING PROMPT ====================
def passage_grading_prompt(original_english: str, student_text: str) -> str:
    return f"""
You are grading a student's attempt to reproduce an English passage from memory.

ORIGINAL PASSAGE (English only):
\"\"\"
{original_english}
\"\"\"

STUDENT'S ATTEMPT:
\"\"\"
{student_text}
\"\"\"

Instructions:
- Compare word by word. COMPLETELY IGNORE capitalisation and spacing differences.
- IGNORE minor punctuation differences (missing comma, full stop).
- Score 1 to 5:
  5 = perfect or near-perfect (only trivial differences)
  4 = mostly correct, 1-2 wrong/missing words per sentence
  3 = roughly half the content correct, some sentences missing or wrong
  2 = significant errors, most words wrong or missing
  1 = barely matches, only a few words in common
- is_nonsense = true ONLY if the text is random gibberish or mindless repetition of
  the same word/phrase (NOT just a bad copy โ€” bad copies get score 1 or 2).

Return ONLY raw JSON, no markdown, no extra text:
{{
  "score": 3,
  "is_nonsense": false,
  "remarks": "One or two sentences of specific feedback."
}}
"""

# ==================== HELPERS ====================
def is_nonsense_heuristic(text: str) -> tuple[bool, str]:
    """
    Multi-signal nonsense detector. Returns (is_bad, reason).
    Checks:
    1. Unique word ratio (weak signal, used with other checks)
    2. Bigram repetition (catches 'cat dog cat dog')
    3. Single repeated token
    4. Ratio of unique bigrams to total bigrams
    """
    words = re.findall(r"\b\w+\b", text.lower())
    if len(words) < 5:
        return False, ""

    # Check 1: single word repeated almost exclusively
    from collections import Counter
    word_counts = Counter(words)
    most_common_word, most_common_count = word_counts.most_common(1)[0]
    if most_common_count / len(words) > 0.5:
        return True, f"Word '{most_common_word}' repeated {most_common_count} times."

    # Check 2: bigram repetition ratio
    bigrams = list(zip(words, words[1:]))
    if bigrams:
        unique_bigrams = set(bigrams)
        bigram_ratio = len(unique_bigrams) / len(bigrams)
        if bigram_ratio < 0.25 and len(words) > 15:
            return True, f"Highly repetitive bigram pattern detected."

    # Check 3: overall unique word ratio (only flag if very low AND many words)
    unique_ratio = len(set(words)) / len(words)
    if unique_ratio < 0.20 and len(words) > 20:
        return True, f"Only {round(unique_ratio*100)}% unique words."

    return False, ""

def student_key(name: str, klass: str) -> str:
    first = str(name).strip().split()[0].lower()
    return f"{first}_{str(klass).strip().lower()}"

def week_bounds(d):
    sunday = d - timedelta(days=(d.weekday() + 1) % 7)
    saturday = sunday + timedelta(days=6)
    return sunday, saturday

def _retry_delays(n: int):
    base = 0.6
    for i in range(n):
        yield base * (2 ** i) * (0.8 + 0.4 * random.random())

def call_openai_compatible(api_key, base_url, model, messages, tries=3):
    last_err = None
    client = OpenAI(api_key=api_key, base_url=base_url) if base_url else OpenAI(api_key=api_key)
    for delay in list(_retry_delays(tries)) + [0]:
        try:
            resp = client.chat.completions.create(model=model, messages=messages)
            return resp.choices[0].message.content, f"{'DeepSeek' if 'deepseek' in (base_url or '') else 'OpenAI'} ({model})"
        except Exception as e:
            last_err = e
            log.warning(f"LLM call failed (will retry): {e}")
            if delay > 0:
                time.sleep(delay)
    raise RuntimeError(f"LLM failed after {tries} attempts: {last_err}")

def llm_chat(messages, rate_key: str = "global"):
    if not _check_rate_limit(rate_key):
        raise RuntimeError("โš ๏ธ Too many requests. Please wait a few minutes before trying again.")
    if DEEPSEEK_API_KEY:
        try:
            return call_openai_compatible(DEEPSEEK_API_KEY, DEEPSEEK_BASE_URL, DEEPSEEK_MODEL, messages, 3)
        except Exception as e:
            ds_err = str(e)
            log.error(f"DeepSeek failed: {ds_err}")
    else:
        ds_err = "DeepSeek key not set."
    if OPENAI_API_KEY:
        try:
            return call_openai_compatible(OPENAI_API_KEY, None, OPENAI_MODEL, messages, 2)
        except Exception as e:
            oe = str(e)
            log.error(f"OpenAI fallback failed: {oe}")
            raise RuntimeError(f"DeepSeek: {ds_err}\nOpenAI: {oe}")
    raise RuntimeError(f"{ds_err}\nNo OpenAI fallback configured.")

def salvage_json(s: str) -> dict:
    """Robust JSON parser โ€” handles markdown fences, trailing commas, smart quotes."""
    s = s.strip()
    # Strip markdown fences
    s = re.sub(r"^\s*```(?:json)?\s*", "", s)
    s = re.sub(r"\s*```\s*$", "", s)
    # Fix smart quotes
    s = s.replace("\u201c", '"').replace("\u201d", '"').replace("\u2019", "'").replace("\u2018", "'")
    # Extract outermost JSON object
    m = re.search(r"\{.*\}\s*$", s, flags=re.S)
    if m:
        s = m.group(0)
    # Fix trailing commas before } or ]
    s = re.sub(r",\s*([}\]])", r"\1", s)
    # Fix missing values for index fields (LLM sometimes omits them)
    s = re.sub(r'"end_index"\s*:\s*(?=(,|\}))', '"end_index": 0', s)
    s = re.sub(r'"start_index"\s*:\s*(?=(,|\}))', '"start_index": 0', s)

    data = json.loads(s)  # will raise if still invalid โ€” caller handles

    # Sanitise grammar_issues
    issues = data.get("grammar_issues", [])
    safe_issues = []
    if isinstance(issues, list):
        for it in issues:
            if not isinstance(it, dict):
                continue
            try: si = int(it.get("start_index", 0))
            except: si = 0
            try: ei = int(it.get("end_index", 0))
            except: ei = 0
            safe_issues.append({
                "error_excerpt": str(it.get("error_excerpt", ""))[:200],
                "correction":    str(it.get("correction",    ""))[:200],
                "explanation":   str(it.get("explanation",   ""))[:200],
                "start_index":   si,
                "end_index":     ei,
            })
    data["grammar_issues"] = safe_issues
    return data

def salvage_passage_json(s: str) -> dict:
    """salvage_json variant for the simpler passage-grading response."""
    s = s.strip()
    s = re.sub(r"^\s*```(?:json)?\s*", "", s)
    s = re.sub(r"\s*```\s*$", "", s)
    s = s.replace("\u201c", '"').replace("\u201d", '"').replace("\u2019", "'")
    m = re.search(r"\{.*\}\s*$", s, flags=re.S)
    if m:
        s = m.group(0)
    s = re.sub(r",\s*([}\]])", r"\1", s)
    data = json.loads(s)
    # Ensure required keys have sane defaults
    data.setdefault("score", 1)
    data.setdefault("is_nonsense", False)
    data.setdefault("remarks", "")
    try:
        data["score"] = max(1.0, min(5.0, float(data["score"])))
    except Exception:
        log.warning(f"Could not parse score from passage JSON, defaulting to 1")
        data["score"] = 1.0
    return data

def stars_bar(value, max_stars: int = 5) -> str:
    if value is None:
        return "โ€”"
    try:
        v = float(value)
    except Exception:
        return "โ€”"
    if v <= 0:
        return "โ€”"
    n_int = max(0, min(max_stars, int(round(v))))
    return "โญ" * n_int

def count_words(text: str) -> int:
    return len(re.findall(r"\b\w[\w'-]*\b", text))

def length_stars(word_count: int) -> int:
    if word_count < 100: return 0
    if word_count <= 150: return 1
    if word_count <= 200: return 3
    if word_count <= 250: return 4
    return 5

def clamp_1_to_5(x) -> int:
    try:
        return max(1, min(5, int(x)))
    except Exception:
        return 1

def grammar_stars_from_count(n: int) -> float:
    if n >= 50: return 0.0
    return max(0.0, 5.0 - 0.1 * n)

def annotate_original_with_issues(text: str, issues: list) -> str:
    """
    Annotate text with grammar issues.
    Falls back gracefully if LLM indices are wrong โ€” uses fuzzy search.
    """
    valid = []
    for i, it in enumerate(issues, 1):
        si, ei = int(it.get("start_index", 0)), int(it.get("end_index", 0))
        excerpt = it.get("error_excerpt", "")

        # Validate LLM-provided indices
        if 0 <= si < ei <= len(text) and text[si:ei].lower() == excerpt[:ei-si].lower():
            valid.append((si, ei, i))
        elif excerpt:
            # Fuzzy fallback: find excerpt in text
            idx = text.lower().find(excerpt.lower())
            if idx != -1:
                valid.append((idx, idx + len(excerpt), i))
            else:
                log.info(f"Grammar issue #{i}: could not locate excerpt '{excerpt[:30]}' in text โ€” skipping annotation")
                # Still list in table below, just skip inline annotation
        # else: skip silently

    valid.sort(key=lambda x: x[0])
    out, cursor, last_end = [], 0, -1
    for si, ei, idx in valid:
        if si < last_end:
            continue
        out.append(text[cursor:si])
        out.append(f"[[#{idx}: {text[si:ei]}]]")
        cursor, last_end = ei, ei
    out.append(text[cursor:])
    return "".join(out)

def now_ist() -> datetime:
    return datetime.utcnow() + timedelta(hours=5, minutes=30)

# ==================== GOOGLE SHEETS ====================
def get_gspread_ws():
    import gspread
    creds = get_svc_creds(["https://www.googleapis.com/auth/spreadsheets"])
    gc = gspread.authorize(creds)
    sh = gc.open_by_key(SHEET_ID)
    return sh.worksheet("Scores")

def get_student_level(name: str, klass: str, mode: str) -> int:
    """Fetch persisted level from Sheets. Returns 2 on any failure."""
    if not SVC_JSON:
        log.info("SVC_JSON not set โ€” using default level 2")
        return 2
    try:
        ws = get_gspread_ws()
        records = ws.get_all_records()
        key = student_key(name, klass)
        best_level = 2
        best_ts = None
        for r in records:
            mode_col = str(r.get("Mode", "") or r.get("Summary", "") or "")
            if mode.lower() not in mode_col.lower():
                continue
            try:
                rkey = student_key(str(r.get("Name", "")), str(r.get("Classs") or r.get("Class", "")))
            except Exception:
                continue
            if rkey != key:
                continue
            m = re.search(r'-(\d+)-', mode_col)
            if m:
                try:
                    ts_str = str(r.get("Date") or r.get("Timestamp", ""))
                    ts = datetime.strptime(ts_str, "%Y-%m-%d %H:%M:%S")
                    if best_ts is None or ts > best_ts:
                        best_ts = ts
                        best_level = int(m.group(1))
                except Exception as parse_err:
                    log.debug(f"Level parse error for row {r}: {parse_err}")
        log.info(f"Loaded level={best_level} for {key} mode={mode}")
        return best_level
    except Exception as e:
        log.error(f"get_student_level failed: {e}")
        return 2

def append_to_sheet(row: list, student_name: str, student_class: str, avg: float, mode_label: str) -> str:
    """
    Append best score. Instead of deleting old row (risky), we ADD a new row and mark
    the old one as superseded by prepending 'OLD|' to its Mode column.
    This preserves audit trail while still allowing best-score logic.
    """
    if not SVC_JSON:
        return "โš ๏ธ Sheets not configured (GOOGLE_SERVICE_ACCOUNT_JSON missing)."
    try:
        ws = get_gspread_ws()
        records = ws.get_all_records()
        today = now_ist().date()
        sun, sat = week_bounds(today)
        key = student_key(student_name, student_class)
        mode_prefix = mode_label.split("-")[0]

        # Find this week's best for same student+mode
        best_row_idx = None
        best_score = -999.0
        for i, r in enumerate(records, start=2):
            try:
                ts_str = str(r.get("Date") or r.get("Timestamp", ""))
                ts = datetime.strptime(ts_str, "%Y-%m-%d %H:%M:%S").date()
                mode_col = str(r.get("Mode", "") or r.get("Summary", "") or "")
                # Skip already-superseded rows
                if mode_col.startswith("OLD|"):
                    continue
                rkey = student_key(str(r.get("Name", "")), str(r.get("Classs") or r.get("Class", "")))
                if sun <= ts <= sat and rkey == key and mode_prefix in mode_col:
                    prev = float(r.get("Star") or r.get("Result") or 0)
                    if prev > best_score:
                        best_score = prev
                        best_row_idx = i
            except Exception as row_err:
                log.debug(f"Sheet row {i} parse error: {row_err}")
                continue

        if best_row_idx is not None and avg <= best_score:
            log.info(f"Not saving: existing best={best_score} >= new={avg}")
            return f"โš ๏ธ A better score ({best_score:.2f}) already exists this week. Not saved."

        # Mark old row as superseded (audit trail preserved)
        if best_row_idx is not None:
            try:
                # Find the Mode/Summary column index (1-based)
                headers = ws.row_values(1)
                mode_col_idx = None
                for ci, h in enumerate(headers, start=1):
                    if h in ("Mode", "Summary"):
                        mode_col_idx = ci
                        break
                if mode_col_idx:
                    old_val = ws.cell(best_row_idx, mode_col_idx).value or ""
                    ws.update_cell(best_row_idx, mode_col_idx, f"OLD|{old_val}")
                    log.info(f"Marked row {best_row_idx} as OLD")
            except Exception as mark_err:
                log.warning(f"Could not mark old row: {mark_err}")

        ws.append_row(row, value_input_option="USER_ENTERED")
        log.info(f"Appended new row for {key} mode={mode_label} score={avg}")
        return "โœ… Score saved to Google Sheets!"
    except Exception as e:
        log.error(f"append_to_sheet failed: {e}")
        return f"โŒ Sheets error: {e}"

def save_to_master_doc(name: str, klass: str, title: str, summary: str) -> str:
    try:
        from googleapiclient.discovery import build
        creds = get_svc_creds([
            "https://www.googleapis.com/auth/documents",
            "https://www.googleapis.com/auth/drive"
        ])
        service = build('docs', 'v1', credentials=creds)
        timestamp = now_ist().strftime('%Y-%m-%d %H:%M:%S')
        new_entry = (
            f"\n\n### START_ENTRY ###\n"
            f"[[METADATA|NAME:{name.strip()}|CLASS:{klass.strip()}|DATE:{timestamp}|TITLE:{title.strip()}]]\n"
            f"--- ESSAY START ---\n{summary.strip()}\n--- ESSAY END ---\n"
            f"### END_ENTRY ###\n"
        )
        doc = service.documents().get(documentId=MASTER_DOC_ID).execute()
        end_index = doc['body']['content'][-1]['endIndex'] - 1
        service.documents().batchUpdate(
            documentId=MASTER_DOC_ID,
            body={'requests': [{'insertText': {'location': {'index': end_index}, 'text': new_entry}}]}
        ).execute()
        log.info(f"Saved to master doc: {name} / {title}")
        return "โœ… Saved to Master Doc"
    except Exception as e:
        log.error(f"save_to_master_doc failed: {e}")
        return f"โŒ Doc Error: {e}"

# ==================== SCORING RULES ====================
# MODERATE: max=7 at level 2. Level up if >=5 stars. Level down if <3. Stay for 3-4.
# For levels above 2: max = 7 + (level-2)*1.2*5  (bonus on top of base 7)
# For levels below 2: max stays 7 (no reduction)
# EASY: max=5 at all levels. Level up if >=4. Level down if <=3.

def compute_max_stars_moderate(level: int) -> float:
    base = 7.0
    if level <= 2:
        return base
    return base + (level - 2) * 1.2 * 5.0

def compute_max_stars_easy(level: int) -> float:
    return 5.0  # fixed max for easy mode

def level_change_moderate(raw_score: float, current_level: int) -> int:
    """Returns new level based on raw 1-5 LLM score."""
    # raw_score is on 1-5 scale from LLM
    # We need to translate to "stars out of max" for threshold check
    # Level up: raw >= 5 (out of 7, that's ~5/7 * max)
    # Level thresholds are applied on raw_score directly since LLM scores 1-5
    if raw_score >= 5:
        return current_level + 1
    elif raw_score < 3:
        return max(0, current_level - 1)
    return current_level  # 3 or 4 โ†’ stay

def level_change_easy(raw_score: float, current_level: int) -> int:
    """Easy mode: up if >=4, down if <=3."""
    if raw_score >= 4:
        return current_level + 1
    elif raw_score <= 3:
        return max(0, current_level - 1)
    return current_level

# ==================== RULES TEXT ====================
STANDARD_RULES = """
## ๐Ÿ“‹ Standard Mode โ€” Full Rules

Write a **summary** of a story or book you have read. The app will grade it automatically.

### How it's marked
Each category is scored out of 5, then **multiplied by 5** โ†’ maximum **25 โญ**

| Category | What we look for |
|---|---|
| ๐Ÿ“– Comprehension | Did you understand the story correctly? |
| โœ๏ธ Expression | Is your writing clear, fluent and well-organised? |
| ๐Ÿ’ก Reflection / Moral | Did you capture the lesson or moral of the story? |
| ๐Ÿ“ Length | Min 100 words needed. 250+ words = full marks. |
| โœ… Grammar | Fewer mistakes = more stars. |

> **Note:** If the AI doesn't recognise the story, Comprehension is skipped and the average is over 4 categories instead of 5.

### โš ๏ธ Penalties & Rules
- Writing **gibberish or repeating the same words** โ†’ **โˆ’1 โญ**
- **Copy-paste is disabled** โ€” you must type manually
- After grading you'll see a **corrected version** of your summary
- You can **redo as many times as you like** โ€” only your **best score** is saved
"""

MODERATE_RULES = """
## ๐Ÿ“‹ Moderate Mode โ€” Full Rules

You'll see **English passages** with Bengali translations below each one.
Read them, then **the passage disappears after a time limit** โ€” type it back from memory!

### โฑ๏ธ Timer
| Level | Passage visible for |
|---|---|
| Level 0 | 1 minute |
| Level 1 | 2 minutes |
| Level 2 | 3 minutes |
| Level 3 | 4 minutes |
| Level N | (N+1) minutes |

After time is up the passage is **hidden** โ€” type what you remember!

### Scoring
| LLM Score | Meaning |
|---|---|
| 5/5 | Perfect or near-perfect reproduction |
| 4/5 | Mostly correct, 1-2 minor word differences per sentence |
| 3/5 | About half correct, some sentences missing or wrong |
| 2/5 | Significant errors, most words wrong |
| 1/5 | Barely matches |

### ๐ŸŽฎ Level System
- Your level is **saved across sessions** (starts at Level 2 for new students)
- **Passages shown = level + 1** (Level 2 โ†’ 3 passages, Level 3 โ†’ 4 passages, etc.)
- **Max stars at Level 2 = 7 โญ** (base)
- **Above Level 2:** max = 7 + (levelโˆ’2) ร— 1.2 ร— 5
- **Level 2 or below:** max stays at 7

### ๐Ÿ”ผ Level Changes (after each attempt)
| Your score | Result |
|---|---|
| LLM gives 5/5 | Level UP โ†‘ |
| LLM gives 3 or 4 out of 5 | Stay same level |
| LLM gives below 3/5 | Level DOWN โ†“ |

### โš ๏ธ Rules
- Capitalisation and spacing **do not matter** โ€” the app ignores them
- Gibberish or mindless repetition โ†’ **โˆ’1 โญ**
- **Copy-paste is disabled**
"""

EASY_RULES = """
## ๐Ÿ“‹ Easy Mode โ€” Full Rules

You'll see **English passages** with Bengali translations below each one.
The passage **stays visible** the whole time โ€” just read and type it back accurately!

### Scoring (max = 5 โญ at all levels)
| LLM Score | Meaning |
|---|---|
| 5/5 | Perfect or near-perfect reproduction |
| 4/5 | Mostly correct, 1-2 minor word differences per sentence |
| 3/5 | About half correct, some sentences missing or wrong |
| 2/5 | Significant errors, most words wrong |
| 1/5 | Barely matches |

### ๐ŸŽฎ Level System
- Your level is **saved across sessions** (starts at Level 2 for new students)
- **Passages shown = level + 1**

### ๐Ÿ”ผ Level Changes
| Your score | Result |
|---|---|
| LLM gives 4 or 5 out of 5 | Level UP โ†‘ |
| LLM gives 3 or below | Level DOWN โ†“ |

### โš ๏ธ Rules
- Capitalisation and spacing **do not matter**
- Gibberish or mindless repetition โ†’ **โˆ’1 โญ**
- **Copy-paste is disabled**
"""

# ==================== STANDARD MODE GRADING ====================
def intro_message_standard(name: str, klass: str) -> str:
    if not name.strip() or not klass.strip():
        return "๐Ÿ‘‹ Please enter your name and class first!"
    return f"### ๐ŸŒŸ Hi {name} of {klass}!\n\nYou're in **Standard Mode**. Read the rules above and write your summary below. Good luck!"

def grade_standard(student_name: str, student_class: str, title: str, student_summary: str):
    try:
        if not all([student_name.strip(), student_class.strip(), title.strip(), student_summary.strip()]):
            return "โš ๏ธ Please fill in all fields.", "", ""
            
        wc = count_words(student_summary)
        if wc < 100:
            return f"โš ๏ธ You wrote {wc} words. Please write at least 100 words.", "", ""

        rate_key = student_key(student_name, student_class)
        prompt = f"TITLE: {title}\nSUMMARY: {student_summary}\n{RUBRIC_USER_TEXT}\n{JSON_SCHEMA_HINT}"
        content, model_used = llm_chat([{"role": "user", "content": prompt}], rate_key=rate_key)
        log.info(f"Standard grade: {student_name} / {title} โ€” model={model_used}")

        data = salvage_json(content)

        is_nonsense_ai  = bool(data.get("is_nonsense", False))
        knows_story     = bool(data.get("knows_story", False))
        scores          = data.get("scores", {}) or {}
        comp            = scores.get("Comprehension", None)
        expr            = clamp_1_to_5(scores.get("Expression", 1))
        refl            = clamp_1_to_5(scores.get("Reflection/Moral Takeaway", 1))
        issues          = data.get("grammar_issues", [])
        corrected       = (data.get("corrected_summary") or "").strip()
        remarks         = (data.get("remarks") or "").strip()

        wc           = count_words(student_summary)
        len_s        = length_stars(wc)
        grammar_star = round(grammar_stars_from_count(len(issues)), 1)

        # Heuristic nonsense check (multi-signal)
        heuristic_bad, heuristic_reason = is_nonsense_heuristic(student_summary)

        reasons = []
        if is_nonsense_ai:
            reasons.append("AI flagged this as nonsense or gibberish.")
        if heuristic_bad:
            reasons.append(heuristic_reason)

        is_failing = len(reasons) > 0
        if is_failing:
            final_score  = -1.0
            display_stars = 0
        else:
            vals = [float(expr), float(refl), float(len_s), float(grammar_star)]
            if knows_story and comp is not None:
                vals.append(float(comp))
            raw_avg     = round(sum(vals) / len(vals), 2) if vals else 0.0
            final_score = round(raw_avg * 5, 2)           # multiply by 5 โ†’ max 25
            final_score = max(0.0, final_score)
            display_stars = min(25, int(round(final_score)))  # capped at 25

        md = ["### ๐Ÿ“š Standard Mode โ€” Grading Report"]
        if is_failing:
            md.append("> ## โŒ FINAL SCORE: โˆ’1 โญ")
            md.append("> **Reason:** " + " | ".join(reasons))
        else:
            md.append(f"\n**๐Ÿ† FINAL SCORE: {final_score:.1f} / 25**")
            md.append("โญ" * display_stars)

        md.append(f"\n**Name:** {student_name} &nbsp;&nbsp; **Class:** {student_class}")
        md.append(f"**Title:** {title} &nbsp;&nbsp; **Words:** {wc}")
        md.append("\n#### Category Scores (each out of 5)")
        if knows_story:
            md.append(f"- ๐Ÿ“– Comprehension: {stars_bar(comp)}")
        else:
            md.append(f"- ๐Ÿ“– Comprehension: โ€” *(story not recognised by AI)*")
        md.append(f"- โœ๏ธ Expression: {stars_bar(expr)}")
        md.append(f"- ๐Ÿ’ก Reflection: {stars_bar(refl)}")
        md.append(f"- ๐Ÿ“ Length ({wc} words): {stars_bar(len_s)}")
        md.append(f"- โœ… Grammar ({len(issues)} issues): {stars_bar(grammar_star)}")
        if remarks:
            md.append(f"\n> ๐Ÿ’ฌ **Remarks:** {remarks}")

        if issues:
            md.append(f"\n#### ๐Ÿ”Ž Annotated Text\n```\n{annotate_original_with_issues(student_summary, issues)}\n```")
            md.append("\n#### ๐Ÿ“ Grammar Issues")
            for i, it in enumerate(issues, 1):
                md.append(f"{i}. โŒ `{it['error_excerpt']}` โ†’ โœ… `{it['correction']}` โ€” *{it['explanation']}*")

        timestamp  = now_ist().strftime("%Y-%m-%d %H:%M:%S")
        mode_label = "standard-2-summary"
        pct        = round(final_score / 25 * 100, 1) if final_score >= 0 else 0
        row = [timestamp, student_name, student_class, round(final_score, 2), "25", f"{pct}%", round(final_score, 2), mode_label]
        sheets_status = append_to_sheet(row, student_name, student_class, final_score, mode_label)
        doc_status    = save_to_master_doc(student_name, student_class, title, student_summary)

        return "\n".join(md), corrected, f"{sheets_status} | {doc_status}"
    except Exception as e:
        log.error(f"grade_standard error: {e}", exc_info=True)
        return f"### โŒ Error\n{e}", "", "Not saved."

# ==================== PASSAGE MODE GRADING ====================
def grade_passage_mode(student_name: str, student_class: str, student_text: str, level: int, mode: str):
    try:
        if not all([student_name.strip(), student_class.strip(), student_text.strip()]):
            return "โš ๏ธ Please fill in all fields.", level, ""

        passages = passages_for_level(level, student_class)
        if not passages:
            return "โš ๏ธ No passages found. Please upload passage files to the root of your HF repo (same folder as app.py).", level, ""
        english_only_passages = [extract_english_only(p) for p in passages]
        combined_english = "\n\n".join(english_only_passages)

        rate_key = student_key(student_name, student_class)
        prompt   = passage_grading_prompt(combined_english, student_text)
        content, model_used = llm_chat([{"role": "user", "content": prompt}], rate_key=rate_key)
        log.info(f"Passage grade: {student_name} level={level} mode={mode} model={model_used}")

        data      = salvage_passage_json(content)   # robust parsing
        raw_score = float(data.get("score", 1))
        is_nonsense_ai = bool(data.get("is_nonsense", False))
        remarks   = str(data.get("remarks", "")).strip()

        heuristic_bad, heuristic_reason = is_nonsense_heuristic(student_text)
        is_failing = is_nonsense_ai or heuristic_bad
        
        # Relevance check: if answer does not resemble passage at all
        if not is_nonsense_ai and not heuristic_bad and raw_score <= 1:
            return (
                    "โŒ Your answer does not match the passage at all. Please try to recall the actual passage.",
                        level,
                    ""
    )

        if mode == "moderate":
            max_stars  = compute_max_stars_moderate(level)
            new_level  = level_change_moderate(raw_score, level) if not is_failing else level
        else:  # easy
            max_stars  = compute_max_stars_easy(level)
            new_level  = level_change_easy(raw_score, level) if not is_failing else level

        if is_failing:
            final_score   = -1.0
            display_stars = 0
            fail_reason   = is_nonsense_ai and "AI flagged as gibberish." or heuristic_reason
        else:
            # Scale raw_score (1-5) to (0 - max_stars), floor at 0
            final_score   = max(0.0, round((raw_score / 5.0) * max_stars, 2))
            display_stars = min(int(max_stars) + 1, int(round(final_score)))  # capped at max_stars (not max+5)

        mode_title = "๐ŸŽฎ Moderate" if mode == "moderate" else "๐ŸŸข Easy"
        md = [f"### {mode_title} Mode โ€” Results (Level {level})"]
        if is_failing:
            md.append("> ## โŒ FINAL SCORE: โˆ’1 โญ")
            md.append(f"> **Reason:** {fail_reason if is_nonsense_ai else heuristic_reason}")
        else:
            md.append(f"\n**๐Ÿ† Score: {final_score:.1f} / {max_stars:.1f}**")
            md.append("โญ" * display_stars)
            md.append(f"\n*(LLM accuracy: {raw_score:.0f}/5)*")

        md.append(f"\n**Name:** {student_name} &nbsp;&nbsp; **Class:** {student_class}")
        md.append(f"**Level:** {level} &nbsp;&nbsp; **Passages used:** {len(passages)}")
        if remarks:
            md.append(f"\n> ๐Ÿ’ฌ {remarks}")

        if new_level > level:
            md.append(f"\n๐ŸŽ‰ **Level UP! {level} โ†’ {new_level}**")
        elif new_level < level:
            md.append(f"\n๐Ÿ“‰ **Level DOWN: {level} โ†’ {new_level}**")
        else:
            md.append(f"\nโžก๏ธ **Level stays at {level}**")

        timestamp  = now_ist().strftime("%Y-%m-%d %H:%M:%S")
        mode_label = f"{mode.lower()}-{new_level}-summary"   # save NEW level
        pct        = round(final_score / max_stars * 100, 1) if max_stars > 0 and final_score >= 0 else 0
        row = [timestamp, student_name, student_class, round(final_score, 2),
               str(round(max_stars, 1)), f"{pct}%", round(final_score, 2), mode_label]
        sheets_status = append_to_sheet(row, student_name, student_class, final_score, mode_label)
        doc_status    = save_to_master_doc(student_name, student_class, f"{mode}-level{level}", student_text)

        return "\n".join(md), new_level, f"{sheets_status} | {doc_status}"
    except Exception as e:
        log.error(f"grade_passage_mode error: {e}", exc_info=True)
        return f"### โŒ Error\n{e}", level, "Not saved."

# ==================== DISPLAY HELPERS ====================
def format_passages_display(passages: list[str]) -> str:
    if not passages:
        return "โš ๏ธ No passages loaded. Please upload pssg1.txt, pssg2.txt etc. to the root of your HF repo (same folder as app.py)."
    parts = []
    for i, p in enumerate(passages, 1):
        parts.append(f"### Passage {i}\n{p}")
    return "\n\n---\n\n".join(parts)

# ==================== JAVASCRIPT ====================
block_paste_js = """
function() {
    function blockPaste(id) {
        const el = document.querySelector(id + " textarea");
        if (el) {
            el.addEventListener('paste', function(e) {
                e.preventDefault();
                alert("โš ๏ธ Copy-pasting is disabled. Please type manually!");
            });
        }
    }
    blockPaste("#std-summary-input");
    blockPaste("#mod-answer-input");
    blockPaste("#easy-answer-input");
}
"""

# ==================== GRADIO UI ====================
with gr.Blocks(title="Summary & Passage Grader", theme=gr.themes.Soft()) as demo:
    gr.Markdown("# ๐Ÿ“ Summary & Passage Grader")
    gr.Markdown("Select a mode below. Read the rules carefully before you start!")

    with gr.Tabs():

        # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
        #  STANDARD MODE
        # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
        with gr.Tab("๐Ÿ“š Standard Mode"):
            gr.Markdown(STANDARD_RULES)
            with gr.Row():
                std_name  = gr.Textbox(label="Student Name", placeholder="Your full name")
                std_class = gr.Textbox(label="Class",        placeholder="e.g. 5A")
            std_intro_btn = gr.Button("๐Ÿ‘‹ Show Personalised Welcome")
            std_intro_out = gr.Markdown()
            std_intro_btn.click(fn=intro_message_standard, inputs=[std_name, std_class], outputs=std_intro_out)

            std_title   = gr.Textbox(label="Book / Story Title")
            std_summary = gr.Textbox(label="Your Summary (type manually โ€” no copy-paste!)",
                                     lines=10, elem_id="std-summary-input")

            std_grade_btn = gr.Button("โœ… Grade My Summary", variant="primary")
            std_report    = gr.Markdown()
            std_corrected = gr.Textbox(label="๐Ÿ“ Corrected Summary (edit if you like, then click Redo)",
                                       lines=8)
            std_status    = gr.Markdown()
            std_redo_btn  = gr.Button("๐Ÿ”„ Redo with Corrected Text", variant="secondary")

            std_grade_btn.click(
                fn=grade_standard,
                inputs=[std_name, std_class, std_title, std_summary],
                outputs=[std_report, std_corrected, std_status]
            )
            std_redo_btn.click(
                fn=lambda c: c,
                inputs=[std_corrected],
                outputs=[std_summary]
            )

        # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
        #  MODERATE MODE  (passage disappears after timer)
        # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
                # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
        #  MODERATE MODE โ€” AUTO DISAPPEAR (NO FLASH)
        # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
        with gr.Tab("๐ŸŽฎ Moderate Mode"):
            gr.Markdown(MODERATE_RULES)

            with gr.Row():
                mod_name  = gr.Textbox(label="Student Name")
                mod_class = gr.Textbox(label="Class")

            mod_level_state    = gr.State(value=2)
            mod_timer_state    = gr.State(value=0)
            mod_passages_state = gr.State(value=[])
            mod_last_state     = gr.State(value=[])

            mod_level_display    = gr.Markdown()
            mod_timer_display    = gr.Markdown()
            mod_passages_display = gr.Markdown()

            mod_load_btn = gr.Button("๐Ÿš€ Start (Passages auto-disappear)", variant="primary")

            # ================= LOAD =================
            def mod_load(name, klass):
                if not name.strip() or not klass.strip():
                    return "โš ๏ธ Enter name and class first.", "", "", 2, 0, [], []

                level    = get_student_level(name, klass, "moderate")
                passages = passages_for_level(level, klass)

                start_time = time.time()

                # initial state = all visible
                last_state = [1] * len(passages)

                level_md = f"### ๐ŸŽฎ Level: {level} | Passages: {len(passages)}"
                timer_md = "โฑ๏ธ Timer started. Passages will disappear automatically."

                # show all passages initially
                display = "\n\n---\n\n".join(
                    [f"### Passage {i+1}\n{p}" for i, p in enumerate(passages)]
                )

                return level_md, timer_md, display, level, start_time, passages, last_state

            mod_load_btn.click(
                fn=mod_load,
                inputs=[mod_name, mod_class],
                outputs=[
                    mod_level_display,
                    mod_timer_display,
                    mod_passages_display,
                    mod_level_state,
                    mod_timer_state,
                    mod_passages_state,
                    mod_last_state
                ]
            )

            # ================= TIMER UPDATE =================
            def update_passages(level, start_time, passages, last_state):
                if start_time == 0 or not passages:
                    return gr.update(), gr.update(), last_state

                now = time.time()
                elapsed = now - start_time

                current_state = []
                visible_parts = []

                for i, p in enumerate(passages):
                    hide_time = (i + 1) * 60

                    if elapsed < hide_time:
                        current_state.append(1)
                        visible_parts.append(f"### Passage {i+1}\n{p}")
                    else:
                        current_state.append(0)
                        visible_parts.append(f"### Passage {i+1}\n๐Ÿ™ˆ *Hidden*")

                # ๐Ÿ”ฅ Only update when something changes
                if current_state == last_state:
                    return gr.update(), gr.update(), last_state

                display = "\n\n---\n\n".join(visible_parts)

                if all(v == 0 for v in current_state):
                    timer_md = "โฐ All passages hidden! Type from memory."
                else:
                    timer_md = "โฑ๏ธ Passages disappearing..."

                return display, timer_md, current_state

            # ================= AUTO TIMER =================
            timer = gr.Timer(10)

            timer.tick(
                fn=update_passages,
                inputs=[
                    mod_level_state,
                    mod_timer_state,
                    mod_passages_state,
                    mod_last_state
                ],
                outputs=[
                    mod_passages_display,
                    mod_timer_display,
                    mod_last_state
                ]
            )

            # ================= ANSWER =================
            mod_answer     = gr.Textbox(label="โœ๏ธ Type from memory", lines=10)
            mod_submit_btn = gr.Button("โœ… Submit", variant="primary")

            mod_report = gr.Markdown()
            mod_status = gr.Markdown()

            def mod_grade(name, klass, answer, level):
                return grade_passage_mode(name, klass, answer, level, "moderate")

            mod_submit_btn.click(
                fn=mod_grade,
                inputs=[mod_name, mod_class, mod_answer, mod_level_state],
                outputs=[mod_report, mod_level_state, mod_status]
            )

        # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
        #  EASY MODE  (passage stays visible always)
        # โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
        with gr.Tab("๐ŸŸข Easy Mode"):
            gr.Markdown(EASY_RULES)
            with gr.Row():
                easy_name  = gr.Textbox(label="Student Name", placeholder="Your full name")
                easy_class = gr.Textbox(label="Class",        placeholder="e.g. 5A")

            easy_level_state = gr.State(value=2)

            easy_load_btn         = gr.Button("๐Ÿš€ Load My Level & Passages", variant="primary")
            easy_level_display    = gr.Markdown()
            easy_passages_display = gr.Markdown()

            def easy_load(name, klass):
                if not name.strip() or not klass.strip():
                    return "โš ๏ธ Enter name and class first.", "", 2
                level    = get_student_level(name, klass, "easy")
                passages = passages_for_level(level, klass)
                ptext    = format_passages_display(passages)
                level_md = (f"### ๐ŸŸข Your Level: **{level}** &nbsp;&nbsp; "
                            f"Passages: **{len(passages)}** &nbsp;&nbsp; Max stars: **5 โญ**")
                return level_md, ptext, level

            easy_load_btn.click(
                fn=easy_load,
                inputs=[easy_name, easy_class],
                outputs=[easy_level_display, easy_passages_display, easy_level_state]
            )

            easy_answer     = gr.Textbox(label="โœ๏ธ Type the English passage(s) here (no copy-paste!)",
                                         lines=10, elem_id="easy-answer-input")
            easy_submit_btn = gr.Button("โœ… Submit Answer", variant="primary")
            easy_report     = gr.Markdown()
            easy_status     = gr.Markdown()

            def easy_grade(name, klass, answer, level):
                report, new_level, status = grade_passage_mode(name, klass, answer, level, "easy")
                passages = passages_for_level(new_level, klass)
                ptext    = format_passages_display(passages)
                level_md = (f"### ๐ŸŸข Your Level: **{new_level}** &nbsp;&nbsp; "
                            f"Passages: **{len(passages)}** &nbsp;&nbsp; Max stars: **5 โญ**")
                return report, status, level_md, ptext, new_level

            easy_submit_btn.click(
                fn=easy_grade,
                inputs=[easy_name, easy_class, easy_answer, easy_level_state],
                outputs=[easy_report, easy_status, easy_level_display,
                         easy_passages_display, easy_level_state]
            )

    demo.load(None, None, None, js=block_paste_js)

if __name__ == "__main__":
    os.makedirs(PASSAGE_DIR, exist_ok=True)
    demo.launch()