File size: 36,124 Bytes
b478fa4
4b6c305
b478fa4
4b6c305
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b478fa4
 
 
 
b6e823c
b478fa4
 
b6e823c
b478fa4
 
3e45135
 
 
 
b478fa4
a7ecabb
4b6c305
b478fa4
 
e5a1d33
4b6c305
 
 
 
b478fa4
d57ae02
bcae715
b478fa4
 
 
dc2a7d2
b478fa4
 
 
 
 
 
 
feda791
 
4b6c305
3e45135
b478fa4
 
 
 
 
 
 
 
 
4b6c305
 
 
 
 
 
 
 
 
b6e823c
 
b478fa4
4b6c305
b478fa4
 
b6e823c
b478fa4
 
 
 
 
 
 
 
 
 
 
 
 
4b6c305
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b478fa4
 
 
b6e823c
71b64e5
 
 
 
 
b478fa4
71b64e5
 
 
b478fa4
71b64e5
 
 
 
 
 
 
b478fa4
 
 
71b64e5
 
 
 
 
 
 
 
 
 
b478fa4
 
71b64e5
 
 
 
 
 
 
b478fa4
bcae715
 
b478fa4
 
 
 
 
bcae715
 
b478fa4
 
 
bcae715
b478fa4
23c8a11
 
bcae715
 
b478fa4
e04572c
b478fa4
 
 
bcae715
 
b478fa4
 
 
 
 
bcae715
 
b478fa4
 
23c8a11
b478fa4
bcae715
b6e823c
b478fa4
e04572c
 
b6e823c
d4b35b4
b478fa4
 
4b1e7e2
feda791
b478fa4
 
 
feda791
b478fa4
 
 
2e01f75
 
 
 
 
 
b478fa4
2e01f75
 
 
b478fa4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e01f75
b478fa4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b6c305
 
 
b478fa4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e04572c
 
b478fa4
 
 
 
 
e04572c
 
 
 
2e01f75
e04572c
2e01f75
b478fa4
e04572c
b478fa4
 
e04572c
 
b478fa4
e04572c
b478fa4
e04572c
b478fa4
 
e04572c
 
b478fa4
e04572c
b478fa4
 
 
 
 
4b6c305
b478fa4
 
4b6c305
b478fa4
 
 
 
 
 
 
 
 
 
4b6c305
 
 
 
 
 
 
b478fa4
4b6c305
b478fa4
 
4b6c305
 
 
 
b478fa4
 
4b6c305
b478fa4
 
 
4b6c305
b478fa4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b6c305
b478fa4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b6c305
b478fa4
 
 
 
 
 
 
 
 
 
 
 
 
0dcb231
 
b6e823c
b478fa4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e04572c
 
 
 
 
 
b478fa4
 
e04572c
b478fa4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e04572c
b478fa4
 
 
 
 
 
bcae715
4b1e7e2
b478fa4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e04572c
b478fa4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e04572c
 
 
b478fa4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc2a7d2
b6e823c
b478fa4
 
 
 
 
 
 
 
 
 
 
 
 
 
e04572c
b478fa4
e04572c
b478fa4
 
 
 
 
 
 
 
 
 
 
 
 
e04572c
b478fa4
 
4b6c305
 
b478fa4
 
 
 
 
 
 
 
 
 
 
 
 
 
e04572c
b478fa4
 
 
 
 
 
 
 
 
 
d57ae02
5400d92
b478fa4
 
4b6c305
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
"""
ADAPTIVE READING COMPREHENSION β€” v6
=====================================
Changes vs v5:
  1. Login now takes ROLL NUMBER + PASSWORD instead of free-text Name/Class.
  2. Name + Class are reverse-looked-up from the gateway sheet:
       https://docs.google.com/spreadsheets/d/1jjxLQED9tJKKMd5yIlQfpxc7dxsLkqB22Vf5ZYKeAio
       (worksheet "name roll", columns: Name | Class | Roll | Password | year | status(pass/fail))
  3. Effective class = sheet Class + (current_year - sheet year), i.e. the
     student is auto-promoted one class per year that has passed since the
     sheet's `year` value β€” UNLESS status(pass/fail) says "fail", in which
     case no promotion happens (student repeats the same class).
       Example: sheet says year=2026, Class=6, status=pass. In 2027, the
       student is treated as Class 7. If status had been "fail", they'd
       stay Class 6 in 2027.
  4. Name + (promoted) Class are what get saved to the Scores sheet, exactly
     as before (Date | Name | Classs | Result | Full Marks | Percentage |
     Star | Level | ...).

Files needed:  pssg1.txt  qstn1.txt  previous.txt (optional)
Secrets:       DEEPSEEK_API_KEY   gcp_service_account
"""

import os, re, json, time, datetime
import gradio as gr

BASE_DIR       = os.path.dirname(os.path.abspath(__file__))
MAX_QUESTIONS  = 6
THRESHOLD_STAR = 4
LOW_STAR_LIMIT = 2

DEEPSEEK_API_KEY  = os.getenv("DEEPSEEK_API_KEY")
DEEPSEEK_BASE_URL = "https://api.deepseek.com"
DEEPSEEK_MODEL    = "deepseek-v4-pro"

SPREADSHEET_ID    = "18oKXXwKMWE_CfKJGljWqRAKAIsp0SK6ffmkly2GHnxk"
WORKSHEET_NAME    = "Scores"

# Gateway sheet β€” reverse-map Roll+Password -> Name / Class / year / status
GATEWAY_SHEET_ID       = "1jjxLQED9tJKKMd5yIlQfpxc7dxsLkqB22Vf5ZYKeAio"
GATEWAY_WORKSHEET_NAME = "name roll"

HIDE_DELAY = [(i + 1) * 5 for i in range(MAX_QUESTIONS)]   # 5,10,15,20,25,30s


# =============================================================
# LAZY CLIENTS
# =============================================================

def get_llm_client():
    if not DEEPSEEK_API_KEY: return None
    try:
        from openai import OpenAI
        return OpenAI(api_key=DEEPSEEK_API_KEY, base_url=DEEPSEEK_BASE_URL)
    except Exception as e:
        print(f"[LLM] {e}"); return None


def _gspread_client():
    try:
        import gspread
        from google.oauth2.service_account import Credentials
    except ImportError as e:
        raise RuntimeError(f"pip install gspread google-auth  ({e})")
    raw = os.environ.get("gcp_service_account")
    if not raw: raise RuntimeError("gcp_service_account secret not set")
    creds = Credentials.from_service_account_info(
        json.loads(raw),
        scopes=["https://www.googleapis.com/auth/spreadsheets"])
    return gspread.authorize(creds)


def get_sheet():
    return _gspread_client().open_by_key(SPREADSHEET_ID).worksheet(WORKSHEET_NAME)


def get_gateway_sheet():
    return _gspread_client().open_by_key(GATEWAY_SHEET_ID).worksheet(GATEWAY_WORKSHEET_NAME)


# =============================================================
# GOOGLE SHEETS β€” SCORES
# Columns: Date | Name | Classs | Result | Full Marks | Percentage | Star | Level
# =============================================================

def log_to_sheets(name, grade, result, full_marks, percent, stars, level_label):
    try:
        row = [datetime.datetime.now().strftime("%m/%d/%Y %H:%M:%S"),
               name, grade, result, full_marks,
               round(float(percent), 1), stars, level_label]
        get_sheet().append_row(row, value_input_option="USER_ENTERED")
        print(f"[Sheets] saved {name} stars={stars} level={level_label}")
        return ""
    except Exception as e:
        import traceback; traceback.print_exc()
        return f"{type(e).__name__}: {e}"


# =============================================================
# STUDENT LOGIN β€” GATEWAY SHEET (Roll + Password -> Name / Class)
# =============================================================

def lookup_student(roll, password):
    """
    Look up a student by Roll + Password in the gateway sheet.
    Returns (record_dict, "") on success, or (None, error_message) on failure.
    record_dict = {"name": str, "class": str, "year": value, "status": str}
    """
    try:
        ws = get_gateway_sheet()
        records = ws.get_all_records()
    except Exception as e:
        return None, f"Could not reach the student database: {type(e).__name__}: {e}"

    roll_clean = str(roll).strip()
    pwd_clean  = str(password).strip()

    for row in records:
        sheet_roll = str(row.get("Roll", "")).strip()
        if sheet_roll.lower() == roll_clean.lower():
            sheet_pwd = str(row.get("Password", "")).strip()
            if sheet_pwd != pwd_clean:
                return None, "Incorrect password."
            return {
                "name":   str(row.get("Name", "")).strip(),
                "class":  str(row.get("Class", "")).strip(),
                "year":   row.get("year", ""),
                "status": str(row.get("status(pass/fail)", "")).strip(),
            }, ""

    return None, "Roll number not found."


def compute_effective_class(base_class, sheet_year, status):
    """
    Promote the sheet's Class by one for every year that has passed since
    `sheet_year`, unless `status` marks the student as having failed (in
    which case they stay at the same class β€” no promotion).
    """
    m = re.match(r"(\d+)", str(base_class).strip())
    if not m:
        return str(base_class).strip()          # non-numeric class, leave as-is
    base_num = int(m.group(1))

    try:
        sheet_year_num = int(str(sheet_year).strip())
    except (TypeError, ValueError):
        return str(base_num)                     # no usable year, no promotion

    current_year  = datetime.datetime.now().year
    years_passed  = max(0, current_year - sheet_year_num)

    failed = str(status).strip().lower().startswith("fail")
    if failed:
        years_passed = 0

    return str(base_num + years_passed)


# =============================================================
# FILE LOADING
# =============================================================

def is_class5(klass: str) -> bool:
    return str(klass).strip().startswith("5")


def load_passages_and_questions(klass: str):
    passages, questions = {}, {}

    class5 = is_class5(klass)

    for fname in os.listdir(BASE_DIR):

        # ================= PASSAGES =================
        if class5:
            m = re.match(r'pssg(\d+)class5\.txt$', fname)
        else:
            m = re.match(r'pssg(\d+)\.txt$', fname)

        if m:
            idx = int(m.group(1))
            passages[idx] = open(
                os.path.join(BASE_DIR, fname),
                encoding="utf-8"
            ).read().strip()

        # ================= QUESTIONS =================
        if class5:
            m = re.match(r'(?:qstn|question)(\d+)class5\.txt$', fname)
        else:
            m = re.match(r'(?:qstn|question)(\d+)\.txt$', fname)

        if m:
            idx = int(m.group(1))
            questions[idx] = [
                l.strip() for l in open(
                    os.path.join(BASE_DIR, fname),
                    encoding="utf-8"
                ) if l.strip()
            ]

    return passages, questions


def load_previous():
    p = os.path.join(BASE_DIR, "previous.txt")
    return (open(p, encoding="utf-8").read().strip()
            if os.path.exists(p)
            else "No previous.txt found.")


# =============================================================
# STARS / LEVEL
# =============================================================

def passages_for_level(level):
    # Level -1 β†’ 2 passages, 0 β†’ 3, 1 β†’ 4, 2 β†’ 5 … (capped at 8)
    return min(8, max(2, level + 3))


def pass1_stars_from_score(correct, total):
    # 0-5 stars from meaning only
    if total <= 0 or correct <= 0: return 0
    if correct >= total:           return 5
    return max(1, round(correct / total * 5))


def english_bonus(eng_correct, eng_total, mode):
    if eng_total <= 0: return 0
    ratio = eng_correct / eng_total
    max_b = 3 if mode == "disappearing" else 1
    return round(ratio * max_b)


def compute_next_level(current, stars):
    if stars >= THRESHOLD_STAR: return current + 1
    if stars <= LOW_STAR_LIMIT: return max(-1, current - 1)  # floor at -1
    return current


def stars_display(n):
    n = max(0, min(8, int(round(n))))
    return "⭐" * n + "β˜†" * max(0, 8 - n)


def build_level_label(level, mode):
    return f"Comprehension-Level {level} - {mode}"


# =============================================================
# LLM β€” PASS 1
# =============================================================

def grade_answers(passage, questions, answers):
    client = get_llm_client()
    if not client: return _fallback_grade(questions, answers)
    lines = []
    for i,(q,a) in enumerate(zip(questions,answers)):
        if not q.strip(): continue
        ans_text = a.strip() if a.strip() else "[NO ANSWER β€” mark as 0, incorrect]"
        lines.append(f"Q{i+1}: {q}\nA{i+1}: {ans_text}")
    qa = "\n".join(lines)
    sys_p = ("Grade reading-comp answers on meaning only. Spelling OK. "
             "STRICT RULE: Any answer marked [NO ANSWER] must receive 0 credit and "
             "be marked incorrect. Do not infer or assume any answer. "
             "Partial credit allowed for partial answers. "
             "Return ONLY JSON: correct_count(float), total_questions(int), "
             "percent(float 0-100), feedback(list of strings, one per active question).")
    try:
        r = client.chat.completions.create(
            model=DEEPSEEK_MODEL, temperature=0,
            messages=[{"role":"system","content":sys_p},
                      {"role":"user",
                       "content":f"PASSAGE:\n{passage}\n\nQ&A:\n{qa}\n\nJSON only."}])
        raw = re.sub(r"^```[a-z]*\n?","",r.choices[0].message.content.strip())
        return json.loads(re.sub(r"\n?```$","",raw))
    except Exception as e:
        print(f"[P1] {e}"); return _fallback_grade(questions, answers)


def _fallback_grade(questions, answers):
    total    = sum(1 for q in questions if q.strip())
    answered = sum(1 for q,a in zip(questions,answers) if q.strip() and a.strip())
    return {"correct_count": answered, "total_questions": total,
            "percent": round(answered/total*100 if total else 0),
            "feedback": ["(No LLM)"] * total}


# =============================================================
# LLM β€” MODEL ANSWERS
# =============================================================

def get_model_answers(passage, questions):
    client = get_llm_client()
    active = [q for q in questions if q.strip()]
    if not client: return ["(unavailable)"] * len(active)
    q_block = "\n".join(f"Q{i+1}: {q}" for i,q in enumerate(questions) if q.strip())
    sys_p   = ("One concise, grammatically correct English sentence per question. "
               "Return ONLY JSON: model_answers(list of strings).")
    try:
        r = client.chat.completions.create(
            model=DEEPSEEK_MODEL, temperature=0,
            messages=[{"role":"system","content":sys_p},
                      {"role":"user",
                       "content":f"PASSAGE:\n{passage}\n\nQUESTIONS:\n{q_block}\n\nJSON only."}])
        raw = re.sub(r"^```[a-z]*\n?","",r.choices[0].message.content.strip())
        return json.loads(re.sub(r"\n?```$","",raw)).get("model_answers", [""]*len(active))
    except Exception as e:
        print(f"[MA] {e}"); return ["(unavailable)"] * len(active)


# =============================================================
# LLM β€” PASS 2
# =============================================================

def grade_english_rewrite(questions, model_answers, rewrites):
    client = get_llm_client()
    active = [q for q in questions if q.strip()]
    total  = len(active)
    if not client:
        filled = sum(1 for a in rewrites if a.strip())
        return {"correct_count": filled, "total": total, "feedback": ["(No LLM)"]*total}
    lines = [f"Q{i+1}: {q}\nModel: {ma}\nStudent: {rw}"
             for i,(q,ma,rw) in enumerate(zip(questions,model_answers,rewrites))
             if q.strip()]
    sys_p = ("Check if each student rewrite is grammatically correct, complete, "
             "captures meaning. Ignore spaces; minor spelling OK; "
             "must start capital, end full stop. "
             "STRICT RULE: blank or missing rewrites must score 0 β€” do not give credit. "
             "Return ONLY JSON: correct_count(int), total(int), feedback(list).")
    try:
        r = client.chat.completions.create(
            model=DEEPSEEK_MODEL, temperature=0,
            messages=[{"role":"system","content":sys_p},
                      {"role":"user","content":"\n\n".join(lines)+"\n\nJSON only."}])
        raw  = re.sub(r"^```[a-z]*\n?","",r.choices[0].message.content.strip())
        data = json.loads(re.sub(r"\n?```$","",raw))
        return {"correct_count": data.get("correct_count",0),
                "total":         data.get("total", total),
                "feedback":      data.get("feedback",[])}
    except Exception as e:
        print(f"[P2] {e}")
        filled = sum(1 for a in rewrites if a.strip())
        return {"correct_count": filled, "total": total, "feedback": [str(e)]*total}


# =============================================================
# HTML HELPERS  (no <script> β€” stripped by Gradio 5)
# =============================================================

NS = ("user-select:none;-webkit-user-select:none;"
      "-moz-user-select:none;-ms-user-select:none;pointer-events:none;")

def passage_html(text):
    if not text: return ""
    return (f'<div style="background:#fafafa;border:1px solid #ddd;'
            f'border-radius:6px;padding:16px;font-size:15px;line-height:1.8;{NS}">'
            f'{text.replace(chr(10),"<br>")}</div>')

def ma_card_text(i, answer, mode):
    delay = HIDE_DELAY[i]
    note  = f" *(hides in {delay}s)*" if mode == "disappearing" else ""
    return f"**Model Answer Q{i+1}{note}:**  {answer}"


ANTI_COPY = """<script>
['contextmenu','copy','cut'].forEach(e=>
  document.addEventListener(e,x=>x.preventDefault()));
document.addEventListener('selectstart',x=>{
  if(!['INPUT','TEXTAREA'].includes(x.target.tagName))x.preventDefault();
});
</script>"""


# =============================================================
# SESSION STATE
# =============================================================

def fresh_state():
    return {
        "student_name":"","student_grade":"","text_mode":"disappearing",
        "level":0,"passages":{},"questions":{},"indices":[],"ptr":0,
        "round_num":0,"Pssg_end":"NO",
        "current_passage":"","current_questions":[],
        "model_answers_list":[],
        "ma_shown_at":None,
        "ma_hidden":[False]*MAX_QUESTIONS,
        "pass1_stars":0,"pass1_correct":0.0,"pass1_total":0,"pass1_percent":0.0,
        "cumulative_correct":0.0,"cumulative_total":0,
        "all_stars":[],"last_stars":0,
    }


def load_next_chunk(state):
    size  = passages_for_level(state["level"])
    chunk = state["indices"][state["ptr"]: state["ptr"] + size]
    if not chunk: return False
    next_ptr = state["ptr"] + size
    state["Pssg_end"] = "YES" if next_ptr >= len(state["indices"]) else "NO"
    state["current_passage"]   = "\n\n".join(state["passages"][i] for i in chunk)
    qs = []
    for i in chunk: qs += state["questions"].get(i,[])
    state["current_questions"] = qs[:MAX_QUESTIONS]
    state["model_answers_list"] = []
    state["ma_shown_at"]  = None
    state["ma_hidden"]    = [False]*MAX_QUESTIONS
    state["ptr"]         += size
    return True


# =============================================================
# UI HELPERS
# =============================================================

def q_updates(q_list, vis):
    return [gr.update(value=f"**Q{i+1}:** {q_list[i]}", visible=True)
            if vis and i < len(q_list) else gr.update(value="", visible=False)
            for i in range(MAX_QUESTIONS)]

def a_updates(q_list, vis):
    return [gr.update(value="", visible=(vis and i < len(q_list)))
            for i in range(MAX_QUESTIONS)]

def rw_updates(q_list, vis):
    return [gr.update(value="", visible=(vis and i < len(q_list)),
                      label=f"Rewrite Q{i+1} in correct English")
            for i in range(MAX_QUESTIONS)]

def ma_updates_show(q_list, model_answers, mode):
    out = []
    for i in range(MAX_QUESTIONS):
        if i < len(q_list) and i < len(model_answers):
            out.append(gr.update(value=ma_card_text(i, model_answers[i], mode),
                                 visible=True))
        else:
            out.append(gr.update(value="", visible=False))
    return out

def ma_updates_hide():
    return [gr.update(value="", visible=False) for _ in range(MAX_QUESTIONS)]


# =============================================================
# BUILD UI
# =============================================================

with gr.Blocks(title="Reading Comprehension Quiz", theme=gr.themes.Soft()) as demo:

    gr.HTML(ANTI_COPY)
    gr.Markdown("# πŸ“– Adaptive Reading Comprehension Quiz")

    # ── WELCOME ────────────────────────────────────────────
    with gr.Group(visible=True) as welcome_panel:

        gr.Markdown("## Step 1 β€” Choose how model answers are shown")
        gr.Markdown(
            "| Mode | How it works | Bonus stars |\n"
            "|---|---|---|\n"
            "| ⏱️ **Disappearing** | Q1 vanishes after 5s, Q2 after 10s … | Up to **+3** |\n"
            "| πŸ“Œ **Static** | Answers stay on screen | Up to **+1** |"
        )

        with gr.Row():
            btn_dis = gr.Button("⏱️  Disappearing  (harder)", variant="primary",  size="lg")
            btn_sta = gr.Button("πŸ“Œ  Static  (easier)",        variant="secondary", size="lg")

        mode_state   = gr.State("disappearing")
        chosen_md    = gr.Markdown(
            "> βœ… **Disappearing** selected β€” answers vanish one by one. "
            "Earn up to **+3 bonus stars**.")

        def pick_dis(_):
            return ("disappearing",
                    "> βœ… **Disappearing** selected β€” answers vanish one by one. "
                    "Earn up to **+3 bonus stars**.",
                    gr.update(variant="primary"), gr.update(variant="secondary"))

        def pick_sta(_):
            return ("static",
                    "> βœ… **Static** selected β€” answers stay on screen. "
                    "Earn up to **+1 bonus star**.",
                    gr.update(variant="secondary"), gr.update(variant="primary"))

        btn_dis.click(pick_dis, inputs=[mode_state],
                      outputs=[mode_state, chosen_md, btn_dis, btn_sta])
        btn_sta.click(pick_sta, inputs=[mode_state],
                      outputs=[mode_state, chosen_md, btn_dis, btn_sta])

        gr.Markdown("---")
        gr.Markdown(
            "### πŸ“‹ How the quiz works\n"
            "1. Read the passage β€” **you cannot copy it**.\n"
            "2. Answer questions and click **Submit Answers** (Pass 1 β€” graded on meaning, 0-5 stars).\n"
            "3. Model answers appear β€” study them, then rewrite in correct English (Pass 2 β€” bonus stars).\n"
            "4. Score high (4+ stars) β†’ harder next passage. Score low (0-2) β†’ easier.\n"
            "5. Your final score is **saved only after all passages are complete**."
        )

        gr.Markdown("---")
        btn_past   = gr.Button("πŸ“–  View Past Story", variant="secondary")
        past_story = gr.Markdown(visible=False)
        btn_past.click(
            lambda: gr.update(value=load_previous(), visible=True),
            outputs=[past_story])

        gr.Markdown("---")
        gr.Markdown("## Step 2 β€” Enter your Roll Number and Password")
        inp_roll  = gr.Textbox(label="Roll Number", placeholder="e.g. SK-2026-6015")
        inp_pwd   = gr.Textbox(label="Password", placeholder="Your password", type="password")
        login_err = gr.Markdown("")
        btn_start = gr.Button("β–Ά  Start Quiz", variant="primary", size="lg")

    # ── QUIZ ───────────────────────────────────────────────
    with gr.Group(visible=False) as quiz_panel:

        status_md   = gr.Markdown("### Level 0")
        passage_box = gr.HTML("")

        gr.Markdown("---")
        gr.Markdown("#### ✏️ Your answers")

        q_labels = [gr.Markdown(visible=False) for _ in range(MAX_QUESTIONS)]
        a_boxes  = [gr.Textbox(label=f"Answer {i+1}", visible=False, lines=2)
                    for i in range(MAX_QUESTIONS)]

        thinking_md = gr.Markdown(visible=False)
        btn_submit  = gr.Button("βœ…  Submit Answers", variant="primary")
        result_md   = gr.Markdown("")

        # Individual model-answer cards (one per question)
        # These are hidden/shown by the Timer
        gr.Markdown("---")
        rewrite_hdr = gr.Markdown(visible=False)
        ma_cards = [gr.Markdown(visible=False) for _ in range(MAX_QUESTIONS)]

        gr.Markdown("---")
        rw_boxes = [gr.Textbox(label=f"Rewrite Q{i+1} in correct English",
                               visible=False, lines=2)
                    for i in range(MAX_QUESTIONS)]

        thinking2_md  = gr.Markdown(visible=False)
        btn_submit_rw = gr.Button("βœ…  Submit Rewrite", variant="primary", visible=False)
        result2_md    = gr.Markdown("")
        btn_next      = gr.Button("➑  Next Passage", visible=False)

    # ── DONE ───────────────────────────────────────────────
    with gr.Group(visible=False) as done_panel:
        gr.Markdown("##   Quiz Complete!")
        done_md = gr.Markdown("")

    sess = gr.State(fresh_state())
    # Separate state for timer β€” prevents Timer tick from overwriting main sess
    ma_timer_state = gr.State({"shown_at": None, "hidden": [False]*MAX_QUESTIONS, "mode": "disappearing"})

    # ── TIMER β€” hides model-answer cards one by one ─────────
    try:
        tick = gr.Timer(value=1)

        def cb_tick(ts):
            # ts keys: shown_at / hidden / mode  (separate from main sess)
            no_change = (ts, *([gr.update()] * MAX_QUESTIONS))
            if ts.get("shown_at") is None:
                return no_change
            if ts.get("mode") != "disappearing":
                return no_change

            elapsed = time.time() - ts["shown_at"]
            updates = []
            for i in range(MAX_QUESTIONS):
                if ts["hidden"][i]:
                    updates.append(gr.update())          # already hidden
                elif elapsed >= HIDE_DELAY[i]:
                    ts["hidden"][i] = True
                    updates.append(gr.update(
                        value=f"~~Q{i+1} model answer β€” time is up~~",
                        visible=True))
                else:
                    updates.append(gr.update())          # still visible, no change
            return (ts, *updates)

        tick.tick(cb_tick, inputs=[ma_timer_state], outputs=[ma_timer_state, *ma_cards])
    except AttributeError:
        pass


    # ==========================================================
    # START β€” now looks up Name + Class from Roll + Password
    # ==========================================================

    def cb_start(roll, pwd, mode, state):
        fail_ret = (state,
                    gr.update(), gr.update(), gr.update(), "",
                    "", "",
                    *q_updates([], False), *a_updates([], False),
                    gr.update(visible=False), gr.update(visible=True),
                    *ma_updates_hide(),
                    gr.update(visible=False), *rw_updates([], False),
                    gr.update(visible=False), "", "",
                    gr.update(visible=False))

        if not roll.strip() or not pwd.strip():
            ret = list(fail_ret)
            ret[4] = "Please enter your roll number and password."
            return tuple(ret)

        record, err = lookup_student(roll, pwd)
        if record is None:
            ret = list(fail_ret)
            ret[4] = err or "Login failed."
            return tuple(ret)

        name      = record["name"]
        eff_class = compute_effective_class(record["class"], record["year"], record["status"])

        passages, qs = load_passages_and_questions(eff_class)
        if not passages:
            ret = list(fail_ret)
            ret[4] = f"No passage files found for Class {eff_class}."
            return tuple(ret)

        state.update({
            "student_name": name, "student_grade": eff_class,
            "text_mode": mode, "passages": passages, "questions": qs,
            "indices": sorted(passages.keys()),
        })
        if not load_next_chunk(state):
            ret = list(fail_ret)
            ret[4] = "No passages available."
            return tuple(ret)

        total = len(state["indices"])
        return (
            state,
            gr.update(visible=False),   # welcome
            gr.update(visible=True),    # quiz
            gr.update(visible=False),   # done
            "",
            f"### {name}  |  Class {eff_class}  |  Level {state['level']}  |  Passage 1 of {total}",
            passage_html(state["current_passage"]),
            *q_updates(state["current_questions"], True),
            *a_updates(state["current_questions"], True),
            gr.update(visible=False),   # thinking_md
            gr.update(visible=True),    # btn_submit
            *ma_updates_hide(),
            gr.update(visible=False),   # rewrite_hdr
            *rw_updates([], False),
            gr.update(visible=False),   # btn_submit_rw
            "", "",
            gr.update(visible=False),   # btn_next
        )

    btn_start.click(
        cb_start,
        inputs=[inp_roll, inp_pwd, mode_state, sess],
        outputs=[
            sess,
            welcome_panel, quiz_panel, done_panel,
            login_err,
            status_md, passage_box,
            *q_labels, *a_boxes,
            thinking_md, btn_submit,
            *ma_cards,
            rewrite_hdr, *rw_boxes,
            btn_submit_rw,
            result_md, result2_md,
            btn_next,
        ],
    )


    # ==========================================================
    # SUBMIT P1 β€” step A: show spinner
    # ==========================================================

    def show_p1_spinner(state):
        return (gr.update(value="⏳ **Grading your answers… please wait.**",
                          visible=True),
                gr.update(visible=False))


    def cb_submit(state, *answer_vals):
        answers   = list(answer_vals)
        questions = state["current_questions"]
        mode      = state["text_mode"]

        result        = grade_answers(state["current_passage"], questions, answers)
        percent       = result.get("percent", 0)
        correct_count = result.get("correct_count", 0)
        total_q       = result.get("total_questions", len(questions))
        feedback      = result.get("feedback", [])

        p1_stars = pass1_stars_from_score(correct_count, total_q)
        state["pass1_stars"]   = p1_stars
        state["pass1_correct"] = correct_count
        state["pass1_total"]   = total_q
        state["pass1_percent"] = percent
        state["cumulative_correct"] = state.get("cumulative_correct",0) + correct_count
        state["cumulative_total"]   = state.get("cumulative_total",  0) + total_q

        fb_lines = [f"- **Q{i+1}:** {feedback[i] if i<len(feedback) else ''}"
                    for i,q in enumerate(questions) if q.strip()]

        max_b = 3 if mode == "disappearing" else 1
        result_text = (
            f"### Pass 1 β€” Meaning\n"
            f"**Score:** {correct_count}/{total_q}  ({percent:.0f}%)\n\n"
            f"**Stars:** {stars_display(p1_stars)}  ({p1_stars} / 5)\n\n"
            + "\n".join(fb_lines) + "\n\n"
            + f"*Study the model answers below. Rewrite in correct English "
              f"to earn up to **+{max_b} bonus stars**.*"
        )

        model_answers = get_model_answers(state["current_passage"], questions)
        state["model_answers_list"] = model_answers
        state["ma_shown_at"]        = time.time()
        state["ma_hidden"]          = [False] * MAX_QUESTIONS

        mode_label = ("⏱️ Answers disappear one by one β€” rewrite quickly!"
                      if mode == "disappearing"
                      else "πŸ“Œ Answers stay on screen β€” rewrite in correct English below.")
        rw_hdr = f"#### πŸ“˜ Model Answers β€” {mode_label}"

        # Build updated timer state for the separate timer gr.State
        new_timer_state = {
            "shown_at": state["ma_shown_at"],
            "hidden":   list(state["ma_hidden"]),
            "mode":     mode,
        }
        return (
            state,
            new_timer_state,                                      # ma_timer_state
            gr.update(visible=False),                            # thinking_md
            result_text,
            gr.update(value=rw_hdr, visible=True),              # rewrite_hdr
            *ma_updates_show(questions, model_answers, mode),   # ma_cards
            *rw_updates(questions, True),                        # rw_boxes
            gr.update(visible=True),                            # btn_submit_rw
        )

    btn_submit.click(
        show_p1_spinner,
        inputs=[sess],
        outputs=[thinking_md, btn_submit],
    ).then(
        cb_submit,
        inputs=[sess, *a_boxes],
        outputs=[
            sess, ma_timer_state, thinking_md, result_md,
            rewrite_hdr,
            *ma_cards,
            *rw_boxes,
            btn_submit_rw,
        ],
    )


    # ==========================================================
    # SUBMIT P2 β€” step A: show spinner
    # ==========================================================

    def show_p2_spinner(state):
        return (gr.update(value="⏳ **Checking your English… please wait.**",
                          visible=True),
                gr.update(visible=False))


    def cb_submit_rewrite(state, *rw_vals):
        rewrites  = list(rw_vals)
        questions = state["current_questions"]
        mode      = state["text_mode"]

        eng       = grade_english_rewrite(questions, state["model_answers_list"], rewrites)
        eng_corr  = eng.get("correct_count", 0)
        eng_total = eng.get("total", len([q for q in questions if q.strip()]))
        eng_fb    = eng.get("feedback", [])

        bonus       = english_bonus(eng_corr, eng_total, mode)
        final_stars = min(8, state["pass1_stars"] + bonus)

        state["last_stars"]  = final_stars
        state["round_num"]  += 1
        state["all_stars"].append(final_stars)

        avg = (round(sum(state["all_stars"])/len(state["all_stars"]),2)
               if state["all_stars"] else 0)

        max_b = 3 if mode == "disappearing" else 1
        bonus_line = (
            f"Earned **+{bonus}** bonus star{'s' if bonus!=1 else ''} "
            f"({eng_corr}/{eng_total} rewrites correct)"
            if bonus > 0
            else f"No bonus this time β€” {eng_corr}/{eng_total} rewrites met the standard."
        )
        eng_fb_lines = [f"- **Q{i+1}:** {eng_fb[i] if i<len(eng_fb) else ''}"
                        for i,q in enumerate(questions) if q.strip()]

        sheets_status = ""
        if state["Pssg_end"] == "YES":
            cc  = state.get("cumulative_correct", 0)
            ct  = state.get("cumulative_total",   0)
            pct = round(cc/ct*100 if ct else 0, 1)
            avg_s = round(sum(state["all_stars"])/len(state["all_stars"]),2) \
                    if state["all_stars"] else 0
            err = log_to_sheets(
                state["student_name"], state["student_grade"],
                round(cc,1), ct, pct,
                round(avg_s,2),
                build_level_label(state["level"], mode)
            )
            sheets_status = (
                "\n\n**Score saved to Google Sheets.**"
                if not err else f"\n\nSheets error: `{err}`"
            )

        result2_text = (
            f"### Pass 2 β€” English Quality\n"
            f"**Rewrites correct:** {eng_corr}/{eng_total}\n\n"
            f"{bonus_line}\n\n"
            f"**Final Stars:** {stars_display(final_stars)}  "
            f"({final_stars} / 8)  "
            f"*(Pass 1: {state['pass1_stars']}/5 + Bonus: +{bonus})*\n\n"
            f"**Running average:** {avg:.2f} / 8\n\n"
            + "\n".join(eng_fb_lines)
            + sheets_status
        )

        more = state["ptr"] < len(state["indices"])
        return (
            state,
            gr.update(visible=False),   # thinking2_md
            result2_text,
            gr.update(visible=False),   # btn_submit_rw
            gr.update(visible=more),    # btn_next
        )

    btn_submit_rw.click(
        show_p2_spinner,
        inputs=[sess],
        outputs=[thinking2_md, btn_submit_rw],
    ).then(
        cb_submit_rewrite,
        inputs=[sess, *rw_boxes],
        outputs=[sess, thinking2_md, result2_md, btn_submit_rw, btn_next],
    )


    # ==========================================================
    # NEXT
    # ==========================================================

    def cb_next(state):
        state["level"] = compute_next_level(state["level"], state["last_stars"])
        ok = load_next_chunk(state)

        if not ok:
            avg = (round(sum(state["all_stars"])/len(state["all_stars"]),2)
                   if state["all_stars"] else 0)
            done = (f"### Well done, **{state['student_name']}**!\n\n"
                    f"Completed **{state['round_num']}** rounds.\n\n"
                    f"**Final Level:** {state['level']}\n\n"
                    f"**Average Stars (saved):** {avg:.2f} / 8  {stars_display(round(avg))}")
            return (
                state, {"shown_at": None, "hidden": [False]*MAX_QUESTIONS, "mode": "disappearing"},
                gr.update(visible=False), gr.update(visible=True),
                done, "",
                passage_html(""),
                *q_updates([], False), *a_updates([], False),
                gr.update(visible=False), gr.update(visible=False),
                *ma_updates_hide(),
                gr.update(visible=False), *rw_updates([], False),
                gr.update(visible=False), "", "",
                gr.update(visible=False),
            )

        total = len(state["indices"])
        return (
            state, {"shown_at": None, "hidden": [False]*MAX_QUESTIONS, "mode": "disappearing"},
            gr.update(visible=True), gr.update(visible=False),
            "",
            f"### {state['student_name']}  |  Class {state['student_grade']}  |  "
            f"Level {state['level']}  |  Passage {state['ptr']} of {total}",
            passage_html(state["current_passage"]),
            *q_updates(state["current_questions"], True),
            *a_updates(state["current_questions"], True),
            gr.update(visible=False), gr.update(visible=True),
            *ma_updates_hide(),
            gr.update(visible=False), *rw_updates([], False),
            gr.update(visible=False), "", "",
            gr.update(visible=False),
        )

    btn_next.click(
        cb_next,
        inputs=[sess],
        outputs=[
            sess, ma_timer_state,
            quiz_panel, done_panel, done_md,
            status_md, passage_box,
            *q_labels, *a_boxes,
            thinking_md, btn_submit,
            *ma_cards,
            rewrite_hdr, *rw_boxes,
            btn_submit_rw,
            result_md, result2_md,
            btn_next,
        ],
    )


if __name__ == "__main__":
    demo.launch()