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50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
"""
BrightMind API Backend
Secure FastAPI backend for BrightLearn iOS app
Deployed on Hugging Face Spaces
"""

import os
import time
import json
import hashlib
from datetime import datetime, timedelta
from typing import Optional, Dict, Any
from functools import wraps
from collections import defaultdict

from fastapi import FastAPI, HTTPException, Header, Request, Depends
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
import requests

# ============================================
# CONFIGURATION
# ============================================

# Secrets (set in HF Space settings)
APP_SECRET_KEY = os.environ.get("appkey", "")  # Key iOS app sends
HF_TOKEN = os.environ.get("HF_TOKEN", "")  # Hugging Face API token
RATE_LIMIT_PER_MINUTE = int(os.environ.get("RATE_LIMIT_PER_MINUTE", "30"))

# LLM Model - Using a reliable model available on HF Inference API
LLM_MODEL = "meta-llama/Llama-3.1-70B-Instruct"

# ============================================
# RATE LIMITING
# ============================================

rate_limit_store: Dict[str, list] = defaultdict(list)

def check_rate_limit(client_id: str) -> bool:
    """Check if client has exceeded rate limit"""
    now = time.time()
    window_start = now - 60  # 1 minute window

    # Clean old entries
    rate_limit_store[client_id] = [
        t for t in rate_limit_store[client_id] if t > window_start
    ]

    if len(rate_limit_store[client_id]) >= RATE_LIMIT_PER_MINUTE:
        return False

    rate_limit_store[client_id].append(now)
    return True

# ============================================
# SECURITY
# ============================================

def get_client_id(request: Request) -> str:
    """Generate unique client ID from request"""
    forwarded = request.headers.get("X-Forwarded-For", "")
    ip = forwarded.split(",")[0].strip() if forwarded else request.client.host
    user_agent = request.headers.get("User-Agent", "")
    return hashlib.sha256(f"{ip}:{user_agent}".encode()).hexdigest()[:16]

async def verify_api_key(
    x_api_key: Optional[str] = Header(None, alias="X-API-Key"),
    x_app_version: Optional[str] = Header(None, alias="X-App-Version"),
):
    """Verify the API key from iOS app"""
    if not APP_SECRET_KEY:
        # No key configured - allow all (development mode)
        return True

    if not x_api_key:
        raise HTTPException(status_code=401, detail="Missing API key")

    if x_api_key != APP_SECRET_KEY:
        raise HTTPException(status_code=401, detail="Invalid API key")

    return True

# ============================================
# FASTAPI APP
# ============================================

app = FastAPI(
    title="BrightMind API",
    description="Secure backend for BrightLearn iOS app",
    version="1.0.0",
)

# CORS - restrict to your app in production
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # In production, restrict this
    allow_credentials=True,
    allow_methods=["POST", "GET"],
    allow_headers=["*"],
)

# ============================================
# REQUEST/RESPONSE MODELS
# ============================================

class AlbertRequest(BaseModel):
    message: str = Field(..., min_length=1, max_length=2000)
    user_name: Optional[str] = "Student"
    age_group: Optional[str] = "9-12"
    history: Optional[list] = []

class MathMindRequest(BaseModel):
    message: str = Field(..., min_length=1, max_length=2000)
    grade_level: Optional[str] = "9-12"
    history: Optional[list] = []

class LessonPlanRequest(BaseModel):
    topic: str = Field(..., min_length=1, max_length=500)
    subject: str
    grade_level: str
    duration: int = Field(ge=15, le=180)
    difficulty: str = "Intermediate"

class ContentRequest(BaseModel):
    topic: str = Field(..., min_length=1, max_length=500)
    subject: str
    grade_level: str
    content_type: str
    content_length: str = "Medium"
    difficulty: str = "Intermediate"

class QuizRequest(BaseModel):
    topic: str = Field(..., min_length=1, max_length=500)
    subject: str
    grade_level: str
    question_count: int = Field(ge=3, le=20)
    question_types: list = ["multiple_choice"]
    standards: str = "none"

class RubricRequest(BaseModel):
    assignment_type: str
    learning_objectives: str
    grade_level: str
    point_scale: int = 100
    special_needs: list = []

class CareerGrowthRequest(BaseModel):
    current_role: str
    years_experience: str
    career_goal: str
    timeline: str

class InterviewPrepRequest(BaseModel):
    position: str
    school_type: str = "Public"
    subject_grade: Optional[str] = ""
    concerns: Optional[str] = ""

class ReportCommentsRequest(BaseModel):
    student_name: str
    subject: str
    grade_level: str
    performance: str
    areas_of_strength: str
    areas_for_improvement: str

class ParentCommunicationRequest(BaseModel):
    topic: str
    student_name: str
    context: str
    tone: str = "Professional"

class ESLToolkitRequest(BaseModel):
    content_type: str  # sentence_frames, cloze, vocabulary, etc.
    topic: str
    proficiency_level: str
    grade_level: str

class ECERequest(BaseModel):
    activity_type: str
    topic: str
    age_group: str  # Pre-K, K, 1st, 2nd
    duration: int = 30

class CareerExplorationRequest(BaseModel):
    interests: str
    skills: str
    grade_level: str

class DifferentiationRequest(BaseModel):
    content: str
    learning_needs: list
    grade_level: str

class CompensationRequest(BaseModel):
    current_role: str
    years_experience: str
    location: str
    certifications: list = []

# --- NEW SYNCED FEATURE REQUEST MODELS ---

class AlbertProRequest(BaseModel):
    message: str = Field(..., min_length=1, max_length=2000)
    user_name: Optional[str] = "Student"
    age_group: Optional[str] = "9-12"
    history: Optional[list] = []

class MathDiagnosticRequest(BaseModel):
    topic: str = Field(..., min_length=1, max_length=500)
    grade_level: Optional[str] = "7"
    student_responses: str = Field(..., min_length=1, max_length=5000)

class ContentProRequest(BaseModel):
    topic: str = Field(..., min_length=1, max_length=500)
    subject: str
    grade_level: str
    difficulty: str = "Intermediate"
    content_type: str
    content_length: str = "Medium"

class SmartPracticeRequest(BaseModel):
    action: str  # 'get_question' or 'check_answer'
    subject: str
    difficulty: Optional[str] = "medium"
    learning_style: Optional[str] = "steps"
    answer: Optional[str] = None
    history: Optional[list] = []
    misconceptions: Optional[list] = []

class StudentGameRequest(BaseModel):
    subject: str
    grade_range: str = "6-8"
    question_count: int = Field(default=10, ge=3, le=20)

class APIResponse(BaseModel):
    success: bool
    response: str
    timestamp: str

# ============================================
# LLM HELPER
# ============================================

def call_llm(system_prompt: str, user_message: str, max_tokens: int = 2000) -> str:
    """Call Hugging Face LLM with error handling"""
    if not HF_TOKEN:
        raise HTTPException(status_code=500, detail="LLM not configured")

    try:
        # Use HuggingFace Inference API with OpenAI-compatible endpoint
        API_URL = "https://router.huggingface.co/v1/chat/completions"

        headers = {
            "Authorization": f"Bearer {HF_TOKEN}",
            "Content-Type": "application/json",
        }

        payload = {
            "model": LLM_MODEL,
            "messages": [
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": user_message},
            ],
            "max_tokens": max_tokens,
            "temperature": 0.7,
        }

        response = requests.post(API_URL, headers=headers, json=payload, timeout=90)
        response.raise_for_status()

        result = response.json()
        return result["choices"][0]["message"]["content"].strip()

    except requests.exceptions.Timeout:
        raise HTTPException(status_code=504, detail="LLM request timed out")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"LLM error: {str(e)}")

# ============================================
# SYSTEM PROMPTS
# ============================================

PROMPTS = {
    "albert": """You are Albert, a friendly and knowledgeable AI learning assistant.
Your name is Albert and you're talking to {user_name}, a student in grade {age_group}.

CRITICAL: Adjust your response based on the student's grade level ({age_group}):
- K-2 (Kindergarten to 2nd grade): Use very simple words, short sentences, fun comparisons to everyday things kids know (toys, animals, family). Use lots of encouragement and emojis.
- 3-5 (3rd to 5th grade): Use clear explanations with relatable examples. Can introduce some new vocabulary with definitions. Keep it engaging and fun.
- 6-8 (Middle School): Can use more complex vocabulary and concepts. Provide deeper explanations with real-world applications. Encourage critical thinking.
- 9-12 (High School): Use academic language appropriate for teens. Provide comprehensive explanations with nuance. Can discuss abstract concepts and multiple perspectives.

Guidelines:
- Be encouraging and supportive
- Break down complex topics appropriately for the grade level
- Ask follow-up questions to ensure understanding
- Be patient and never condescending
- Match vocabulary and sentence complexity to the grade level""",

    "mathmind": """You are MathMind, an expert math tutor for grade {grade_level} students.

CRITICAL: Adjust your explanation based on the student's grade level ({grade_level}):
- K-2: Use counting, basic addition/subtraction, simple shapes. Use visual examples (apples, toys, fingers). Very simple language with encouragement.
- 3-5: Cover multiplication, division, fractions, basic geometry. Use real-world examples (pizza slices, money). Clear step-by-step explanations.
- 6-8: Include pre-algebra, ratios, percentages, basic equations. Introduce mathematical vocabulary. Show multiple solution methods.
- 9-12: Cover algebra, geometry proofs, trigonometry, pre-calculus. Use formal mathematical notation. Explain underlying concepts and theorems.

Guidelines:
- Explain mathematical concepts step by step appropriate for the grade level
- Use LaTeX notation for math: \\( inline \\) and \\[ block \\]
- Provide examples and practice problems at the right difficulty
- Be encouraging when students struggle
- Match problem complexity to the grade level""",

    "lesson_plan": """You are an expert curriculum designer. Create a detailed lesson plan with:
- Learning objectives (SMART goals)
- Materials needed
- Introduction/Hook (5-10 min)
- Direct instruction
- Guided practice
- Independent practice
- Assessment strategies
- Differentiation ideas
- Closure activity
Format in clear markdown with headers.""",

    "content": """You are an expert educational content creator. Generate high-quality {content_type} that:
- Is appropriate for {grade_level} level
- Covers the topic thoroughly
- Includes clear instructions
- Has engaging activities
- Is formatted in clean markdown""",

    "quiz": """You are an expert assessment designer. Create a quiz with:
- Clear, unambiguous questions
- Appropriate difficulty for {grade_level}
- Mix of question types as requested
- Answer key at the end
- Aligned to {standards} standards if specified
Format in markdown.""",

    "rubric": """You are an expert in inclusive assessment design. Create a rubric that:
- Has clear criteria and descriptors
- Uses the {point_scale}-point scale
- Accommodates diverse learners
- Includes specific, measurable criteria
- Is fair and transparent
Format as a clear table in markdown.""",

    "career_growth": """You are a career development coach for educators. Create a personalized career plan with:
- Current situation analysis
- SMART goals for the timeline
- Specific action steps
- Professional development recommendations
- Networking strategies
- Milestones and checkpoints
Format in markdown with actionable items.""",

    "interview_prep": """You are an expert interview coach for educators. Provide:
- Common interview questions for this position
- STAR method response frameworks
- Tips specific to {school_type} schools
- Questions to ask the interviewer
- Confidence-building strategies
Format in clear, actionable markdown.""",

    "report_comments": """You are an expert at writing personalized, constructive report card comments. Write comments that:
- Are specific and meaningful
- Highlight strengths genuinely
- Frame improvements constructively
- Are appropriate for parents to read
- Encourage continued growth""",

    "parent_communication": """You are an expert at culturally sensitive parent communication. Write a message that:
- Is professional yet warm
- Respects cultural differences
- Clearly communicates the topic
- Invites collaboration
- Provides next steps if needed""",

    "esl_toolkit": """You are an ESL/ELL specialist. Create {content_type} materials that:
- Are appropriate for {proficiency_level} English learners
- Support language acquisition
- Include visual supports where helpful
- Build academic vocabulary
- Are culturally responsive""",

    "ece": """You are an early childhood education specialist. Create age-appropriate activities that:
- Are developmentally appropriate for {age_group}
- Include play-based learning
- Support multiple domains (cognitive, social, physical)
- Are safe and engaging
- Include simple materials""",

    "career_exploration": """You are a career counselor for students. Help explore careers that:
- Match their interests and skills
- Include educational pathways
- Provide realistic salary expectations
- Suggest related careers to explore
- Include next steps for exploration""",

    "differentiation": """You are a differentiation specialist. Adapt the content to:
- Meet the specified learning needs
- Maintain rigor while increasing access
- Provide multiple means of engagement
- Include scaffolds and supports
- Suggest modifications and accommodations""",

    "compensation": """You are a compensation and career advancement advisor for educators. Provide:
- Salary benchmarks for the role and location
- Advancement pathways with salary increases
- Additional income opportunities
- Certification ROI analysis
- Negotiation strategies""",

    # --- NEW SYNCED FEATURE PROMPTS ---

    "albert_pro": """You are Albert Pro, a friendly and enthusiastic learning assistant for {age_group} year olds.
You explain things in a fun, age-appropriate way. You're patient, encouraging, and make learning enjoyable.
{user_context}
Always be positive and use simple language that {age_group} year olds can understand.
IMPORTANT: When a student asks a question, you MUST provide a helpful, informative answer. Do not just say "I'm here to help" or ask them to tell you more - actually answer their question in an age-appropriate way. Be specific and educational while keeping it fun and engaging.""",

    "math_diagnostic": """You are an expert math education specialist trained in identifying and addressing common mathematical misconceptions. Analyze the following student responses and provide a detailed diagnosis.

## Context
- **Math Topic**: {topic}
- **Grade Level**: {grade_level}

## Student Responses to Analyze
{student_responses}

## Your Task
Analyze these responses and identify the underlying **misconceptions** (not just errors). A misconception is a flawed way of thinking that leads to systematic errors.

Provide your analysis in this exact format:

# 📊 Misconception Analysis Report

## Overview
Provide a brief summary of the analysis (2-3 sentences about what you found).

## 🔴 Misconceptions Identified

For EACH misconception found, provide:

### Misconception 1: [Name of Misconception]

**Students Affected:** [List which students show this misconception]

**What They Think:**
> Explain in plain language what the student believes (the flawed mental model)

**Why This Happens:**
- Explain the cognitive reason behind this misconception
- Common prior knowledge that leads to this error

**Evidence from Responses:**
- Quote specific student answers that demonstrate this misconception

**🔧 5-Minute Fix (Do This Tomorrow):**
1. **Step 1:** [Specific action with example dialogue]
2. **Step 2:** [Follow-up activity]
3. **Step 3:** [Practice problems to assign]

**💡 Key Question to Ask Students:**
> [A powerful question that exposes the misconception]

---

[Repeat for each misconception found]

## ✅ Students Without Major Misconceptions
List any students who showed correct understanding and are ready for grade-level work.

## 📋 Recommended Student Groupings
| Group | Misconception | Students | Priority |
|-------|--------------|----------|----------|
| Group A | [Misconception name] | [Students] | High/Medium/Low |
| Group B | [Misconception name] | [Students] | High/Medium/Low |

## 🎯 Immediate Next Steps
1. [Action for tomorrow]
2. [Action for this week]
3. [Follow-up assessment suggestion]

---

**Important Guidelines:**
- Be specific and actionable - teachers should be able to use this immediately
- Focus on the THINKING ERROR, not just the wrong answer
- Provide interventions that address the root cause
- Use simple, teacher-friendly language
- Include specific examples and dialogue teachers can use
- Make the 5-minute fix realistic to do in a busy classroom""",

    "content_pro": """You are an expert educational content creator. Create {content_length} educational {content_type} about the topic.

Requirements:
- Appropriate for {grade_level} grade level
- {difficulty} difficulty level
- {content_length} length
- Well-structured and engaging
- Include examples and explanations
- Use clear, age-appropriate language

Format the content with clear sections, headings, and examples.""",

    "smart_practice_question": """You are an adaptive math tutor. Generate a single practice question.

Subject: {subject}
Difficulty: {difficulty} (easy=single-step, medium=two steps, hard=multiple steps)
{focus_context}

Recent conversation:
{recent_history}

Rules:
1. Generate ONE clear math problem
2. Do NOT give the answer
3. Keep it to 1-3 sentences max
4. Make it appropriate for the difficulty level

Respond with ONLY the question, nothing else.""",

    "smart_practice_check": """You are checking a student's math answer.

Question: {question}
Student's answer: {answer}
Subject: {subject}
Teaching style: {style_prompt}

Respond with ONLY a JSON object (no markdown):
{{
  "isCorrect": true or false,
  "feedback": "2-3 sentences. If wrong, explain using their style. Be encouraging.",
  "misconception": "If wrong, name the specific misconception. If correct, empty string.",
  "misconceptionDescription": "Brief description for report. If correct, empty string."
}}""",
}

# ============================================
# API ENDPOINTS
# ============================================

@app.get("/")
async def root():
    """Health check endpoint"""
    return {"status": "healthy", "service": "BrightMind API", "version": "1.0.0"}

@app.get("/health")
async def health():
    """Health check"""
    return {"status": "ok", "timestamp": datetime.utcnow().isoformat()}


# --- ASK ALBERT ---
@app.post("/api/albert", response_model=APIResponse)
async def albert(
    request: Request,
    data: AlbertRequest,
    _: bool = Depends(verify_api_key),
):
    client_id = get_client_id(request)
    if not check_rate_limit(client_id):
        raise HTTPException(status_code=429, detail="Rate limit exceeded")

    system_prompt = PROMPTS["albert"].format(
        age_group=data.age_group,
        user_name=data.user_name,
    )

    # Include history context
    context = ""
    if data.history:
        context = "Previous conversation:\n"
        for msg in data.history[-5:]:  # Last 5 messages
            role = "Student" if msg.get("role") == "user" else "Albert"
            context += f"{role}: {msg.get('content', '')}\n"
        context += "\nCurrent message:\n"

    response = call_llm(system_prompt, context + data.message)

    return APIResponse(
        success=True,
        response=response,
        timestamp=datetime.utcnow().isoformat(),
    )


# --- MATHMIND ---
@app.post("/api/mathmind", response_model=APIResponse)
async def mathmind(
    request: Request,
    data: MathMindRequest,
    _: bool = Depends(verify_api_key),
):
    client_id = get_client_id(request)
    if not check_rate_limit(client_id):
        raise HTTPException(status_code=429, detail="Rate limit exceeded")

    system_prompt = PROMPTS["mathmind"].format(grade_level=data.grade_level)

    context = ""
    if data.history:
        context = "Previous conversation:\n"
        for msg in data.history[-5:]:
            role = "Student" if msg.get("role") == "user" else "MathMind"
            context += f"{role}: {msg.get('content', '')}\n"
        context += "\nCurrent question:\n"

    response = call_llm(system_prompt, context + data.message, max_tokens=3000)

    return APIResponse(
        success=True,
        response=response,
        timestamp=datetime.utcnow().isoformat(),
    )


# --- LESSON PLAN ---
@app.post("/api/lesson-plan", response_model=APIResponse)
async def lesson_plan(
    request: Request,
    data: LessonPlanRequest,
    _: bool = Depends(verify_api_key),
):
    client_id = get_client_id(request)
    if not check_rate_limit(client_id):
        raise HTTPException(status_code=429, detail="Rate limit exceeded")

    user_message = f"""Create a {data.duration}-minute lesson plan:
Topic: {data.topic}
Subject: {data.subject}
Grade Level: {data.grade_level}
Difficulty: {data.difficulty}"""

    response = call_llm(PROMPTS["lesson_plan"], user_message, max_tokens=3000)

    return APIResponse(
        success=True,
        response=response,
        timestamp=datetime.utcnow().isoformat(),
    )


# --- CONTENT GENERATOR ---
@app.post("/api/content", response_model=APIResponse)
async def content(
    request: Request,
    data: ContentRequest,
    _: bool = Depends(verify_api_key),
):
    client_id = get_client_id(request)
    if not check_rate_limit(client_id):
        raise HTTPException(status_code=429, detail="Rate limit exceeded")

    system_prompt = PROMPTS["content"].format(
        content_type=data.content_type,
        grade_level=data.grade_level,
    )

    user_message = f"""Create {data.content_length} {data.content_type}:
Topic: {data.topic}
Subject: {data.subject}
Grade Level: {data.grade_level}
Difficulty: {data.difficulty}"""

    response = call_llm(system_prompt, user_message, max_tokens=4000)

    return APIResponse(
        success=True,
        response=response,
        timestamp=datetime.utcnow().isoformat(),
    )


# --- QUIZ GENERATOR ---
@app.post("/api/quiz", response_model=APIResponse)
async def quiz(
    request: Request,
    data: QuizRequest,
    _: bool = Depends(verify_api_key),
):
    client_id = get_client_id(request)
    if not check_rate_limit(client_id):
        raise HTTPException(status_code=429, detail="Rate limit exceeded")

    system_prompt = PROMPTS["quiz"].format(
        grade_level=data.grade_level,
        standards=data.standards,
    )

    user_message = f"""Create a {data.question_count}-question quiz:
Topic: {data.topic}
Subject: {data.subject}
Grade Level: {data.grade_level}
Question Types: {', '.join(data.question_types)}
Standards Alignment: {data.standards}"""

    response = call_llm(system_prompt, user_message, max_tokens=3000)

    return APIResponse(
        success=True,
        response=response,
        timestamp=datetime.utcnow().isoformat(),
    )


# --- RUBRIC GENERATOR ---
@app.post("/api/rubric", response_model=APIResponse)
async def rubric(
    request: Request,
    data: RubricRequest,
    _: bool = Depends(verify_api_key),
):
    client_id = get_client_id(request)
    if not check_rate_limit(client_id):
        raise HTTPException(status_code=429, detail="Rate limit exceeded")

    system_prompt = PROMPTS["rubric"].format(point_scale=data.point_scale)

    special_needs_text = ", ".join(data.special_needs) if data.special_needs else "None specified"

    user_message = f"""Create an inclusive rubric:
Assignment Type: {data.assignment_type}
Learning Objectives: {data.learning_objectives}
Grade Level: {data.grade_level}
Point Scale: {data.point_scale}
Special Needs to Accommodate: {special_needs_text}"""

    response = call_llm(system_prompt, user_message, max_tokens=3000)

    return APIResponse(
        success=True,
        response=response,
        timestamp=datetime.utcnow().isoformat(),
    )


# --- CAREER GROWTH ---
@app.post("/api/career-growth", response_model=APIResponse)
async def career_growth(
    request: Request,
    data: CareerGrowthRequest,
    _: bool = Depends(verify_api_key),
):
    client_id = get_client_id(request)
    if not check_rate_limit(client_id):
        raise HTTPException(status_code=429, detail="Rate limit exceeded")

    user_message = f"""Create a career development plan:
Current Role: {data.current_role}
Years of Experience: {data.years_experience}
Career Goal: {data.career_goal}
Timeline: {data.timeline}"""

    response = call_llm(PROMPTS["career_growth"], user_message, max_tokens=3000)

    return APIResponse(
        success=True,
        response=response,
        timestamp=datetime.utcnow().isoformat(),
    )


# --- INTERVIEW PREP ---
@app.post("/api/interview-prep", response_model=APIResponse)
async def interview_prep(
    request: Request,
    data: InterviewPrepRequest,
    _: bool = Depends(verify_api_key),
):
    client_id = get_client_id(request)
    if not check_rate_limit(client_id):
        raise HTTPException(status_code=429, detail="Rate limit exceeded")

    system_prompt = PROMPTS["interview_prep"].format(school_type=data.school_type)

    user_message = f"""Prepare for this interview:
Position: {data.position}
School Type: {data.school_type}
Subject/Grade Level: {data.subject_grade or 'Not specified'}
Specific Concerns: {data.concerns or 'None'}"""

    response = call_llm(system_prompt, user_message, max_tokens=3000)

    return APIResponse(
        success=True,
        response=response,
        timestamp=datetime.utcnow().isoformat(),
    )


# --- REPORT COMMENTS ---
@app.post("/api/report-comments", response_model=APIResponse)
async def report_comments(
    request: Request,
    data: ReportCommentsRequest,
    _: bool = Depends(verify_api_key),
):
    client_id = get_client_id(request)
    if not check_rate_limit(client_id):
        raise HTTPException(status_code=429, detail="Rate limit exceeded")

    user_message = f"""Write a report card comment:
Student Name: {data.student_name}
Subject: {data.subject}
Grade Level: {data.grade_level}
Performance Level: {data.performance}
Strengths: {data.areas_of_strength}
Areas for Improvement: {data.areas_for_improvement}"""

    response = call_llm(PROMPTS["report_comments"], user_message)

    return APIResponse(
        success=True,
        response=response,
        timestamp=datetime.utcnow().isoformat(),
    )


# --- PARENT COMMUNICATION ---
@app.post("/api/parent-communication", response_model=APIResponse)
async def parent_communication(
    request: Request,
    data: ParentCommunicationRequest,
    _: bool = Depends(verify_api_key),
):
    client_id = get_client_id(request)
    if not check_rate_limit(client_id):
        raise HTTPException(status_code=429, detail="Rate limit exceeded")

    user_message = f"""Write a parent communication:
Topic: {data.topic}
Student Name: {data.student_name}
Context: {data.context}
Tone: {data.tone}"""

    response = call_llm(PROMPTS["parent_communication"], user_message)

    return APIResponse(
        success=True,
        response=response,
        timestamp=datetime.utcnow().isoformat(),
    )


# --- ESL TOOLKIT ---
@app.post("/api/esl-toolkit", response_model=APIResponse)
async def esl_toolkit(
    request: Request,
    data: ESLToolkitRequest,
    _: bool = Depends(verify_api_key),
):
    client_id = get_client_id(request)
    if not check_rate_limit(client_id):
        raise HTTPException(status_code=429, detail="Rate limit exceeded")

    system_prompt = PROMPTS["esl_toolkit"].format(
        content_type=data.content_type,
        proficiency_level=data.proficiency_level,
    )

    user_message = f"""Create ESL materials:
Content Type: {data.content_type}
Topic: {data.topic}
Proficiency Level: {data.proficiency_level}
Grade Level: {data.grade_level}"""

    response = call_llm(system_prompt, user_message, max_tokens=3000)

    return APIResponse(
        success=True,
        response=response,
        timestamp=datetime.utcnow().isoformat(),
    )


# --- ECE (Early Childhood) ---
@app.post("/api/ece", response_model=APIResponse)
async def ece(
    request: Request,
    data: ECERequest,
    _: bool = Depends(verify_api_key),
):
    client_id = get_client_id(request)
    if not check_rate_limit(client_id):
        raise HTTPException(status_code=429, detail="Rate limit exceeded")

    system_prompt = PROMPTS["ece"].format(age_group=data.age_group)

    user_message = f"""Create an early childhood activity:
Activity Type: {data.activity_type}
Topic: {data.topic}
Age Group: {data.age_group}
Duration: {data.duration} minutes"""

    response = call_llm(system_prompt, user_message)

    return APIResponse(
        success=True,
        response=response,
        timestamp=datetime.utcnow().isoformat(),
    )


# --- CAREER EXPLORATION ---
@app.post("/api/career-exploration", response_model=APIResponse)
async def career_exploration(
    request: Request,
    data: CareerExplorationRequest,
    _: bool = Depends(verify_api_key),
):
    client_id = get_client_id(request)
    if not check_rate_limit(client_id):
        raise HTTPException(status_code=429, detail="Rate limit exceeded")

    user_message = f"""Help explore careers:
Interests: {data.interests}
Skills: {data.skills}
Grade Level: {data.grade_level}"""

    response = call_llm(PROMPTS["career_exploration"], user_message)

    return APIResponse(
        success=True,
        response=response,
        timestamp=datetime.utcnow().isoformat(),
    )


# --- DIFFERENTIATION ---
@app.post("/api/differentiation", response_model=APIResponse)
async def differentiation(
    request: Request,
    data: DifferentiationRequest,
    _: bool = Depends(verify_api_key),
):
    client_id = get_client_id(request)
    if not check_rate_limit(client_id):
        raise HTTPException(status_code=429, detail="Rate limit exceeded")

    user_message = f"""Differentiate this content:
Content: {data.content}
Learning Needs: {', '.join(data.learning_needs)}
Grade Level: {data.grade_level}"""

    response = call_llm(PROMPTS["differentiation"], user_message, max_tokens=3000)

    return APIResponse(
        success=True,
        response=response,
        timestamp=datetime.utcnow().isoformat(),
    )


# --- COMPENSATION & ADVANCEMENT ---
@app.post("/api/compensation", response_model=APIResponse)
async def compensation(
    request: Request,
    data: CompensationRequest,
    _: bool = Depends(verify_api_key),
):
    client_id = get_client_id(request)
    if not check_rate_limit(client_id):
        raise HTTPException(status_code=429, detail="Rate limit exceeded")

    certifications_text = ", ".join(data.certifications) if data.certifications else "None"

    user_message = f"""Provide compensation and advancement guidance:
Current Role: {data.current_role}
Years of Experience: {data.years_experience}
Location: {data.location}
Current Certifications: {certifications_text}"""

    response = call_llm(PROMPTS["compensation"], user_message)

    return APIResponse(
        success=True,
        response=response,
        timestamp=datetime.utcnow().isoformat(),
    )


# ============================================
# NEW SYNCED FEATURE ENDPOINTS
# ============================================

# --- ALBERT PRO ---
@app.post("/api/albert-pro", response_model=APIResponse)
async def albert_pro(
    request: Request,
    data: AlbertProRequest,
    _: bool = Depends(verify_api_key),
):
    client_id = get_client_id(request)
    if not check_rate_limit(client_id):
        raise HTTPException(status_code=429, detail="Rate limit exceeded")

    user_context = f"The student's name is {data.user_name}." if data.user_name else ""
    system_prompt = PROMPTS["albert_pro"].format(
        age_group=data.age_group,
        user_context=user_context,
    )

    # Include history context
    context = ""
    if data.history:
        context = "Previous conversation:\n"
        for msg in data.history[-10:]:  # Last 10 messages
            role = "Student" if msg.get("role") == "user" else "Albert Pro"
            context += f"{role}: {msg.get('content', '')}\n"
        context += "\nCurrent message:\n"

    response = call_llm(system_prompt, context + data.message, max_tokens=1500)

    return APIResponse(
        success=True,
        response=response,
        timestamp=datetime.utcnow().isoformat(),
    )


# --- MATH DIAGNOSTIC ---
@app.post("/api/math-diagnostic", response_model=APIResponse)
async def math_diagnostic(
    request: Request,
    data: MathDiagnosticRequest,
    _: bool = Depends(verify_api_key),
):
    client_id = get_client_id(request)
    if not check_rate_limit(client_id):
        raise HTTPException(status_code=429, detail="Rate limit exceeded")

    # Build the analysis prompt
    user_message = PROMPTS["math_diagnostic"].format(
        topic=data.topic.replace("-", " "),
        grade_level=data.grade_level,
        student_responses=data.student_responses,
    )

    response = call_llm(
        "You are an expert math education specialist trained in identifying student misconceptions.",
        user_message,
        max_tokens=3500
    )

    return APIResponse(
        success=True,
        response=response,
        timestamp=datetime.utcnow().isoformat(),
    )


# --- CONTENT PRO ---
@app.post("/api/content-pro", response_model=APIResponse)
async def content_pro(
    request: Request,
    data: ContentProRequest,
    _: bool = Depends(verify_api_key),
):
    client_id = get_client_id(request)
    if not check_rate_limit(client_id):
        raise HTTPException(status_code=429, detail="Rate limit exceeded")

    system_prompt = PROMPTS["content_pro"].format(
        content_type=data.content_type,
        grade_level=data.grade_level,
        difficulty=data.difficulty,
        content_length=data.content_length,
    )

    user_message = f"""Create {data.content_length} educational {data.content_type.lower()} about "{data.topic}" for {data.grade_level} students studying {data.subject}.

Topic: {data.topic}
Subject: {data.subject}
Grade Level: {data.grade_level}
Difficulty: {data.difficulty}"""

    response = call_llm(system_prompt, user_message, max_tokens=4000)

    return APIResponse(
        success=True,
        response=response,
        timestamp=datetime.utcnow().isoformat(),
    )


# --- SMART PRACTICE ---

# Subject topic details for better questions
SMART_PRACTICE_SUBJECTS = {
    "fractions": {
        "topics": ["Adding fractions", "Subtracting fractions", "Multiplying fractions", "Dividing fractions"],
        "misconceptions": ["Adding numerators AND denominators", "Not finding common denominator", "Forgetting to flip when dividing"]
    },
    "algebra": {
        "topics": ["Combining like terms", "Solving one-step equations", "Solving two-step equations", "Distributive property"],
        "misconceptions": ["Adding unlike terms", "Forgetting to apply operation to both sides", "Sign errors"]
    },
    "decimals": {
        "topics": ["Adding decimals", "Subtracting decimals", "Multiplying decimals", "Dividing decimals"],
        "misconceptions": ["Not lining up decimal points", "Miscounting decimal places", "Moving decimal wrong direction"]
    },
    "geometry": {
        "topics": ["Perimeter of rectangles", "Area of rectangles", "Area of triangles", "Circumference of circles"],
        "misconceptions": ["Confusing area and perimeter", "Forgetting radius vs diameter", "Not dividing by 2 for triangle"]
    },
    "negative-numbers": {
        "topics": ["Adding negative numbers", "Subtracting negative numbers", "Multiplying negative numbers"],
        "misconceptions": ["Double negative errors", "Wrong sign when multiplying negatives", "Confusing subtraction direction"]
    },
    "ratios": {
        "topics": ["Writing ratios", "Equivalent ratios", "Unit rates", "Solving proportions"],
        "misconceptions": ["Reversing ratio order", "Not keeping units consistent", "Cross-multiplying incorrectly"]
    }
}

LEARNING_STYLE_PROMPTS = {
    "visual": "Use visual representations and emoji to illustrate. Describe pictures.",
    "steps": "Break down into clear numbered steps. Show each step explicitly.",
    "examples": "Relate to real-world situations like pizza, money, sports.",
    "practice": "Be brief and direct. Quick tip, then move on."
}

DEFAULT_QUESTIONS = {
    "fractions": {"easy": "What is 1/4 + 1/4?", "medium": "What is 2/3 + 1/6?", "hard": "What is 3/4 - 2/5?"},
    "algebra": {"easy": "Simplify: 3x + 2x", "medium": "Solve: x + 5 = 12", "hard": "Solve: 2x + 3 = 11"},
    "decimals": {"easy": "What is 0.5 + 0.3?", "medium": "What is 2.5 × 0.4?", "hard": "What is 3.6 ÷ 0.9?"},
    "geometry": {"easy": "What is the perimeter of a square with side 5?", "medium": "What is the area of a rectangle with length 6 and width 4?", "hard": "What is the area of a circle with radius 3? (Use π = 3.14)"},
    "negative-numbers": {"easy": "What is -3 + 5?", "medium": "What is -4 - (-2)?", "hard": "What is -6 × -3?"},
    "ratios": {"easy": "Write the ratio of 4 apples to 8 oranges in simplest form.", "medium": "If 3 notebooks cost $6, how much do 5 notebooks cost?", "hard": "Solve: 4/x = 12/15"}
}

@app.post("/api/smart-practice")
async def smart_practice(
    request: Request,
    data: SmartPracticeRequest,
    _: bool = Depends(verify_api_key),
):
    client_id = get_client_id(request)
    if not check_rate_limit(client_id):
        raise HTTPException(status_code=429, detail="Rate limit exceeded")

    if data.action == "get_question":
        return await _generate_practice_question(data)
    elif data.action == "check_answer":
        return await _check_practice_answer(data)
    else:
        raise HTTPException(status_code=400, detail="Invalid action. Use 'get_question' or 'check_answer'")


async def _generate_practice_question(data: SmartPracticeRequest):
    """Generate a practice question based on subject and difficulty"""
    subject_info = SMART_PRACTICE_SUBJECTS.get(data.subject, {"topics": [], "misconceptions": []})

    focus_context = ""
    if data.misconceptions:
        misconception_topics = [m.get("topic", "") for m in data.misconceptions if m.get("topic")]
        if misconception_topics:
            focus_context = f"The student has shown these misconceptions: {', '.join(misconception_topics)}. Generate a question that helps them practice and overcome these specific gaps."

    recent_history = ""
    if data.history:
        recent_history = "\n".join([f"{m.get('role', 'user')}: {m.get('content', '')}" for m in data.history[-4:]])

    prompt = PROMPTS["smart_practice_question"].format(
        subject=data.subject,
        difficulty=data.difficulty,
        focus_context=focus_context,
        recent_history=recent_history,
    )

    try:
        question = call_llm("You are an adaptive math tutor.", prompt, max_tokens=150)
    except:
        # Fallback to default question
        subject_defaults = DEFAULT_QUESTIONS.get(data.subject, DEFAULT_QUESTIONS["fractions"])
        question = subject_defaults.get(data.difficulty, "What is 2 + 3?")

    return JSONResponse(content={
        "success": True,
        "question": question,
        "timestamp": datetime.utcnow().isoformat(),
    })


async def _check_practice_answer(data: SmartPracticeRequest):
    """Check a student's answer and provide feedback"""
    if not data.answer:
        raise HTTPException(status_code=400, detail="Answer is required for check_answer action")

    # Find the last question from history
    question = "the previous question"
    if data.history:
        for msg in reversed(data.history):
            if msg.get("role") == "assistant":
                question = msg.get("content", question)
                break

    style_prompt = LEARNING_STYLE_PROMPTS.get(data.learning_style, LEARNING_STYLE_PROMPTS["steps"])

    prompt = PROMPTS["smart_practice_check"].format(
        question=question,
        answer=data.answer,
        subject=data.subject,
        style_prompt=style_prompt,
    )

    try:
        response_text = call_llm("You are a helpful math tutor checking student answers.", prompt, max_tokens=300)

        # Try to parse JSON response
        # Clean up response
        cleaned = response_text.replace("```json", "").replace("```", "").strip()
        parsed = json.loads(cleaned)

        return JSONResponse(content={
            "success": True,
            "is_correct": parsed.get("isCorrect", False),
            "feedback": parsed.get("feedback", "Let me help you with that..."),
            "misconception": parsed.get("misconception", ""),
            "misconception_description": parsed.get("misconceptionDescription", ""),
            "timestamp": datetime.utcnow().isoformat(),
        })
    except:
        # Fallback response
        return JSONResponse(content={
            "success": True,
            "is_correct": False,
            "feedback": "Let me think about that... Let's try looking at this differently. What steps did you use to get your answer?",
            "misconception": "",
            "misconception_description": "",
            "timestamp": datetime.utcnow().isoformat(),
        })


# ============================================
# STUDENT GAME ENDPOINT
# ============================================

# Fallback quiz questions by subject
FALLBACK_QUIZ_QUESTIONS = {
    'Mathematics': [
        {"question": "What is 7 + 8?", "options": ["14", "15", "16", "17"], "correctIndex": 1, "explanation": "7 + 8 = 15"},
        {"question": "What is 12 - 5?", "options": ["6", "7", "8", "9"], "correctIndex": 1, "explanation": "12 - 5 = 7"},
        {"question": "What is 6 x 4?", "options": ["20", "22", "24", "26"], "correctIndex": 2, "explanation": "6 x 4 = 24"},
        {"question": "What is 36 ÷ 6?", "options": ["4", "5", "6", "7"], "correctIndex": 2, "explanation": "36 ÷ 6 = 6"},
        {"question": "What is the next number: 2, 4, 6, 8, ?", "options": ["9", "10", "11", "12"], "correctIndex": 1, "explanation": "The pattern adds 2 each time. 8 + 2 = 10"},
        {"question": "How many sides does a hexagon have?", "options": ["5", "6", "7", "8"], "correctIndex": 1, "explanation": "A hexagon has 6 sides"},
        {"question": "What is 1/2 + 1/2?", "options": ["1/4", "1/2", "1", "2"], "correctIndex": 2, "explanation": "1/2 + 1/2 = 1 whole"},
        {"question": "What is 100 - 37?", "options": ["53", "63", "73", "83"], "correctIndex": 1, "explanation": "100 - 37 = 63"},
        {"question": "How many minutes are in 1 hour?", "options": ["30", "45", "60", "100"], "correctIndex": 2, "explanation": "There are 60 minutes in 1 hour"},
        {"question": "Perimeter of a square with sides 5 cm?", "options": ["15 cm", "20 cm", "25 cm", "10 cm"], "correctIndex": 1, "explanation": "4 × 5 = 20 cm"},
    ],
    'Science': [
        {"question": "What do plants need to make food?", "options": ["Water only", "Sunlight and water", "Air only", "Soil only"], "correctIndex": 1, "explanation": "Plants use sunlight and water for photosynthesis"},
        {"question": "What is the largest planet?", "options": ["Earth", "Mars", "Jupiter", "Saturn"], "correctIndex": 2, "explanation": "Jupiter is the largest planet"},
        {"question": "What type of animal is a frog?", "options": ["Mammal", "Reptile", "Amphibian", "Fish"], "correctIndex": 2, "explanation": "Frogs are amphibians"},
        {"question": "What is H2O?", "options": ["Salt", "Sugar", "Water", "Air"], "correctIndex": 2, "explanation": "H2O is water"},
        {"question": "What force keeps us on the ground?", "options": ["Magnetism", "Friction", "Gravity", "Electricity"], "correctIndex": 2, "explanation": "Gravity pulls us toward Earth"},
        {"question": "What organ pumps blood?", "options": ["Brain", "Lungs", "Heart", "Stomach"], "correctIndex": 2, "explanation": "The heart pumps blood"},
        {"question": "What is the closest star to Earth?", "options": ["Moon", "Mars", "Sun", "Polaris"], "correctIndex": 2, "explanation": "The Sun is our closest star"},
        {"question": "Animals that eat only plants are called?", "options": ["Carnivores", "Herbivores", "Omnivores", "Decomposers"], "correctIndex": 1, "explanation": "Herbivores eat only plants"},
        {"question": "In what state of matter is ice?", "options": ["Gas", "Liquid", "Solid", "Plasma"], "correctIndex": 2, "explanation": "Ice is solid water"},
        {"question": "What gas do humans breathe in?", "options": ["Nitrogen", "Carbon Dioxide", "Oxygen", "Helium"], "correctIndex": 2, "explanation": "We breathe in oxygen"},
    ],
    'History': [
        {"question": "Who was the first US President?", "options": ["Lincoln", "Jefferson", "Washington", "Adams"], "correctIndex": 2, "explanation": "George Washington was the first President"},
        {"question": "When did World War II end?", "options": ["1943", "1944", "1945", "1946"], "correctIndex": 2, "explanation": "WWII ended in 1945"},
        {"question": "Who built the pyramids?", "options": ["Romans", "Greeks", "Egyptians", "Mayans"], "correctIndex": 2, "explanation": "Ancient Egyptians built the pyramids"},
        {"question": "Who wrote the Declaration of Independence?", "options": ["Washington", "Franklin", "Jefferson", "Adams"], "correctIndex": 2, "explanation": "Thomas Jefferson wrote it"},
        {"question": "What ship brought the Pilgrims?", "options": ["Santa Maria", "Mayflower", "Titanic", "Nina"], "correctIndex": 1, "explanation": "The Mayflower brought the Pilgrims"},
        {"question": "Who first walked on the moon?", "options": ["Aldrin", "Armstrong", "Glenn", "Gagarin"], "correctIndex": 1, "explanation": "Neil Armstrong was first on the moon"},
        {"question": "Who invented the telephone?", "options": ["Edison", "Bell", "Tesla", "Franklin"], "correctIndex": 1, "explanation": "Alexander Graham Bell invented it"},
        {"question": "What ancient wonder is in Egypt?", "options": ["Colosseum", "Great Pyramid", "Hanging Gardens", "Lighthouse"], "correctIndex": 1, "explanation": "The Great Pyramid of Giza"},
        {"question": "Who was King of Rock and Roll?", "options": ["Jackson", "Elvis", "Beatles", "Berry"], "correctIndex": 1, "explanation": "Elvis Presley was the King of Rock"},
        {"question": "What did Romans build roads with?", "options": ["Wood", "Stone", "Brick", "Dirt"], "correctIndex": 1, "explanation": "Romans built stone roads"},
    ],
    'English': [
        {"question": "What is a noun?", "options": ["Action word", "Describing word", "Person/place/thing", "Connecting word"], "correctIndex": 2, "explanation": "A noun is a person, place, or thing"},
        {"question": "Which word is a verb?", "options": ["Happy", "Run", "Beautiful", "The"], "correctIndex": 1, "explanation": "Run is an action word (verb)"},
        {"question": "What ends a question?", "options": ["Period", "Exclamation", "Question mark", "Comma"], "correctIndex": 2, "explanation": "Questions end with ?"},
        {"question": "What is opposite of hot?", "options": ["Warm", "Cold", "Wet", "Dry"], "correctIndex": 1, "explanation": "Cold is the opposite of hot"},
        {"question": "Which is spelled correctly?", "options": ["Freind", "Friend", "Frend", "Freand"], "correctIndex": 1, "explanation": "Friend is correct"},
        {"question": "A synonym for happy?", "options": ["Sad", "Angry", "Joyful", "Tired"], "correctIndex": 2, "explanation": "Joyful means happy"},
        {"question": "What type of word is 'quickly'?", "options": ["Noun", "Verb", "Adjective", "Adverb"], "correctIndex": 3, "explanation": "Quickly is an adverb"},
        {"question": "What is plural of child?", "options": ["Childs", "Childes", "Children", "Childrens"], "correctIndex": 2, "explanation": "Children is the plural"},
        {"question": "Which rhymes with cat?", "options": ["Dog", "Hat", "Cup", "Bed"], "correctIndex": 1, "explanation": "Hat rhymes with cat"},
        {"question": "Which sentence is correct?", "options": ["Him went", "He went", "Her went", "Me went"], "correctIndex": 1, "explanation": "He went is grammatically correct"},
    ],
    'Geography': [
        {"question": "What is the largest continent?", "options": ["Africa", "North America", "Asia", "Europe"], "correctIndex": 2, "explanation": "Asia is the largest continent"},
        {"question": "What is the longest river?", "options": ["Amazon", "Nile", "Mississippi", "Yangtze"], "correctIndex": 1, "explanation": "The Nile is the longest river"},
        {"question": "Which ocean is largest?", "options": ["Atlantic", "Indian", "Arctic", "Pacific"], "correctIndex": 3, "explanation": "The Pacific is the largest ocean"},
        {"question": "Where is the Eiffel Tower?", "options": ["Italy", "Spain", "France", "Germany"], "correctIndex": 2, "explanation": "The Eiffel Tower is in France"},
        {"question": "US capital city?", "options": ["New York", "Los Angeles", "Washington D.C.", "Chicago"], "correctIndex": 2, "explanation": "Washington D.C. is the capital"},
        {"question": "Tallest mountain?", "options": ["K2", "Mount Everest", "Kilimanjaro", "Mount Fuji"], "correctIndex": 1, "explanation": "Mount Everest is the tallest"},
        {"question": "Two languages of Canada?", "options": ["English/Spanish", "English/French", "French/Spanish", "English/German"], "correctIndex": 1, "explanation": "English and French are official"},
        {"question": "Brazil is on which continent?", "options": ["Africa", "Europe", "South America", "Asia"], "correctIndex": 2, "explanation": "Brazil is in South America"},
        {"question": "What is an island?", "options": ["Land surrounded by water", "Water surrounded by land", "Tall mountain", "Dry desert"], "correctIndex": 0, "explanation": "An island is land surrounded by water"},
        {"question": "Map showing mountains is called?", "options": ["Political", "Climate", "Physical", "Road"], "correctIndex": 2, "explanation": "Physical maps show terrain"},
    ],
}

@app.post("/api/student-game")
async def student_game(
    request: Request,
    data: StudentGameRequest,
    _: bool = Depends(verify_api_key),
):
    """Generate quiz questions for the student game"""
    client_id = get_client_id(request)
    if not check_rate_limit(client_id):
        raise HTTPException(status_code=429, detail="Rate limit exceeded")

    subject = data.subject
    question_count = data.question_count

    # Build prompt for LLM
    prompt = f"""Generate exactly {question_count} educational multiple-choice quiz questions about {subject} for {data.grade_range} grade students.

Return as a JSON array with no extra text:
[
  {{"question": "...", "options": ["A", "B", "C", "D"], "correctIndex": 0, "explanation": "..."}}
]

Requirements:
- Age-appropriate vocabulary
- 4 answer choices each
- Brief explanations
- Varied difficulty

Generate {question_count} questions now:"""

    try:
        response_text = call_llm("You are an educational quiz generator.", prompt, max_tokens=3000)

        # Try to parse JSON from response
        questions = []
        try:
            # Find JSON array in response
            json_match = response_text
            if '[' in response_text:
                start = response_text.index('[')
                end = response_text.rindex(']') + 1
                json_match = response_text[start:end]
            parsed = json.loads(json_match)
            if isinstance(parsed, list):
                questions = [
                    {
                        "question": q.get("question", ""),
                        "options": q.get("options", []),
                        "correctIndex": q.get("correctIndex", 0),
                        "explanation": q.get("explanation", "")
                    }
                    for q in parsed
                    if q.get("question") and len(q.get("options", [])) == 4
                ]
        except:
            pass

        # Use fallback if parsing failed or not enough questions
        if len(questions) < question_count:
            fallback = FALLBACK_QUIZ_QUESTIONS.get(subject, FALLBACK_QUIZ_QUESTIONS.get('Science', []))
            questions = fallback[:question_count]

        return JSONResponse(content={
            "success": True,
            "questions": questions,
            "timestamp": datetime.utcnow().isoformat(),
        })

    except Exception as e:
        # Return fallback questions on any error
        fallback = FALLBACK_QUIZ_QUESTIONS.get(subject, FALLBACK_QUIZ_QUESTIONS.get('Science', []))
        return JSONResponse(content={
            "success": True,
            "questions": fallback[:question_count],
            "timestamp": datetime.utcnow().isoformat(),
        })


# ============================================
# ERROR HANDLERS
# ============================================

@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
    return JSONResponse(
        status_code=exc.status_code,
        content={
            "success": False,
            "error": exc.detail,
            "timestamp": datetime.utcnow().isoformat(),
        },
    )

@app.exception_handler(Exception)
async def general_exception_handler(request: Request, exc: Exception):
    return JSONResponse(
        status_code=500,
        content={
            "success": False,
            "error": "Internal server error",
            "timestamp": datetime.utcnow().isoformat(),
        },
    )


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=7860)