
    _ i                       S SK J r   S SKJrJrJrJrJrJrJrJ	r	  S SK
Jr  S SKJrJr  S SKJrJr  S SKJr  S SKJrJrJrJrJrJrJrJrJrJrJr  S SK J!r!J"r"J#r#J$r$J%r%J&r&J'r'J(r(J)r)J*r*J+r+J,r,J-r-J.r.J/r/J0r0J1r1J2r2J3r3J4r4  S S	K J5r5J6r6J7r7J8r8J9r9J:r:J;r;J<r<  S S
KJ=r=J>r>J?r?J@r@  S SKArAS SKBrBS SKCJCrCJDrD  S SKEJFrF  \F" 5         \" \G5      rH\HR$                  R                  \5        \" \H\AR                  " S5      SS9  SS jrK\R                  " \H5        \" \H5      rM\HR                  S 5       rO\HR                  5          \R                  " 5         \R" S5        \R" S5        \R" S5        \R                  R                  5       rU\R" S\U 35        \R                  R                  SS9R                  5       rW\R" S\W 35        \US :X  a  \R" S5        \R                  " 5        Ho  u  rYrZ\ZR                  5        HU  u  r[r\\R" S\[ S\Y S35        \\ H:  r]\" \]\[\Y\] S\[ S\Y 3S9r^\R                  R                  \^5        \R" S \] 35        M<     MW     Mq     \R                  R                  5         \R" S!5        O\WS :X  a  \R" S"5        S# H  rYS$ H  r[\[\\Y   ;   d  M  \R" S\[ S\Y S35        \\Y   \[    Hx  r]\R                  R                  \]\[\YS%9R                  5       rb\b(       d9  \" \]\[\Y\] S\[ S\Y 3S9r^\R                  R                  \^5        \R" S \] 35        Ml  \R" S&\] S'35        Mz     M     M     \R                  R                  5         \R" S(5        O\R" S)5        \R                  R                  5       rc\R" S*S 35        \R" S+\c 35        S, HA  r[\R                  R                  \[S9R                  5       rT\TS :  d  M2  \R" S-\[ S.\T S/35        MC     \R" S05        SSS5        \HR                  S1 5       re\HR                  S25      S3 5       rg0 S4S5_S6S7_S8S9_S:S;_S<S=_S>S?_S@SA_SBSC_SDSE_SFSG_SHSI_SJSK_SLSM_SNSO_SPSQ_SRSS_STSU_SVSWSXSYSZS[S\S]S^S_S`SOSaSb.Erh\HR                  Sc5      Sd 5       ri\HR                  SeSf/Sg9Sh 5       rjSi rk\HR                  Sj 5       rO\HR                  SkSlSf/Sg9Sm 5       rl\HR                  SnSlSf/Sg9So 5       rm\HR                  Sp5      Sq 5       rn\HR                  SrSf/Sg9Ss 5       ro\HR                  St5      Su 5       rp\HR                  SvSf/Sg9Sw 5       rq\HR                  SxSf/Sg9Sy 5       rr\HR                  SzSf/Sg9S{ 5       rs\HR                  S|5      S} 5       rt\HR                  S~SlSf/Sg9S 5       ru\HR                  SSlSf/Sg9S 5       rv\HR                  SSf/Sg9S 5       rw\HR                  SSlSf/Sg9S 5       rx\HR                  SSf/Sg9S 5       ry\HR                  SSlSf/Sg9S 5       rz\HR                  SSlSf/Sg9S 5       r{\HR                  S5      S 5       r|\HR                  SSf/Sg9S 5       r}\HR                  SSlSf/Sg9S 5       r~S r\HR                  S5      S 5       r\HR                  SSf/Sg9S 5       r\HR                  SSf/Sg9S 5       r\HR                  S5      S 5       r\HR                  SSf/Sg9S 5       r\HR                  S5      S 5       rS r\HR                  SSf/Sg9S 5       r\HR                  SSf/Sg9S 5       r\HR                  SSf/Sg9S 5       r\HR                  S5      S 5       r\HR                  S5      S 5       r\HR                  S5      S 5       r\HR                  SSf/Sg9S 5       r\HR                  S5      S 5       r\HR                  S5      S 5       r\HR                  S5      S 5       rS rS r\R" S5        \R" S5        \R" S5        \R" S5        \R" S5        \R" S5        \R" S5        \R" S5        \R" S5        \R" S5        \R" S5        \HR                  S5      S 5       r\HR                  S5      S 5       r\HR                  S5      S 5       rS r\HR                  S5      S 5       r\HR                  S5      S 5       r\HR                  SSf/Sg9S 5       r\HR                  S5      S 5       r\HR                  S5      S 5       r\HR                  SSf/Sg9S 5       r\HR                  SSf/Sg9S 5       r\HR                  S5      S 5       r\HR                  S5      S 5       r\HR                  S5      S 5       r\HR                  SSl/Sg9S 5       r\HR                  SSl/Sg9S 5       r\HR                  S5      S 5       r\HGRI                  S5      S 5       r\HGRI                  S5      S 5       r\GS:X  a  \HGRO                  SS9  gg! , (       d  f       GN= f)    )time)Flaskrender_templaterequestjsonifysessionredirecturl_forflash)CORS)MailMessage)Selectfunc)Config)dbUserConceptConceptProgress
AssessmentQuestionHistoryVerificationCodeCONCEPTS_DATAPracticeSessionSchoolTableTeacherTable)generate_verification_codegenerate_unique_usernamesis_username_availablesend_verification_emailgenerate_ai_questionsgenerate_gamified_ai_questionscalculate_mastery_levelget_performance_insightsanalyze_assessment_results(generate_adaptive_ai_questions_age_awarehash_questionvalidate_passwordgenerate_ai_chat_responsecreate_verification_codeverify_code$generate_adaptive_questions_enhanced,generate_concept_questions_adaptive_with_age)generate_progressive_assessment_questions.generate_gamified_ai_questions_age_appropriateshuffle_all_questions)update_user_ranking&update_concept_mastery_from_assessment$update_concept_mastery_from_practiceupdate_practice_ranking)generate_adaptive_questions_with_prioritycalculate_question_pointsget_user_dashboard_statscheck_assessment_eligibility)UserRankingConceptMasteryPracticeRankingQuestionN)datetime	timedelta)load_dotenvFRONTEND_URIT)originssupports_credentialsc           	      x   [        SS 35        [        SU 35        [        S 5        [        U SS 5       Hr  u  p#[        SUS-    SUS	   SS
  S35        [        S5        [        US   5       H$  u  pEXCS   :X  a  SOSn[        SU SU U 35        M&     [        SUS    35        Mt     [        S S35        g)z3Debug: Log question structure to verify correctness
<============================================================u    📊 QUESTION STRUCTURE CHECK - N   z
Q   : question2   z...z
  Options:optionscorrect_answeru    ✓ CORRECT z    [z] z  Correct Index: )print	enumerate)	questionssourceidxqioptmarkers          2D:\beyond school\teacher-association - Copy\app.pylog_question_structurerX   &   s    	Bvh-	,VH
56	VHIbqM*CE7"Qz]3B/045
)-FA'(.>,?'?^RFE!BseF8,- . 	!!$4"5!678 + 
VHB-    c                  |    S[         ;   a/  [        R                   R                  [        [         S   5      n SU 0$ SS0$ )z+Make user object available to all templatesuser_iduserN)r   r   getr   r\   s    rW   inject_userr_   9   s9     Gzz~~dGI$67~D>rY   z=
============================================================zCHECKING CONCEPTS DATABASErE   zExisting concepts in database: 1)gradezGrade 1 concepts: uC   
🆕 Fresh database detected - Adding ALL concepts (Grade 1-12)...z
  Adding Grade  z concepts...z for Grade )namera   streamdescriptionu       ✓ u%   
✅ All concepts added successfully!u>   
🔄 Existing database - Adding missing Grade 1-5 concepts...)CBSEICSE)r`   2345)rc   ra   rd   z    - z (already exists)u+   
✅ Grade 1-5 concepts added successfully!u-   
✅ All concepts already present in databaserD   zTOTAL CONCEPTS IN DATABASE: )r`   rh   ri   rj   rk   6789101112z  Grade rH   z	 conceptsz=============================================================
c                  f    [         R                  " SS5      S:X  a  [        R                  " 5         gg)z0Clean up expired verification codes periodicallyrG   d   N)randomrandintr   cleanup_expired rY   rW   cleanup_expired_codesry      s(     ~~a"((* #rY   /c                  T    S[         ;   a  [        [        S5      5      $ [        S5      $ )zWelcome pager[   	dashboardzwelcome.html)r   r	   r
   r   rx   rY   rW   indexr}      s'     G,-->**rY   male_1u   👨‍💼male_2u   👨‍🎓male_3u   👨‍💻male_4u   👨‍🔬male_5u   👨‍🎨male_6u   👨‍🚀male_7u   🧑‍🏫male_8u   👨‍⚕️male_9u   👨‍🎤male_10u   👨‍🏭male_11u   🧔male_12u   👨‍🦱male_13u   👨‍🦰male_14u   🧑‍🚒male_15u   👨‍✈️female_1u   👩‍💼female_2u   👩‍🎓u   👩‍💻u   👩‍🔬u   👩‍🎨u   👩‍🚀u   👩‍🏫u   👩‍⚕️u   👩‍🎤u   👩‍🏭u   👩u   👩‍🦱u   👩‍🦰u   👩‍✈️)female_3female_4female_5female_6female_7female_8female_9	female_10	female_11	female_12	female_13	female_14	female_15z/debug-sessionc                      [        [        R                  " S5      [        R                  " S5      [        [        R                  " 5       5      S.5      $ )zDebug session datar[   account_type)r[   r   session_keys)r   r   r]   listkeysrx   rY   rW   debug_sessionr      s<     ;;y)N3W\\^,  rY   z/switch-account-typePOST)methodsc                      S[         ;  a  [        SSS.5      S4$ [        R                  " 5       n U (       d  [        SSS.5      S4$ U R	                  SS	5      nUS
;  a  [        SSS.5      S4$ U[         S'   S[         l        [        SU S[         R                  " S5       35        [        SSU S3US.5      $ ! [         a1  n[        S[        U5       35        [        SSS.5      S4s SnA$ SnAff = f)z2Enhanced switch account with better error handlingr[   FNot logged insuccessmessage  zNo data received  r   student)r   parentzInvalid account typeTu   ✅ Account type switched to: z for user: zSwitched to z view)r   r   r   u   ❌ Switch account error: Server error  N)	r   r   r   get_jsonr]   modifiedrN   	Exceptionstr)datar   es      rW   switch_account_typer      s   KG#uIJCOO!u9KLMsRRxx	:44u9OPQSVVV #/.|nKT]H^G_`a%l^59(
  	  K*3q6(345^DEsJJKs/   B< +B< 'B< 0AB< <
C7&C2,C72C7c                  0    [         R                  " SS5      $ )z%Get current account type from sessionr   r   )r   r]   rx   rY   rW   get_account_typer      s    ;;~y11rY   c                      0 n S[         ;   a>  [        R                   R                  [        [         S   5      nXS'   [	        5       U S'   U $ SU S'   SU S'   U $ )z<Make user object and account type available to all templatesr[   r\   current_account_typeNr   )r   r   r]   r   r   )contextr\   s     rW   r_   r_      sa     GGzz~~dGI$67*:*<&' N *3&'NrY   z/school-infoGETc                     [         R                  S:X  a  [        S5      $ [         R                  " 5       n U R	                  SS5      R                  5       nU R	                  SS5      R                  5       nU R	                  SS5      R                  5       n[        XU/5      (       d  [        SSS	.5      $ U[        S
'   U[        S'   U[        S'   S[        S'   [        SSSS.5      $ )z*School information collection - FIRST STEPr   zschool_info.htmlschoolrM   	school_idcityFAll fields are requiredr   temp_schooltemp_school_id	temp_cityusernameregistration_stepTzSchool information saved	/username)r   r   	next_step)	r   methodr   r   r]   stripallr   r   )r   r   r   r   s       rW   school_infor      s     ~~122DXXh#))+Fb)//1I88FB%%'D4())55NOPP $GM )GGK#-G -   rY   z/loginc                     S[         ;   a  [        [        S5      5      $ [        R                  S:X  a  [        S5      $ [        R                  " 5       n U R                  SS5      R                  5       R                  5       nU R                  SS5      R                  5       nU(       a  U(       d  [        SS	S
.5      $ [        R                  R                  US9R                  5       nU(       d  [        SSS
.5      $ UR                  U5      (       d  [        SSS
.5      $ UR!                  5         S[         l        UR$                  [         S'   UR&                  [         S'   [)        SU S35        [        SSS
.5      $ )zLogin page and handlerr[   r|   r   z
login.htmlr   rM   passwordFz"Username and password are requiredr   r   zInvalid username or passwordT	   ✅ User z logged in successfullyzLogin successful)r   r	   r
   r   r   r   r   r]   r   lowerr   r   query	filter_byfirstcheck_passwordupdate_last_login	permanentidr   rN   )r   r   r   r\   s       rW   loginr     sG    G,--~~|,, Dxx
B'--/557Hxx
B'--/H855YZ[[ ::288:D55STUU x((55STUU 	 GGI--GJ	IhZ6
78 t0BCDDrY   z/logoutc                     S[         ;   a[  [        R                   R                  [        [         S   5      n U (       a)  U R	                  5         [        SU R                   S35        [         R                  " 5         [        [        S5      5      $ )z Logout user and update timestampr[   r   z logged out successfullyr}   )
r   r   r]   r   update_last_logoutrN   r   clearr	   r
   r^   s    rW   logoutr   .  se     Gzz~~dGI$67##%Idmm_,DEF MMOGG$%%rY   z/get_conceptc                  j    [         R                  " S5      n U (       d  [        SSS.5      S4$ [        R                  " 5       nUR                  S5      nU(       d  [        SSS.5      S4$ [        [        5      R                  [        R                  [        U5      :H  [        R                  U R                  S	5      :H  -  5      n[        R                   R                  U5      R                  5       R                  5       n/ nU HN  nUR                  UR                   UR                  UR                  UR"                  S
.nUR%                  U5        MP     [        SUS.5      $ ! [&         aB  n[        R                   R)                  5         [        SS[        U5      S.5      S4s S nA$ S nAff = f)NteacherFzNo active teacher found.r   r   ra   zPayload required  rd   )r   rc   ra   rd   re   T)r   resultInternal server errorr   r   errorr   )r   r]   r   r   r   r   r   wherera   r   rd   r   executescalarsr   r   rc   re   appendr   rollback)	r   bodyra   stmtr   r   cresr   s	            rW   get_conceptr   =  s   *++i( 5    !! -   
 g$$gmms5z&AgnnX_XcXcdlXmFm%no##D)113779Add(( }}C KK  
  	
  


-V
  	 	s)   ,E& <E& ,C9E& &
F207F-'F2-F2z/get_curr_userc                       [         R                  " S5      n U (       a  [        SSU S.5      S4$ [        SSS.5      S4$ ! [         a$  n[        SS	[	        U5      S
.5      S4s S nA$ S nAff = f)Nr   T)r   roleusers   FzNo active user foundr   r   r   r   r   )r   r]   r   r   r   )r   r   s     rW   get_curr_userr   l  s    ++i( !   	  -
   	  -V
  	 	s"   -A  A   
A.
A)#A.)A.z/teacher-Registrationc                      [         R                  " 5       n U R                  S5      nU R                  S5      nU R                  S5      nU R                  S5      nU R                  S5      n[        [        5      R                  [        R                  U:H  5      n[        R                  R                  U5      R                  5       nU(       a  [        SSS.5      S	4$ [        [        5      R                  [        R                  " [        R                  " [        R                   5      5      [        R                  " [        R                  " U5      5      :H  [        R"                  U:H  -  5      n[        R                  R                  U5      R                  5       n	U	(       d  [        SS
S.5      S4$ Sn
[	        UUU
U	R$                  S9nUR'                  U5        [        R                  R)                  U5        [        R                  R+                  5         [        SSUR$                  S.5      $ ! [,         aB  n[        R                  R/                  5         [        SS[1        U5      S.5      S4s S nA$ S nAff = f)N
schoolNameschoolIdemailr   gradesFz5Email is already exist please try with diffrent emailr     zSchool not foundr   i@ )r   r   otpr   Tz!teacher registration successfully)r   r   
teacher_idr   r   r   )r   r   r]   r   r   r   r   r   r   r   scalar_one_or_noner   r   r   r   trimschool_namer   r   set_passwordaddcommitr   r   r   )r   r   r   r   r   r   stmt1isExiststmt2r   r   new_teacherr   s                rW   teacher_registrationr    s9   ;!hh|,HHZ(	!88J'(# |$**<+=+=+FG**$$U+>>@ R    {#))4::dii@W@W6X+Y]a]g]ghlhqhqr}h~]+  EP  EZ  EZ  ^g  Eg  +h  i##E*==? -     #			
 	  * 	

{#


:%..
  	  


.V
  	 	s,   CH5 CH5 6A>H5 5
J?7I<6J<Jz/teacher-verificationc                      [         R                  " 5       n U R                  S5      nU R                  S5      n[        [        5      R                  [        R                  U:H  5      n[        R                  R                  U5      R                  5       nU(       d  [        SSS.5      S4$ [        UR                  5      R                  5       [        U5      R                  5       :w  a  [        SSS.5      S4$ SUl        [        R                  R!                  5         [        ["        5      R                  ["        R                  UR$                  :H  5      n[        R                  R                  U5      R                  5       nUR                  UR&                  UR$                  UR(                  UR*                  S	.[        S
'   [        SS[        S
   S
S.5      $ ! [,         a$  n[        SS[        U5      S.5      S4s S nA$ S nAff = f)Nr   r   FzSomething went wrongr   r   zIncorrect OtpTr   r   r   r   rd   r   z!Teacher Verification successfullyr   r   r   r   r   r   r   )r   r   r]   r   r   r   r   r   r   r   r   r   r   r   r   
isVerifiedr   r   r   r   r   rd   r   )r   r   r   r   r   r  r   r   s           rW   teacher_verificationr
    s   .!XXl+
hhuol#)),//Z*GH**$$T*==?  1   
 w{{!!#s3x~~'77 *   
 "


{#))+..G<M<M*MN##E*==? **]] **nnmm
	 :Y'	
  	  .V
  	 	s,   B)G ,AG :C"G 
H'H HHz/teacher-loginc                     [        SSS.5      n  [        R                  " 5       nUR                  S5      nUR                  S5      nU(       a  U(       d  U S4$ [	        [
        5      R                  [
        R                  U:H  5      n[        R                  R                  U5      R                  5       nU(       d  U S4$ UR                  U5      (       d  U $ [	        [        5      R                  [        R                  UR                  :H  5      n[        R                  R                  U5      R                  5       nUR                  UR                  UR                  UR                   UR"                  S.[        S'   [        S	S
[        S   SS.5      $ ! [$         aB  n[        R                  R'                  5         [        SS[)        U5      S.5      S4s S nA$ S nAff = f)NFz0Invalid credential, Please check your credentialr   r   r   r   r  r   TzTeacher Login successfullyr  Internal Server Errorr   r   )r   r   r   r]   r   r   r   r   r   r   r   r   r   r   r   r   r   rd   r   r   r   )	err_responser   r   r   r   r   r  r   r   s	            rW   teacher_loginr    s   E L*!!88J'H$$l#)),*<*<*EF**$$T*==?$$%%h//{#))+..G<M<M*MN##E*==? **]] **nnmm
	 3Y'	
  	  


.V
  	 	s2   AF A&F  F B=F 
G" 7GG"G"z/teacher-logoutc                       [         R                  " 5         [        SSS.5      S4$ ! [         a$  n [        SS[	        U 5      S.5      S4s S n A $ S n A ff = f)	NTzLoggout successfullyr   r   Fr  r   r   )r   r   r   r   r   )r   s    rW   teacher_logoutr  (  sm    -
   	
  .V
  	 	s   $' 
AA
AAz/forgot-passwordc                     [         R                  S:X  a  [        S5      $ [         R                  " 5       n U R	                  S5      nUS:X  a  U R	                  SS5      R                  5       R                  5       nSU;  d  SU;  a  [        S	S
S.5      $ [        R                  R                  US9R                  5       nU(       d  [        SSS.5      $ [        USS9n[        X$UR                  SS9(       a  [        SSS.5      $ [        S	SS.5      $ US:X  a  U R	                  SS5      R                  5       R                  5       nU R	                  SS5      R                  5       nU(       a  U(       d  [        S	SS.5      $ [        X$SS9u  pVU(       a   U[         S'   S[         S'   [        SSS.5      $ [        S	US.5      $ g)z Forgot password page and handlerr   zforgot_password.htmlaction	send_coder   rM   @.FInvalid email formatr   r   Tz@If an account exists with this email, a reset code has been sentpassword_reset	code_typez&Password reset code sent to your emailzFailed to send reset coder+   codezEmail and code are requiredreset_emailcode_verifiedreset_passwordr   r   N)r   r   r   r   r]   r   r   r   r   r   r   r   r*   r    rc   r+   r   )r   r  r   r\   r  is_validr   s          rW   forgot_passwordr!  ;  s    ~~566DXXhF"%++-335es%/u9OPQQ zz##%#0668t8z{|| (9IJ #5		EUVt8`abbu9TUVV	=	 "%++-335xx#))+Du9VWXX (?OP%*GM"'+GO$t:JKLLuABB! 
!rY   z/reset-passwordc                  "   [         R                  S:X  a)  S[        ;  a  [        [	        S5      5      $ [        S5      $ [         R                  " 5       n U R                  SS5      R                  5       nU R                  SS5      R                  5       nS[        ;  d
  S[        ;  a  [        S	S
S.5      $ X:w  a  [        S	SS.5      $ [        U5      u  p4U(       d  [        S	US.5      $ [        S   n[        R                  R                  US9R                  5       nU(       d  [        S	SS.5      $  UR                  U5        [         R                  R#                  5         [        R$                  " SS5        [        R$                  " SS5        ['        SUR(                   35        [        SSS.5      $ ! [*         aM  n[         R                  R-                  5         ['        S[/        U5       35        [        S	SS.5      s SnA$ SnAff = f)zReset password page and handlerr   r  r!  zreset_password.htmlnew_passwordrM   confirm_passwordr  Fz#Invalid session. Please start over.r   Passwords do not matchr  User not foundNu(   ✅ Password reset successful for user: Tz-Password reset successful! You can now login.u   ❌ Password reset error: z+Failed to reset password. Please try again.)r   r   r   r	   r
   r   r   r]   r   r   r(   r   r   r   r   r   r   r   poprN   r   r   r   r   )r   r#  r$  r   error_messager   r\   r   s           rW   r  r  k  s    ~~')G$5677455 D88NB/557Lxx 2B7==? G#g'E55Z[\\ '55MNOO 0=H5]CDD M"E::e,224D55EFGGe,'


 	M4(OT*8HI44cdee e


*3q6(3455bcddes    4BF7 7
HAH	H	Hz/start-registrationc                  0    S[         S'   [        SSS.5      $ )zStart the registration processr   r   Tr   r  )r   r   rx   rY   rW   start_registrationr*    s     $1G t*=>>rY   r   c                     [         R                  S:X  a  [        S5      $ [         R                  " 5       n U R	                  SS5      R                  5       nU(       d  [        SSS.5      $ [        U5      nU[        S'   [        S	US
.5      $ )zUsername creation stepr   zusername.htmlrc   rM   FzName is requiredr   	temp_nameT)r   suggestions)	r   r   r   r   r]   r   r   r   r   )r   rc   r-  s      rW   username_stepr.    s     ~~//D88FB%%'D55GHII+D1KGK"  rY   z/select-usernamec                  .   [         R                  " 5       n U R                  SS5      R                  5       R	                  5       nU(       d  [        SSS.5      $ [        U5      (       d  [        SSS.5      $ U[        S'   S[        S	'   [        S
SS.5      $ )zHandle username selectionr   rM   FzUsername is requiredr   zUsername not availabletemp_usernamer   r   T/email-verificationr  )r   r   r]   r   r   r   r   r   )r   r   s     rW   select_usernamer2    s     Dxx
B'--/557H55KLMM **55MNOO'GO#*G t2GHIIrY   r1  c                  r   [         R                  S:X  a  [        S5      $ [         R                  " 5       n U R	                  S5      nUS:X  a  U R	                  SS5      R                  5       R                  5       nSU;  d  SU;  a  [        S	S
S.5      $ [        R                  R                  US9R                  5       (       a  [        S	SS.5      $ [        USS9nU[        S'   [        X#[        R                  " SS5      SS9(       a  [        SSS.5      $ [        S	SS.5      $ US:X  a  U R	                  SS5      R                  5       n[        R                  " S5      nU(       d  [        S	SS.5      $ [        X#SS9u  pEU(       a   S[        S'   S[        S'   [        SSS.5      $ [        S	US.5      $ g)z!Email verification step - UPDATEDr   zemail_verify.htmlr  r  r   rM   r  r  Fr  r   r  zEmail already registeredregistrationr  
temp_emailr,  r   TzVerification code sentzFailed to send emailr+   r  z$Session expired. Please start again.email_verifiedstudent_infor   r  N)r   r   r   r   r]   r   r   r   r   r   r   r   r*   r   r    r+   )r   r  r   r  r   r   s         rW   email_verificationr8    s    ~~233DXXhF"%++-335es%/u9OPQQ::e,2244u9STUU (H %"5K0P\jkt8PQRRu9OPQQ	=	 xx#))+L)u9_`aa (~N(,G$%+9G'(t.IJJuABB 
!rY   z/student-infoc                     [         R                  S:X  a)  S[        ;  a  [        [	        S5      5      $ [        S5      $ [         R                  " 5       n U R                  SS5      R                  5       nU R                  SS5      R                  5       nU R                  SS5      R                  5       nU R                  S	S5      R                  5       nU R                  S
S5      R                  5       nU R                  SS5      R                  5       n[        X4XV/5      (       d  [        SSS.5      $ XV:w  a  [        SSS.5      $ [        U5      u  pxU(       d  [        SUS.5      $ S[        ;  d  S[        ;  d
  S[        ;  a  [        SSS.5      $  [        R                  R                  [        S   S9R                  5       n	U	(       a  [        SSS.5      $ [        R                  R                  [        S   S9R                  5       n
U
(       a  [        SSS.5      $ [        [        S   [        S   [        S   UUUUSS9nUR!                  U5        ["        R                  R%                  U5        ["        R                  R'                  5         [)        SUR*                   35        UR,                  [        S'   UR*                  [        S'   S[        S'   UR/                  5         [        SSS S!.5      $ ! [0         am  n["        R                  R3                  5         [)        S"[5        U5       35        S#S$KnUR9                  5         [        SS%[5        U5       3S.5      s S$nA$ S$nAff = f)&z>Student information collection - UPDATED TO REDIRECT TO AVATARr   r   r   zstudent_info.htmlr   rM   r   ra   rd   r   r$  Fr   r   r%  r0  r5  r,  z1Session expired. Please start registration again.r   zUsername already taken.r  zEmail already registered.T)r   r   rc   r   r   ra   rd   is_verifiedu   ✅ User created successfully: r[   r   avatarr   zInformation saved/avatar-selection)r   r   r	   u   ❌ Registration error: r   NzRegistration failed: )r   r   r   r	   r
   r   r   r]   r   r   r   r(   r   r   r   r   r   r   r   r   rN   r   r   r   r   r   r   	traceback	print_exc)r   r   r   ra   rd   r   r$  r   r(  existing_userexisting_emailr\   r   r=  s                 rW   r7  r7    s    ~~'GM233233 DXXh#))+F88FB%%'DHHWb!'')EXXh#))+Fxx
B'--/Hxx 2B7==?;<<55NOPP#55MNOO/9H5]CDDg%W)D[bHb55hijj0X

,,go6N,OUUWu9RSTT--GL4I-JPPRu9TUVV _-,'%	
 	(#


t


/?@ "WW	"mm
'/#$ 
 *+
  	  X


(Q1257LSQRVH5UVWWXs.   AK< AK< #CK< <
M3A"M.(M3.M3r<  c                  (   S[         ;  a  [        [        S5      5      $ [        R                   R	                  [
        [         S   5      n U (       d  [        [        S5      5      $ U R                  (       a  [        [        S5      5      $ [        SU S9$ )zShow avatar selection pager[   r   r|   zavatar_selection.htmlr^   )r   r	   r
   r   r]   r   	avatar_idr   r^   s    rW   avatar_selectionrC  K  so     ())::>>$	 23D()) ~~,--2>>rY   z/save-avatarc                     S[         ;  a  [        SSS.5      S4$  [        R                  " 5       n U R	                  S5      nU R	                  S5      nU(       a  US;  a  [        SS	S.5      S
4$ U(       a
  U[
        ;  a  [        SSS.5      S
4$ [
        U   n[        R                   R	                  [        [         S   5      nU(       d  [        SSS.5      S4$ Xl        X$l	        X4l
        [        R                   R                  5         / SQnU H  n[         R                  " US5        M     [        SUR                   SU 35        [        SSUS.5      $ ! [         ac  n[        R                   R!                  5         [        S[#        U5       35        SSKnUR'                  5         [        SSS.5      S4s SnA$ SnAff = f)zSave user's selected avatarr[   Fr   r   r   genderrB  )malefemalezInvalid genderr   Invalid avatarr&  r   )r0  r5  r,  r   Nu   ✅ Avatar saved for user rH   TzAvatar saved successfullyr   r   avatar_emojiu   ❌ Error saving avatar: r   r   r   )r   r   r   r   r]   AVATAR_EMOJISr   r   rE  rB  rJ  r   r'  rN   r   r   r   r   r=  r>  )	r   rE  rB  rJ  r\   	temp_keyskeyr   r=  s	            rW   save_avatarrN  [  s    5_EFKK,K!(#HH[)	 '99u9IJKSPPI]:u9IJKSPP %Y/ zz~~dGI$67u9IJKSPP"(


 V	CKKT"  	*4==/L>JK2(
  	  K


)#a&235^DEsJJKs3   AE 0 E A
E A=E 
G$AG<GGz/change-avatarc                     S[         ;  a  [        SSS.5      S4$ [        R                  S:X  ar  [        R                   R                  [        [         S   5      n U (       d  [        SSS.5      S4$ [        S	U R                  U R                  U R                  S
.S.5      $  [        R                  " 5       nUR                  S5      nU(       a
  U[        ;  a  [        SSS.5      S4$ [        U   n[        R                   R                  [        [         S   5      n U (       d  [        SSS.5      S4$ X l        X0l	        [        R                   R                  5         [        SU R                   SU 35        [        S	SUS.5      $ ! [         aO  n[        R                   R!                  5         [        S[#        U5       35        [        SSS.5      S4s SnA$ SnAff = f)z.Allow user to change their avatar from profiler[   Fr   r   r   r   r&  r   T)rE  rB  rJ  )r   current_avatarrB  rH  r   u   ✅ Avatar changed for user rH   zAvatar updatedrI  u   ❌ Error changing avatar: r   r   N)r   r   r   r   r   r]   r   rE  rB  rJ  r   rK  r   rN   r   r   r   r   )r\   r   rB  rJ  r   s        rW   change_avatarrQ    s    5_EFKK~~zz~~dGI$67u9IJKSPP++!^^ $ 1 1
  	K!HH[)	I]:u9IJKSPP$Y/zz~~dGI$67u9IJKSPP"(


,T]]O2l^LM'(
  	  K


+CF8455^DEsJJKs.   "AF )A
F 4AF 
G!AGG!G!c                     S[         ;  a  [        SSS.5      S4$  [        R                  " 5       n U R	                  S5      nU R	                  S5      n[
        R                   R	                  [        [         S   5      nU(       d  [        SSS.5      S	4$ UR                  U5      (       d  [        SS
S.5      S4$ [        U5      u  pEU(       d  [        SUS.5      S4$ UR                  U5        [
        R                   R                  5         [        SSS.5      $ ! [         aO  n[
        R                   R                  5         [        S[        U5       35        [        SSS.5      S4s SnA$ SnAff = f)zChange user passwordr[   Fr   r   r   current_passwordr#  r&  r   zCurrent password is incorrectr   TzPassword changed successfullyu   ❌ Error changing password: zFailed to change passwordr   N)r   r   r   r   r]   r   r   r   r(   r   r   r   r   rN   r   )r   rS  r#  r\   r   r(  r   s          rW   change_passwordrT    sS   5_EFKKX!88$67xx/zz~~dGI$67u9IJKSPP ""#344u9XYZ\___ #4L"AuGH#MM 	,'


44STUU X


-c!fX6755PQRTWWWXs1   A8D %D ;#D <D 
E5&AE0*E50E5z/concept-selectionc                     S[         ;  a  [        [        S5      5      $ [        R                   R	                  [
        [         S   5      n U (       d  [        [        S5      5      $ [        R                  R                  U R                  U R                  S9R                  5       n[        R                  R                  U R                  S9R                  5       nU Vs0 s H  o3R                  U_M     nn[        SU UUS9$ s  snf )zConcept selection pager[   r}   ra   rd   r[   zconcept_selection.html)r\   conceptsprogress)r   r	   r
   r   r]   r   r   r   r   ra   rd   r   r   r   
concept_idr   )r\   rX  rY  pprogress_dicts        rW   concept_selectionr]    s     ())::>>$	 23D())}}&&TZZ&LPPRH$$..tww.?CCEH.67h\\1_hM73""*"/1 1 8s   Dz/ai-chat-responsec                  6   S[         ;  a  [        SSS.5      $  [        R                  " 5       n U R	                  SS5      R                  5       nU R	                  SS5      nU(       d  [        SSS.5      $ [        R                   R	                  [        [         S   5      n[        R                  R	                  S	5      =(       d    [        R                  " S	5      nU(       a  US
:X  a  [        SSS.5      $ [        UUUR                  US9nUS   (       a  [        SUS   US   S.5      $ [        SUR	                  SS5      S.5      $ ! [         aC  n[        S[!        U5       35        SSKnUR%                  5         [        SSS.5      s SnA$ SnAff = f)z5Handle AI chat messages with grade-specific responsesr[   Fr   r   r   rM   question_contextzEmpty message
AI_API_KEYyour-openai-api-key-herezAI chat not configured)user_messager_  
user_gradeapi_keyr   Tresponsera   )r   re  ra   zFailed to generate responseu   ❌ Chat endpoint error: r   Nr   )r   r   r   r   r]   r   r   r   appconfigosgetenvr)   ra   r   rN   r   r=  r>  )r   rb  r_  r\   rd  r   r   r=  s           rW   ai_chat_responserj    s    5_EFF,!xx	2.44688$6;uIJJzz~~dGI$67**...I"))L2I'%?? 3   +%-zz	
 )":.    !::i1NO  
  )#a&23%
  		s1   AE 6BE 84E -E 
F8FFFz/save-concept-selectionc                     S[         ;  a  [        SSS.5      $ [        R                  " 5       n U R	                  S/ 5      n[         S   n[
        R                   R	                  [        U5      n[        SU 35        [        SU 35         0 n[        R                  R                  US9R                  5        H  nXTUR                  '   M     [        S	[        U5       S
35        [        R                  R                  US9R                  SS05        U H  nXd;   a5  XF   nSUl        [         R"                  " 5       Ul        [        SU 35        M=  [        UUSSUR&                  SSSSS9	n[
        R                   R)                  U5        [        SU 35        M     [
        R                   R+                  5         [        S5        [        SS05      $ ! [,         am  n[
        R                   R/                  5         [        S[1        U5       35        SSKn	U	R5                  5         [        SS[1        U5       3S.5      s SnA$ SnAff = f)z3Save selected concepts with adaptive initializationr[   Fr   r   rX  u(   
📝 Saving concept selection for user z   Selected concepts: rW  z	   Found z existing progress recordsis_knownTu      ✓ Reactivated concept r   )	r[   rZ  rl  mastery_levelcurrent_difficulty_gradeconsecutive_correctconsecutive_incorrecttotal_attemptscorrect_attemptsu(      ✓ Created new progress for concept u    ✅ Concepts saved successfully
r   u   ❌ Error saving concepts: NzFailed to save selections: )r   r   r   r   r]   r   r   rN   r   r   r   r   rZ  lenupdaterl  r=   utcnowlast_updatedra   r   r   r   r   r   r=  r>  )
r   selected_conceptsr[   r\   existing_progressprogrZ  rY  r   r=  s
             rW   save_concept_selectionrz  0  s    5_EFFDR0i G::>>$(D	5gY
?@	"#4"5
67,^#))33G3DHHJD15doo. K 		#/011KLM 	'''8??U@ST ,J.,8$(!(0(9%3J<@A +#)!"#-1ZZ()*+#$%&
 

x(@MN+ ,. 	

13	4()) ^


+CF84557RSVWXSYRZ5[\]]^s    
EG 
I
A"I?I
I
z/assessmentc                     S[         ;  a  [        [        S5      5      $ [        R                   R	                  [
        [         S   5      n [        R                  R                  U R                  SS9R                  [        5      R                  5       nU(       d  [        S5        [        [        S5      5      $ [        SXS9$ )	zAssessment pager[   r}   Tr[   rl  zPlease select concepts firstr]  zassessment.html)r\   rX  )r   r	   r
   r   r]   r   r   r   r   r   joinr   r   r   r   )r\   rw  s     rW   
assessmentr~  m  s     ())::>>$	 23D'--77$ 8 
d7mCCE  ,- 3455,4TTrY   z/generate-questionsc            
         S[         ;  a  [        SSS.5      $ [        R                   R                  [        [         S   5      n [
        R                  R                  U R                  SS9R                  5       nU(       d  [        SSS.5      $ / nU HK  n[        R                   R                  [        UR                  5      nU(       d  M:  UR                  U5        MM     [        SS	 35        [        S
5        [        S	 5        [        SU R                   SU R                   S35        [        SU Vs/ s H  oUR                   PM     sn 35         SSKJn  / nS['        U5      -  nS['        U5      -  n	[)        U5       GH  u  pXU	:  a  SOS-   n[
        R                  R                  U R                  UR                  S9R+                  5       nU(       a  UR,                  OSnU(       a  UR.                  OSnUS:  a  SnOUS:  a  SnOUS:  a  SnOSn[        SUR                    35        [        SU 35        [        SU 35        [0        R2                  " U R                  UR                   5      n[5        5       nU" U R6                  U R                  UR                   SSSS9nU H7  n[9        US   5      U;   d  M  UR;                  UR                  S 5      5        M9     U" U R6                  U R                  UR                   UUUS9nU(       a,  [        S!['        U5       S"35        UR=                  U5        GM  [        S#5        GM     ['        U5      S$:  a  [?        S%['        U5       S&35      e[@        RB                  " U5        USS [         S''   S[         S('   [        S)['        USS 5       S"35        [        S	 S35        [        SUSS S*.5      $ s  snf ! [D         aL  n[        S+[G        U5       35        SSK$nURK                  5         [        S[G        U5      S.5      s SnA$ SnAff = f),u)   
✅ PROGRESSIVE ASSESSMENT - JSON BASED
r[   Fr   r   Tr|  No concepts selectedrD   P================================================================================u'   🎯 ASSESSMENT - JSON BASED GENERATIONzUser: z (Grade )z
Concepts: r   load_questions_from_json   rG   )r[   rZ  rF   easy(   mediumF   hardu   
📚 Concept: z
   Quota: z   Difficulty: Nrd   ra   concept_name
difficultycountexclude_idsrI   r   u      ✅ Got 
 questionsu      ❌ No questions found!
   Only z questions generatedcurrent_questionsassessment_is_adaptiveu   
✅ Assessment Ready: r   rP      ❌ Error: )&r   r   r   r]   r   r   r   r   r   r   r   rZ  r   rN   r   ra   rc   utils_json_loaderr  rs  rO   r   rm  rp  r   get_asked_questionssetrd   r'   r   extend
ValueErrorru   shuffler   r   r=  r>  )r\   selected_progressrw  ry  conceptr   r  all_questionsquestions_per_concept	remainingrR   quotarY  masteryconsecutive_wrongr  asked_hashesr  temp_questionsrS   concept_questionsr   r=  s                          rW   generate_questionsr    s    5_EFF::>>$	 23D (--77$ 8 	ce  55KLMM!**..$//:7$$W- "
 
Bvh-	35	VH	F4==/$**Q
78	J(9:(91(9:;
<=Z>> "c*;&< <.//	%&78LC)	/QqIE ',,66":: 7  eg 
 19h,,aGBJ > >PQ !A%#
2%
2%
#
$W\\N34Jug&'OJ<01 +>>twwUL %K5{{jj$\\ N $ :/<?OOAEE$K0 $
 !9{{jj$\\%'! !C(9$:#;:FG$$%6724u 9x }"uS%7$88LMNN 	}% (5Sb'9#$,0()(]3B-?)@(ALMm&s+
  	g ;p  >CF8$%5SV<==	>s-   7O%
E/O* 	DO* *
Q 4AP;5Q ;Q z/api/test-keyc                     [         R                  R                  S5      =(       d    [        R                  " S5      n U (       a  U S:X  a  [        SSS.5      $  SSKnSU  3S	S
.nUR                  SUSSSS./SS.SS9nUR                  S:X  a  [        SSS.5      $ [        SSUR                   3UR                  SS S.5      $ ! [         a!  n[        S[        U5      S.5      s SnA$ SnAff = f)zTest if OpenAI API key worksr`  ra  FAPI key not configured)validr   r   NzBearer zapplication/json)AuthorizationzContent-Typez*https://api.openai.com/v1/chat/completionszgpt-3.5-turbor\   zSay 'OK')r   content   )modelmessages
max_tokensr  )headersjsontimeoutr   TzAPI key works!)r  r   zAPI returned )r  r   details)rf  rg  r]   rh  ri  r   requestspoststatus_codetextr   r   )rd  r  r  re  r   s        rW   test_api_keyr    s    jjnn\*Ebii.EGg!;;-
  	
:  'wi0.
 ==8(&,DE
  ! 	
 3&T6FGHH()=)=(>?#==#.    :Q899:s%   AC (C 
C1C,&C1,C1c           	      d   0 nSU ;   a  U S   R                  5        H  u  p#US   S:  a  US   US   -  S-  OSnUS:  a  SnSnS	nS
U S3SSS/nO?US:  a  SnSnSnSU S3SSS/nO(US:  a  SnSnSnU S3SSSS /nOS!nS"nS#nU S$3S%S&S'S(S)/nUUU[        US*5      US   US   US+.X'   M     U$ ),z4Generate AI-powered recommendations for each conceptconcept_performancetotalr   correctrt   P   	excellentu   🌟z#5cb85czOutstanding work on z! You've mastered this topic.z2Challenge yourself with advanced practice problemsz5Consider helping peers who struggle with this conceptz-Explore real-world applications of this topic<   goodu   👍z#5bc0dezGood progress in z! You're on the right track.z6Practice 5-10 more questions to solidify understandingz-Review incorrect answers to identify patternsz1Focus on understanding the 'why' behind solutionsr  needs_improvementu   📚z#f0ad4ez3 needs more attention. Don't worry, practice helps!z7Start with easier difficulty levels to build confidencez.Break down complex problems into smaller stepsz1Spend 15-20 minutes daily practicing this conceptz2Watch tutorial videos or read concept explanationsurgentu   🎯z#d9534fz, requires focused practice. You can do this!z2Start with fundamental concepts and basic examplesz7Practice 10-15 questions daily until you feel confidentz3Seek help from teachers or tutors for clarificationz;Use visual aids and real-life examples to understand betterz'Review step-by-step solutions carefullyrG   )leveliconcoloraccuracyr  r  tips)itemsround)	analysisrecommendationsr  r   r  r  r  r  r  s	            rW    generate_concept_recommendationsr  '  s]   O(%&;<BBDMGBFw-RSBSY$w-7#=YZH 2~#!*7)3PQHKC	 R!'y0LMLCG	 R+!iRSMDGH !!iKLHMIQ= !(A.	?g(O$a Et rY   z/submit-assessmentc                  	   S[         ;  a  [        SSS.5      $ [        R                  " 5       n U R	                  S0 5      nU R	                  S0 5      n[         R                  " S/ 5      nU(       d  [        SSS.5      $  [         S   n[
        R                   R	                  [        U5      n0 nS	S	S	S
.nUR                  5        H	  u  pXU'   M     UR                  5        H  u  p[        U5      nX;   nUS==   S-  ss'   U
R	                  SS5      nU
R	                  SS5      nU(       a+  US   Xh'   US==   S-  ss'   [        SUS-    SU S35        Mw  SXh'   US==   S-  ss'   [        SUS-    SU S35        M     [        X65      nUS   nUS   n[        UU5      n[        S5        [        SU 35        [        SU 35        [        SU S35        [        S US    S!US    S"US    S#35        S	nS	nUS$    HH  nUR	                  S%S&5      n[        U5      nUU-  nUS   (       a  UU-  n[        UUS'   US   U5        MJ     [        R                  R!                  US(S)9R#                  5       n[%        UUUUUUS(S*9nUR'                  U Vs/ s H  nUR(                  PM     sn5        UUUUUS$   US+   US,   US-   UUS..
nUR+                  U5        [
        R                   R-                  U5        [
        R                   R/                  5         US$    Hx  n[1        UR2                  US'   UR	                  S%S&5      US/   US   US   (       a  [        UR	                  S%S&5      5      OS	S09n[
        R                   R-                  U5        Mz     [
        R                   R/                  5         [5        UU5      n[7        U5      nUR2                  [         S1'   [        S(UUUUUUS   US   US   U(       a  UR8                  OS2U(       a  UR:                  OS2U(       a  UR<                  OS2U(       a  UR>                  OS2U(       a  UR@                  OS2S3.UUS,   US-   S4.S5.5      $ s  snf ! [B         am  n[
        R                   RE                  5         [        S6[G        U5       35        S	S2K$n U RK                  5         [        SS7[G        U5       3S.5      s S2nA$ S2nAff = f)8z,Submit assessment with typed answers supportr[   Fr   r   answerstyped_answersr  zNo active assessmentr   )r  r  wrongr  rG   answerrM   
is_correctrL   r  u   ✅ Qz	: Typed 'z' - CORRECTr  u   ❌ Qz	' - WRONGtotal_correcttotal_answeredu   
📊 ASSESSMENT SUMMARY:z   Total Questions: z   Correct: z
   Score: %z   Typed Answers: z (z
 correct, z wrong)resultsdifficulty_levelr  r  Tr|  )r[   total_questionscorrect_answersscore_percentagetotal_pointsmax_possible_pointsis_adaptiver  weak_conceptsr  )
rP   r  r  typed_answers_summaryr  r  r  r  r  r  rI   )assessment_idr  r  question_textr  points_awardedcurrent_assessment_idNr   r   statenationalworld)r  r  )r   scorer  r  points
max_pointstyped_answers_counttyped_correcttyped_wrongrankingeligibilityr  u   ❌ Error saving assessment: zFailed to save assessment: )&r   r   r   r   r]   r   r   r  intrN   r%   r#   r6   r2   r   r   r   r   r   set_concepts_testedrZ  set_questions_datar   r   r<   r   r1   r8   school_rank	city_rank
state_ranknational_rank
world_rankr   r   r   r=  r>  )!r   r  r  rP   r[   r\   all_answersr  rM  value
typed_dataquestion_idxrI   user_typed_textr  r  correct_countr  r  r  r  r   r  r  rw  r~  cpquestions_dataquestion_entryr  r  r   r=  s!                                    rW   submit_assessment_enhancedr  i  sm    5_EFFDhhy"%GHH_b1M/4I55KLMM[^)$zz~~dG, !
 "--/JC$ *  -224OCs8L .H!'*a/* )nnXr:O#e<J#+,<#= %i0A50lQ./y8IUV $& %g.!3.lQ./y8IST'  5, .iE 1"#342=/R*,$_$567]O,-
+,A./"#8#A"B"EZ[dEeDffp  rG  HO  rP  qQ  QX  Y  	Z y)F$6AJ.z:F6)l#& 3y!|$	 *" ,11;;d < 

#% 	  +)-% 3

 	&&@Q'R@Q"@Q'RS #"*%:	*#+,A#B%o6'(9:(#6
 	%%n5


z"


 y)F%(mm#I.!',>!I$Z0!,/flmyfz8DVX`9ab  ABN JJNN>* * 	

 &g|<27;+5=='(%$$"-#8#A29=0918'--d-4))$/6++D5<G11$/6++D '!)/!:#+,=#>%
  	Q (S@  ^


-c!fX6757RSVWXSYRZ5[\]]^s3   ?HQ7 Q2,GQ7 2Q7 7
S.A"S)#S.)S.z/verify-typed-answerc            
         S[         ;  a  [        SSS.5      S4$  [        R                  " 5       n U R	                  S5      nU R	                  S5      nU R	                  SS	5      nU R	                  S
5      nU(       a  U(       d  [        SSS.5      S4$ [        SS 35        [        S5        [        S 5        [        SU 35        [        SU 35        [        SU 35        [        R                  R	                  S5      =(       d    [        R                  " S5      nU(       a  US:X  a  [        SSS.5      S4$ SSK
Jn  U" UUU5      nUS   (       a@  [        S5        [        SUS    35        [        SSUS   UR	                  SS5      S S!.5      $ [        S"5        [        S#UR	                  S$S%5       35        [        SSUS   UR	                  S$S5      UR	                  S&S'5      S(.5      $ ! [         aE  n[        S)[        U5       35        SS*Kn	U	R                  5         [        SS+S.5      S4s S*nA$ S*nAff = f),z%
Verify user's typed answer using AI
r[   Fr   r   r   rI   user_answerr  Mathematicsquestion_indexz Question and answer are requiredr   rD   rE   u   🔍 VERIFYING TYPED ANSWERz
Question: zUser Answer: 	Concept: r`  ra  zAI verification not availabler   r   )verify_user_typed_answerr  u   ✅ Answer VERIFIED as CORRECTz   Confidence: 
confidenceTexplanationrM   zYour answer is correct!)r   r  r  r  r   u   ❌ Answer INCORRECTz   Reason: reasonzDoes not matchr   z$Answer does not appear to be correct)r   r  r  r  r   u"   ❌ Error verifying typed answer: Nz*Failed to verify answer. Please try again.)r   r   r   r   r]   rN   rf  rg  rh  ri  utilsr
  r   r   r=  r>  )
r   r  r  r  r  rd  r
  verification_resultr   r=  s
             rW   verify_typed_answerr    sk   
 5_EFKKD!,hh}-((9m4"23K =   
 	6(m+-
=/*+k]+,	'#$**...I"))L2I'%?? :    	36
 |,24O$7$E#FGH"1,?266}bI4   (*K 3 7 7BR STUV#1,?-11(B?.229>de    23q6(;<C
   	s3   A7G3 B'G3 <AG3 AG3 3
I=:H=7I=Iz/submit-practice-answerc                  x   S[         ;  a  [        SSS.5      $ [        R                  " 5       n U R	                  S5      nU R	                  S5      nU R	                  SS5      nU R	                  S	S
5      nU(       a  Uc  [        SSS.5      $  [         S   n[        UUUU5      nU(       a  [        U5      OSnUS:  a  [        XQU5      n[        R                  R                  UUS9R                  5       n	SU	(       a  U	R                  OSU	(       a  U	R                  OSU	(       a  U	R                  OSUR	                  SS5      S.UUS   S.n
US   (       a  SSUS   S SU S3US.U
S'   [        U
5      $ ! [         a8  n[!        S[#        U5       35        [        S[#        U5      S.5      s SnA$ SnAff = f)z3Submit SINGLE practice answer with attempt trackingr[   Fr   r   r  r  r  r  attempt_numberrG   NzInvalid datar   r[   r  Tmastery_change)practice_masterypractice_attemptspractice_correctr  eligible)r   r  r  r  u   🎉 Eligible for Assessment!zYou have achieved r  .1fz% mastery in !)titler   r  notificationu   ❌ Error updating practice: )r   r   r   r   r]   r3   r6   r4   r:   r   r   r   r  r  r  r   rN   r   )r   r  r  r  r  r[   eligibility_resultr  practice_rankr  re  r   s               rW   submit_practice_answerr  a  s    5_EFFD88I&L,'J,1JXX.2N:-5^DEE0>)$ B	
 ;E*:6! A:3G6RM !&&00% 1 
 %' 	 @GG$<$<QBIW%>%>q@GG$<$<Q"4"8"89I1"M	 *:6

 j)8/0B90Mc/RR_`l_mmno'(H^$ x   >-c!fX675SV<==>s   C)E7 7
F9-F4.F94F9z/api/top-rankingsc            
      :   S[         ;  a  [        SS05      $  [        R                   R                  [        [         S   5      n U (       d  [        SS05      $ [
        R                  R                  U R                  S9R                  5       nU(       di  [        U R                  U R                  U R                  SSSS9n[        R                   R                  U5        [        R                   R                  5         [
        R                  R                  U R                  S	9R                  [
        R                  R!                  5       5      R#                  S
5      R%                  5       n[
        R                  R                  U R                  S9R                  [
        R                  R!                  5       5      R#                  S
5      R%                  5       n[
        R                  R                  SS9R                  [
        R                  R!                  5       5      R#                  S
5      R%                  5       n[
        R                  R                  [
        R                  R!                  5       5      R#                  S
5      R%                  5       nS n[        U R&                  U R(                  =(       d    SUR*                  UR,                  UR.                  UR0                  UR                  S.U" X R                  5      U" X0R                  5      U" X@R                  5      U" XPR                  5      S.5      $ ! [2         aM  n[5        S[7        U5       35        SSKnUR;                  5         [        S[7        U5      05      S4s SnA$ SnAff = f)z,Get top 5 students for each ranking categoryr[   r   r   r&  rW  Maharashtrar   r[   r   	city_name
state_nametotal_scoretotal_assessments)r   r  )r#  )r$  c                 d   / n[        U S5       H  u  p4[        R                  R                  [        UR
                  5      nU(       d  M<  UR                  UUR                  UR                  UR                  =(       d    SUR                  UR                  UR
                  U:H  S.5        M     U$ )NrG      👤)rankrc   r   r;  r  assessmentsis_current_user)rO   r   r   r]   r   r[   r   rc   r   rJ  r%  r&  )rankingsr[   r   rR   r)  user_objs         rW   format_rankings)api_top_rankings.<locals>.format_rankings  s    F&x3	::>>$=8MM # ($,$5$5"*"7"7"A6!%!1!1'+'='=+/<<7+B#  4 MrY   r(  )rc   r;  r  r  r  r  r%  )current_userr   r   r  r  u   ❌ Error in top_rankings: Nr   )r   r   r   r]   r   r9   r   r   r   r   r   r   r   r   order_byr%  desclimitr   rc   rJ  r  r  r  r  r   rN   r   r=  r>  )	r\   user_ranking
school_topcity_top	state_topnational_topr.  r   r=  s	            rW   api_top_rankingsr9    s    122K/zz~~dGI$67G%5677"((224772CIIK& KK))("#L JJNN<(JJ !&&00 1 

(;**//1
2558CCE 	
 $$..ii / 

(;**//1
2558CCE 	
  %%//$ 0 

(;**//1
2558CCE 	
 #((11##((*

%(335 		  		++5v+77)33*55!-!;!;+77 &j'':#Hgg6$Y8'gg>
  	   /+CF845Q()3..	/s%   >M K*M 
NANNNz/resultsc                     S[         ;  a  [        [        S5      5      $ [         R                  " S5      n U (       d  [        [        S5      5      $ [        R                   R                  [
        U 5      nU(       d  [        [        S5      5      $ [        R                   R                  [        [         S   5      n[
        R                  R                  UR                  S9R                  [
        R                  5      R                  5       nUR                  5       n[        U5      n[        5       nUS:X  a  SnOSn[!        UUUUUS	9$ )
z1Assessment results page with account type supportr[   r}   r  r]  rW  r   zstudent_results.htmlzresults.html)r~  r\   all_assessmentsr  )r   r	   r
   r]   r   r   r   r   r   r   r1  completed_atr   get_questions_datar  r   r   )r  r~  r\   r;  r  r  r   template_names           rW   r  r    s
    ())KK 78M 3455
M:J 3455::>>$	 23D !&&000AJJ:KbKbcggiO  224N6~FO $%Ly .&=$.")8)8	: :rY   z/gamified-practicec                      S[         ;  a  [        [        S5      5      $ [        R                   R	                  [
        [         S   5      n U (       d  [        [        S5      5      $ [        SU S9$ )zGamified practice pager[   r}   zgamified_practice.htmlr^   )r   r	   r
   r   r]   r   r   r^   s    rW   gamified_practicer@    sV     ())::>>$	 23D())3$??rY   z/generate-gamified-questionsc            	         S[         ;  a  [        SSS.5      $  [        R                  " 5       n U R	                  SS5      nU R	                  SS5      nU R	                  S	S
5      nU R	                  S5      n[
        R                   R	                  [        [         S   5      nSSSSSSS.nUR	                  US5      nU(       a  UnO[        R                  R                  UR                  SS9R                  5       n	U	(       aD  [
        R                   R	                  [        U	R                  5      n
U
(       a  U
R                  OSnOSn[        SS 35        [        S5        [        S 5        [        SU 35        [        SU 35        [        SU 35        [        SU 35        SSKJn  U" UR$                  UR&                  UUUS-   SS9nU(       a9  [)        U5      U:  a*  [        S[)        U5       S35        [        SUSU US.5      $ [+        S [)        U5       S!35      e! [,         a8  n[        S"[/        U5       35        [        S[/        U5      S.5      s SnA$ SnAff = f)#u$   
✅ GAMIFIED PRACTICE - JSON BASED
r[   Fr   r   r  r  r     r  r  r  r  r  )simpler  moderater  r  	very_hardTr|  r  rD   rE   u   🎮 GAMIFIED PRACTICE - JSONzLevel: zDifficulty: r	  zCount: r   r  Nr  u   ✅ Loaded r  )r   rP   practicing_conceptr  z questions availabler  )r   r   r   r   r]   r   r   r   r   r   r   r   r   rZ  rc   rN   r  r  rd   ra   rs  r  r   r   )r   r  difficulty_numr  target_conceptr\   level_to_difficultyr  r  r  r  r  rP   r   s                 rW   generate_gamified_questionsrJ  +  sI    5_EFFE>!&),2!$),zz~~dGI$67  
 ),,UH=
 )L !0 5 5 ? ?$ !@ !eg  !**..2C2N2NO/6w||M,6(m-/w ZL)*	,()w  	?,;;**%!!)
	 Y50KI/z:;&v.&2   uS^$44HIJJ >CF8$%5SV<==>s$   G3H& H& &
I(0-I#I(#I(z/api/chart-datac                  (   S[         ;  a  [        SS05      $ [         S   n [        R                  R	                  U S9R                  [        R                  5      R                  5       nU(       d  [        / / S./ S.5      $ U Vs/ s H  o"R                  PM     nnU Vs/ s H  o"R                  R                  S5      PM     nn0 n[        R                  R	                  U S9R                  5       nU HL  nUR                  nX;  a  SSS	.XX'   XX   S
==   S-  ss'   UR                  (       d  M=  XX   S==   S-  ss'   MN     U(       d  U H  n	U	R                  5       n
SU
;   aN  U
S   R                  5        H5  u  pX;  a  SSS	.XX'   XX   S==   US   -  ss'   XX   S
==   US
   -  ss'   M7     Mg  SU
;   d  Mo  U
S    HK  nUR                  SS5      nX;  a  SSS	.XX'   XX   S
==   S-  ss'   US   (       d  M<  XX   S==   S-  ss'   MM     M     / nUR                  5        H>  u  pUS
   S:  d  M  [!        US   US
   5      nUR#                  UUUS   US
   S.5        M@     UR%                  S S9  [        UUS.US.5      $ s  snf s  snf )z1Get chart data for results with adaptive analysisr[   r   r   rW  )labelsr   )progress_chartconcept_chartz%m/%dr   )r  r  r  rG   r  r  r  r  Unknownr  )r  
percentager  r  c                     U S   $ )Nr  rx   xs    rW   <lambda>chart_data.<locals>.<lambda>  s    AiLrY   )rM  )r   r   r   r   r   r1  r<  r   r  strftimer   r  r  r=  r  r]   r#   r   sort)r[   r*  ascoresdatesr  all_historyhistory_entryr  r~  r  r   r   concept_datarP  s                  rW   
chart_datar^  z  s    122i G"",,W,=FFzG^G^_cceK)+R8
  	 +66+Q  +F67BC{!^^$$W-{EC  "''11'1BFFHK$,,-781+E($W-2-###(3q83 % %J'::<N$6%34I%J%P%P%RMG9CDq7Q+4'0;tIN;'09T']J9	 &S n,,Y7F$jjI>G9CDq7Q+4'09Q>9l+++4Y?1D? 8 &* L,224=10i$w-PJ"(	?g	!  5 01
 &  o 7Cs   J
 $Jz/api/config-checkc                      [         R                  R                  S5      =(       d    [        R                  " S5      n [        U =(       a    U S:g  5      n[        UU(       a  SS.5      $ SS.5      $ )z'Check if API key is properly configuredr`  ra  zAPI key configuredr  )api_configuredr   )rf  rg  r]   rh  ri  boolr   )rd  is_configureds     rW   config_checkrc    sf     jjnn\*Ebii.EGJW0J%JKM'+8'  >V  rY   z
/dashboardc                     S[         ;  a  [        [        S5      5      $ [        R                   R	                  [
        [         S   5      n U (       d  [        [        S5      5      $ [        5       nUS:X  a  [        U 5      $ [        U 5      $ )z,Enhanced dashboard with account type supportr[   r}   r   )	r   r	   r
   r   r]   r   r   render_student_dashboardrender_parent_dashboard)r\   r   s     rW   r|   r|     sp     ())::>>$	 23D()) $%Ly '--&t,,rY   c                    [         R                  R                  U R                  S9R	                  5       nUS:  Ga  [         R                  R                  U R                  S9R                  5       n[        S U 5       5      [        U5      -  n[        R                  R                  U R                  S9R	                  5       n[        R                  R                  U R                  SS9R	                  5       nUS:  a  [        XT-  S-  S5      OSnU[        US5      U[        R                  R                  U R                  SS9R	                  5       S	.nOSSSSS	.n[        S
XS9$ )z#Render simplified student dashboardrW  r   c              3   8   #    U  H  oR                   v   M     g 7fNr  .0rX  s     rW   	<genexpr>+render_student_dashboard.<locals>.<genexpr>       @Kq**K   Tr[   r  rt   rG   r|  )r&  average_scorer  total_conceptszstudent_dashboard.htmlr\   stats)r   r   r   r   r  r   sumrs  r   r  r   r   )r\   r&  r*  	avg_scorer  correct_questionsr  ru  s           rW   re  re    sH    #((224772CIIK1 &&000AEEG@K@@3{CSS	)//99$''9JPPR+11;;DGGX\;]cceL[^_L_5+=CaHef "3"9a0 -33==dggX\=]cce	
 "#	
 3$LLrY   c                    U R                   n[        R                  R                  US9R	                  5       n[
        R                  R                  US9R                  5       nU(       d_  [        UU R                  U R                  SSSS9n[        R                  R                  U5        [        R                  R                  5         US:  GaL  [        R                  R                  US9R                  5       n[        S U 5       5      [        U5      -  n[        R                  R                  US9R!                  [        R"                  R%                  5       5      R                  5       n[&        R                  R                  USS9R                  5       nSSSS.n[(        R                  R                  US9R                  5       n	U	(       aU  U	 HN  n
U
R*                  S	:  a  US
==   S-  ss'   M"  U
R*                  S:  a  US==   S-  ss'   MA  US==   S-  ss'   MP     OTU HN  nUR,                  S	:  a  US
==   S-  ss'   M"  UR,                  S:  a  US==   S-  ss'   MA  US==   S-  ss'   MP     [.        R                  R                  US9R	                  5       n[.        R                  R                  USS9R	                  5       nU[1        US5      U(       a  UR2                  OS[        U5      UUUUS:  a  [1        X-  S-  S5      OSS.nOSSSSSSSS.SSSS.nSSKJn  U R6                  (       a  UR8                  " 5       U R6                  -
  nUR:                  S:  a%  UR:                   SUR:                  S:  a  SOS S3nOUUR<                  S-  S:  a   UR<                  S-  nU SUS:  a  SOS S3nO"UR<                  S-  nU SUS:  a  SOS S3nOSn[?        SU UUUS9$ )z1Render full parent dashboard (existing dashboard)rW  r!  r   r"  c              3   8   #    U  H  oR                   v   M     g 7fri  rj  rk  s     rW   rm  *render_parent_dashboard.<locals>.<genexpr>  ro  rp  Tr|  )masteredlearning
needs_workr  r|  rG   rJ   r}  r~  rq  rt   )r&  rr  latest_scorers  mastery_statsr  rx  r  )r=    daysrM    ago   hourr   minutezFirst time loginzdashboard.html)r\   ru  	last_seenr  ) r   r   r   r   r  r9   r   r   r   r   r   r   r   r   rv  rs  r1  r<  r2  r   r:   overall_masteryrm  r   r  r  r=   
last_loginru  dayssecondsr   )r\   r[   r&  r  r*  rw  latest_assessmentrw  r  concept_masteriesr  rY  r  rx  ru  r=   	time_diffr  hoursminutess                       rW   rf  rf    s   
 ggG #((2272CIIK ))'):@@BGii$
 	

w


1 &&000AEEG@K@@3{CSS	&,,66w6GPPQ[QhQhQmQmQopvvx+11;;GVZ;[__a 
 +00::7:KOOQ,**b0!*-2-,,2!*-2-!,/14/ - .))R/!*-2-++r1!*-2-!,/14/ . *//99'9JPPR+11;;GX\;]cce "3"9a0BS->>YZ!"34*.!2Q`cdQd0BSH1Mjk	
 "#*+!L !"	
 "OO%7	>>A$>>*$innq6Hsb.QQUVI$&*%%-E 'eaisR&@EI''2-G")7'A+32*FdKI&	+"$#,!(	* *rY   r  u!   ✅ AVATAR INTEGRATION CODE READYz
NEXT STEPS:zB1. Run database migration: flask db migrate -m 'Add avatar fields'z$2. Apply migration: flask db upgradez(3. Create avatar_selection.html templatez4. Create profile.html templatez'5. Update dashboard.html to show avatarz)6. Update base.html navbar to show avatarz/api/recent-activityc                     SW ;  a  [        / 5      $ U S   n/ n[        R                  R                  US9R	                  [        R
                  R                  5       5      R                  S5      R                  5       nU H@  nUR                  SSUR                  S S3UR
                  R                  S5      S	.5        MB     [        R                  R                  US9R	                  [        R
                  R                  5       5      R                  S
5      R                  5       nU H?  n UR                  SSU R                   S3U R
                  R                  S5      S	.5        MA     UR                  S SS9  [        USS 5      $ )z)Get recent activity for student dashboardr[   rW  rF   u   📝zCompleted assessment with r  z% scorez%b %d, %H:%M)r  r  r   rB  u   🎮zPractice session: z levelc                     U S   $ )Nr   rx   rR  s    rW   rT  !recent_activity.<locals>.<lambda>  s    !F)rY   T)rM  reverseNr  )r   r   r   r   r1  r<  r2  r3  r   r   r  rV  r   r  rW  )r   r[   
activitiesrecent_assessmentsr~  recent_practices         rW   recent_activityr  r  sg    r{i GJ $))33G3D	*))..0	1	q##%  )
01L1LS0QQXY++44^D
 	 ) &++55g5F	/..335	6	q##%  #(v>((11.A
 	 # OO+TO::bq>""rY   z/api/user-rankingc            
         S[         ;  a  [        SS05      $ [        R                  R	                  [         S   S9R                  5       n U (       d  [        SSSSSSS.S.5      $ [        U R                  U R                  U R                  U R                  U R                  U R                  U R                  S.S	.5      $ )
zGet user's current rankingr[   r   r   rW  r   Nr  )r%  r,  )r%  r&  r,  )r   r   r9   r   r   r   r%  r&  r  r  r  r  r  )r  s    rW   api_user_rankingr    s     122))')2D)EKKMG 	
 	 		 **$66))%%''--''

 
 
rY   z/api/grade-concepts-analysisc                     S[         ;  a  [        SSS.5      $  [        R                   R                  [        [         S   5      n U (       d  [        SSS.5      $ [
        R                  R                  U R                  U R                  S9R                  5       n0 n[        R                  R                  U R                  S9R                  5       nU H_  nUR                  UR                  UR                  UR                   UR"                  UR$                  UR&                  S.X$R(                  '   Ma     / n[+        U5      nS	nS	nS	n	U GH  n
UR                  U
R,                  0 5      nUR                  S
S	5      nUR                  SS	5      S	:  =(       d    UR                  SS	5      S	:  nU(       a  US-  nUS:  a  US-  nX-  n	UR/                  U
R,                  UUR                  SS	5      UR                  SS	5      UR                  SS	5      UR                  SS	5      UR                  SS	5      UR                  SS5      [1        X5      S.	5        GM     US	:  a  X-  OS	n[        SUUU[3        US5      US.5      $ ! [4         aC  n[7        S[9        U5       35        S	SKnUR=                  5         [        SSS.5      s SnA$ SnAff = f)z$Get complete grade concepts analysisr[   Fr   r   r&  rV  rW  )assessment_masteryr  r  assessment_attemptsr  r  is_eligibler   r  r  r  rG   r  r  r  r  r  )	r  r  r  r  r  r  r  r  statusT)r   rs  practiced_conceptscleared_conceptsoverall_progressrX  z"Error in grade concepts analysis: Nr   )r   r   r   r]   r   r   r   r   ra   rd   r   r:   r   r  r  r  r  r  r  is_eligible_for_assessmentr  rs  rc   r   get_mastery_statusr  r   rN   r   r=  r>  )r\   grade_conceptsuser_masterymastery_recordsrecordconcepts_datars  r  r  total_mastery_sumr  mastery_datar  has_attemptsr  r   r=  s                    rW   api_grade_concepts_analysisr    s    5_EFFMFzz~~dGI$67u9IJKK !00**;; 1 
 #% 	 (..888IMMO%F&,&?&?$*$;$;#)#9#9'-'A'A%+%=%=$*$;$;%@@1L,,- & ^,%G'++GLL"=L*../@!DO   !6:Q> =  !4a81< 
 "a'""$ A% 0   '*&2&6&67KQ&O$0$4$45G$K'3'7'78Mq'Q%1%5%56I1%M$0$4$45G$K+//uE,_K
" 
% &> BPRSAS,=YZ,"4 0 %&6 :%
  	  F23q6(;<5^DEE	Fs$   ?J H)J 
K8KKKc                 0    U(       d  gU S:  a  gU S:  a  gg)z+Helper function to determine mastery statusnot_startedr  r|  rJ   in_progressr~  rx   )r  r  s     rW   r  r  	  s    	B	BrY   z#/api/concept-mastery/<concept_name>c                 (   S[         ;  a  [        SSS.5      $  [         S   n[        R                  R	                  UU S9R                  5       nU(       aZ  [        SUR                  UR                  UR                  UR                  UR                  UR                  UR                  S.5      $ [        SSSSSSSSS.5      $ ! [         aC  n[        S	[        U5       35        SS
KnUR#                  5         [        SSS.5      s S
nA$ S
nAff = f)z'Get mastery data for a specific conceptr[   Fr   r   r  T)r   r  r  r  r  r  r  r  r   zError getting concept mastery: Nr   )r   r   r:   r   r   r   r  r  r  r  r  r  r  r   rN   r   r=  r>  )r  r[   r  r   r=  s        rW   api_concept_masteryr  	  s'    5_EFF%F)$ !&&00% 1 
 %' 	
 &-&@&@$+$<$<#*#:#:'.'B'B%,%>%>$+$<$<&AA	 	 	 &'$%#$'(%&$%$	 	 	  F/Ax895^DEE	Fs$   BC 0C 
D8DDDz/profilec                     S[         ;  a  [        [        S5      5      $ [        R                   R	                  [
        [         S   5      n U (       d  [        [        S5      5      $ [        R                  R                  U R                  S9R                  5       nUS:  a  [        R                  R                  U R                  S9R                  5       n[        S U 5       5      [        U5      -  nU[        US5      [        R                  R                  U R                  SS9R                  5       S	.nOSSSS	.n[!        S
XS9$ )zUser profile pager[   r   rW  r   c              3   8   #    U  H  oR                   v   M     g 7fri  rj  rk  s     rW   rm  profile.<locals>.<genexpr>R	  ro  rp  rG   Tr|  )r&  rr  rs  zprofile.htmlrt  )r   r	   r
   r   r]   r   r   r   r   r   r  r   rv  rs  r  r   r   )r\   r&  r*  rw  ru  s        rW   profiler  C	  s    ())::>>$	 23D()) #((224772CIIK1 &&000AEEG@K@@3{CSS	 "3"9a0-33==dggX\=]cce
 "#
 >BBrY   z/update-profilec                     S[         ;  a  [        SSS.5      S4$  [        R                  " 5       n [        R                   R                  [        [         S   5      nU(       d  [        SSS.5      S4$ U R                  SUR                  5      Ul        U R                  S	UR                  5      Ul        U R                  S
UR                  5      Ul	        U R                  SUR                  5      Ul
        U R                  SUR                  5      Ul        U R                  SUR                  5      Ul        [        R                   R                  5         [        SSS.5      $ ! [         aO  n[        R                   R                  5         [!        S[#        U5       35        [        SSS.5      S4s SnA$ SnAff = f)zUpdate user profile informationr[   Fr   r   r   r&  r   rc   r   r   r   ra   rd   TzProfile updated successfullyu   ❌ Error updating profile: zFailed to update profiler   N)r   r   r   r   r   r]   r   rc   r   r   r   ra   rd   r   r   r   rN   r   )r   r\   r   s      rW   update_profiler  a	  s[    5_EFKKW!zz~~dGI$67u9IJKSPP HHVTYY/	XXgtzz2
hhx5HHVTYY/	XXgtzz2
hhx5


44RSTT W


,SVH5655OPQSVVVWs&   AE% 3C1E% %
F>/AF93F>9F>z/api/check-eligibilityc                     S[         ;  a  [        SS05      $ [        R                  R	                  [         S   SS9R                  5       n [        [        U 5      S:  U  Vs/ s H  oR                  PM     sn[        U 5      S.5      $ s  snf )zCheck assessment eligibilityr[   r   r   T)r[   r  r   )r  rX  r  )r   r   r:   r   r   r   rs  r  )eligible_masteriesms     rW   api_check_eligibilityr  	  s     122'--77	"#' 8  
ce 
 *+a/-?@-?^^-?@'(  @s   !B	
z$/api/practice-ranking/<concept_name>c                 4   S[         ;  a  [        SS05      $ [        R                  R	                  [         S   U S9R                  5       nU(       d  [        SSSSS.5      $ [        UR                  UR                  UR                  UR                  S.5      $ )z Get practice ranking for conceptr[   r   r   r  r   N)r%  r  r  r  )
r   r   r;   r   r   r   total_practice_scoretotal_practice_questionsconcept_world_rankconcept_national_rank)r  r  s     rW   api_practice_rankingr  	  s     122##--	"! .  eg 
  !	
  	 33";;00 66	  rY   z/generate-priority-questionsc                  ~   S[         ;  a  [        SSS.5      $ [        R                  R	                  S5      =(       d    [
        R                  " S5      n U (       a  U S:X  a  [        SSS.5      $ [        R                   R	                  [        [         S   5      n[        R                  R                  UR                  SS	9R                  5       nU(       d  [        SS
S.5      $ / nU HU  n[        R                   R	                  [        UR                  5      nU(       d  M:  UR!                  UR"                  5        MW      [%        UR                  UU SS9nU[         S'   S[         S'   [        SUS.5      $ ! [&         a8  n[)        S[+        U5       35        [        S[+        U5      S.5      s SnA$ SnAff = f)z0Generate questions with 50-50 priority-new splitr[   Fr   r   r`  ra  r  Tr|  r  r  )r[   rw  rd  r  r  r  r  r  N)r   r   rf  rg  r]   rh  ri  r   r   r   r   r   r   r   r   rZ  r   rc   r5   r   rN   r   )rd  r\   r  rw  ry  r  rP   r   s           rW   generate_priority_questionsr  	  sv    5_EFFjjnn\*Ebii.EGg!;;55MNOO::>>$	 23D (--77$ 8 	ce  55KLMM !**..$//:7$$W\\2 "
>=GG/	
	 (1#$,0()4i@AA >CF8$%5SV<==>s   5E: :
F<-F71F<7F<z/save-practice-sessionc                  X   S[         ;  a  [        SSS.5      $ [        R                  " 5       n U R	                  S5      n U(       Ga  [
        R                  R                  U[         S   S9R                  5       nU(       Gar  U R	                  SUR                  5      Ul	        U R	                  SUR                  5      Ul
        U R	                  S	UR                  5      Ul        U R	                  S
UR                  5      Ul        U R	                  SUR                  5      Ul        U R	                  SS5      Ul        U R	                  SUR                  5      Ul        [         R"                  " 5       Ul        U R	                  SS5      nU R	                  SS5      nUUS.nU R	                  S/ 5      nU(       a  UR'                  U5        [)        SU 35        US:  a  [)        SU SU S35        GO[        SSS.5      S4$ [        [         S   U R	                  S5      U R	                  S5      U R	                  SS5      U R	                  SS5      U R	                  SS5      U R	                  S	S5      U R	                  S
S5      U R	                  SS5      U R	                  SS5      S9
nU R	                  S/ 5      nUR'                  U5        [*        R                   R-                  U5        [)        S5        [*        R                   R/                  5         [        SUR0                  S S!.5      $ ! [2         ao  n[*        R                   R5                  5         [)        S"[7        U5       35        SS#KnUR;                  5         [        SS$[7        U5       3S.5      S%4s S#nA$ S#nAff = f)&zSave or update practice sessionr[   Fr   r   
session_idr   r[   r  r  r  lives_remainingduration_secondsis_completed	sub_levelr  r   r  )r  r  rX  u   ✅ Updated session z   Typed answers: rz   z correctSession not foundr   r  r  rG   rF   )
r[   r  r  r  r  r  r  r  r  r  u    ✅ Created new practice sessionTz#Practice session saved successfully)r   r  r   u#   ❌ Error saving practice session: Nz!Failed to save practice session: r   )r   r   r   r   r]   r   r   r   r   r  r  r  r  r  r  r  r=   ru  r<  set_conceptsrN   r   r   r   r   r   r   r   r=  r>  )	r   r  practice_sessionr  r  
extra_datarX  r   r=  s	            rW   save_practice_sessionr  	  sS    5_EFFD,'JK.44>>	*  ?   eg 
  3788<MO_OoOo3p 03788<MO_OoOo3p 0)-';K;Q;Q)R &3788<MO_OoOo3p 048HH=OQaQrQr4s 1040O --1XXkCSC]C]-^ *080A - '+hh/Da&H# $! <
 ,?%2

  88J3$11(;,ZL9:&*.}oQ?R>SS[\]5=PQRTWWW  /	*hhw'88L1((;2 $):A > $):A >hhw* $):A >!%*<a!@!XXne<  xx
B/H))(3JJNN+,46


*--<
  	  


3CF8<=:3q6(C
   	s'    GL0 D*L0 0
N):A$N$N)$N)z/api/practice-statsc                  `   S[         ;  a  [        SS05      $  [         S   n [        R                  " U 5      n0 nUR	                  S0 5      R                  5        Hi  n[        R                  R                  U US9R                  5       nU(       d  M8  UR                  UR                  UR                  UR                  S.X#'   Mk     X!S'   [        U5      $ ! [         aM  n[        S[!        U5       35        S	S
KnUR%                  5         [        S[!        U5      05      S4s S
nA$ S
nAff = f)z<Get comprehensive practice statistics for the logged-in userr[   r   r   concepts_practicedr  )r  r  r  r  r  u#   ❌ Error fetching practice stats: r   Nr   )r   r   r   get_user_practice_statsr]   r   r:   r   r   r   r  r  r  r  r   rN   r   r=  r>  )r[   ru  r  r  r  r   r=  s          rW   practice_statsr  6
  s'    122/)$77@ !II&:B?DDFL$**44) 5  eg 
 w(/(@(@*1*D*D'.'>'>#*#E#E	3!/ G &7!"u~ /3CF8<=Q()3..	/s&   A5C AC 
D- AD("D-(D-z)/api/concept-practice-need/<concept_name>c                    S[         ;  a  [        SS05      $  [        R                  " [         S   U 5      n[        U5      $ ! [         a7  n[        S[        U5       35        [        S[        U5      05      s SnA$ SnAff = f)z/Check if a specific concept needs more practicer[   r   r   u"   ❌ Error checking practice need: N)r   r   r   get_concept_practice_needr   rN   r   )r  needr   s      rW   concept_practice_needr  X
  sz     122*889K\Zt} *23q6(;<Q())*s   (A 
B,A>8B>Bz/practice-historyc                     S[         ;  a  [        [        S5      5      $ [        R                   R	                  [
        [         S   5      n U (       d  [        [        S5      5      $ [        R                  R                  U R                  S9R                  [        R                  R                  5       5      R                  5       n[        R                  " U R                  5      n[        SU UUS9$ )zView detailed practice historyr[   r}   rW  zpractice_history.htmlr\   sessionsru  )r   r	   r
   r   r]   r   r   r   r   r   r1  r<  r2  r   r  r   r  s      rW   practice_historyr  e
  s     ())::>>$	 23D()) $$..tww.?	/..335	6	 
 33DGG<E2""*$& &rY   z/api/check-resumable-sessionc                  P   S[         ;  a  [        SSS.5      $  [        R                  R	                  [         S   SS9R                  [        R                  [        R                  " 5       [        SS9-
  :  5      R                  [        R                  R                  5       5      R                  5       n U (       Ga  [        R                  " 5       U R                  -
  nUR                  S:  a%  UR                   S	UR                  S
:  a  SOS S3nOZUR                  S-  S:  a   UR                  S-  nU SUS
:  a  SOS S3nO'UR                  S-  nUS:  a  U SUS
:  a  SOS S3OSn[        SU R                  U R                   U R"                  U R$                  U R&                  U R(                  US.S.5      $ [        SS05      $ ! [*         aN  n[-        S[/        U5       35        SSKnUR3                  5         [        [/        U5      SS.5      S4s SnA$ SnAff = f)z1Check if user has an incomplete session to resumer[   r   F)r   has_session)r[   r     )r  r   r  rG   r  rM   r  r  r  r  r  zjust nowT)r   r  r  r  r  r  time_ago)r  r   r  u&   ❌ Error checking resumable session: Nr   )r   r   r   r   r   filterr<  r=   ru  r>   r1  r2  r   r  r  r   r  r  r  r  r  r   rN   r   r=  r>  )recent_sessionr  r  r  r  r   r=  s          rW   check_resumable_sessionr  
  s    GHH(E(..88I& 9 
 &((HOO,=	PR@S,SS

(?//446
7 	  )N,G,GGI~~!'nn-T!9K#QS1TTXY""d*Q.!))T1#WE#)C4H#++r1RY\]R]gYgWq[cb-INcm#(+++11!/!9!9"0";";+11'5'E'E (   u-.. E6s1vh?@Q>?DD	Es%   F%G  G 
H%AH H% H%z$/api/resume-session/<int:session_id>c           
      ,   S[         ;  a  [        SSS.5      S4$  [        R                  R	                  U [         S   S9R                  5       nU(       d  [        SSS.5      S4$ [        S	UR                  UR                  UR                  UR                  UR                  UR                  5       S
.S.5      $ ! [         aN  n[        S[        U5       35        SSKnUR!                  5         [        S[        U5      S.5      S4s SnA$ SnAff = f)zResume a practice sessionr[   Fr   r   r   r  r  r   T)r  r  r  r  r  rX  )r   r   u   ❌ Error resuming session: r   Nr   )r   r   r   r   r   r   r  r  r  r  r  get_conceptsr   rN   r   r=  r>  )r  r  r   r=  s       rW   resume_session_apir  
  s    5_EFKKC*00::I& ; 
 %' 	
  u9LMNPSSS)//.99-77)//#3#C#C,99;

 
 
	  C,SVH565SV<=sBB	Cs&   A	B; &AB; ;
DADDDz/api/adaptive-statusc                     S[         ;  a  [        SSS.5      $  [         S   n [        R                  R	                  U SS9R                  5       n/ nU H  n[        R                   R                  [        UR                  5      nU(       d  M:  UR                  UR                  UR                  UR                  UR                  UR                  UR                  UR                   UR"                  S.5        M     [        SUS.5      $ ! [$         aC  n['        S	[)        U5       35        S
SKnUR-                  5         [        SSS.5      s SnA$ SnAff = f)z9Get user's adaptive learning status and selected conceptsr[   Fr   r   Tr|  )r  current_levelmastery_scorerq  rr  ro  rp  rn  )r   adaptive_statuszError getting adaptive status: r   Nr   )r   r   r   r   r   r   r   r]   r   rZ  r   rc   rm  rq  rr  ro  rp  rn  r   rN   r   r=  r>  )r[   r  r  rY  r  r   r=  s          rW   api_adaptive_statusr  
  sE    5_EFF!F)$ ,11;; < 
 #% 	
 )HjjnnWh.A.ABGw$$&||%-%;%;%-%;%;&.&=&=(0(A(A+3+G+G-5-K-K080Q0Q	& 	 * ,
  	
  F/Ax895^DEE	Fs%   A/D	 A;D	 	
E8EEEr   c                 *    [        [        S5      5      $ )Nr}   )r	   r
   r   s    rW   	not_foundr  
  s    GG$%%rY   r   c                 @    [         R                  R                  5         g)N)r   r   )r   r   r   r  s    rW   internal_errorr  
  s    JJ'rY   __main__)debug)rM   )r   flaskr   r   r   r   r   r	   r
   r   
flask_corsr   
flask_mailr   r   
sqlalchemyr   r   rg  r   modelsr   r   r   r   r   r   r   r   r   r   r   r  r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   rh  ru   r=   r>   dotenvr?   __name__rf  from_objectri  rX   init_appmailcontext_processorr_   app_context
create_allrN   r   r  existing_concepts_countr   grade_1_conceptsr  rd   r   ra   rX  r  r  r   r   r   existingrs  before_requestry   router}   rK  r   r   r   r   r   r   r   r   r  r
  r  r  r!  r  r*  r.  r2  r8  r7  rC  rN  rQ  rT  r]  rj  rz  r~  r  r  r  r  r  r  r9  r  r@  rJ  r^  rc  r|   re  rf  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  errorhandlerr  r  runrx   rY   rW   <module>r     s5    ] ] ]  $ #  `  `  `  `	 	 	 	 	 	   J I 	  (  Ho 

  v  S"))N+$ G" C Cy  	__MMO 
-	
&'	&M%mm113	+,C+D
EF }}..S.9??A	/0
12!#TU+113NFF#)<<>x)%&FG$,L%)#%'3nKwax$P	G JJNN7+H\N34 %- $2 4 	

67	Q	OP&F2M&11-eWAfX\JK(5f(=e(D#*==#:#:!-"'#) $; $  %'	 !  (&-%1&+'-/;nKwaPVx,X	'G JJNN73!H\N";<!F<.8I"JK% )E 3 '0 	

<= 	>? ]]((*N	Bvh-	((8
9: Q''e'4::<19HUG2eWI67 Q
 
-a f + + 3+ +	m	%}	6>	OWYf	m	%}	6>	OWYh	 m	 '	 8A&	 KTUb	 }		 (		 9B?		
 	
  *=	
 GTan=mapM]j]	   !F84K 5K<2 
 
 >E6?3 42 8eV_-&E .&EP 9& & >F8,+ -+\  0 "VH5< 6<| "VH5/ 6/b fX./ //b  $ v7-C 8-C^ ufo61e 71ej  6(3? 4?
 ;0 1& x0J 1J   5&/:)C ;)CV ?UFO4NX 5NXd ?  ? >F8,1K -1Kf eV_52K 62Kf!XJ  1 !1& 11 21f $vh7:^ 8:^x =U U*  6(3x> 4x>r ?(: (:R?D &2h^ 3h^T !F84K 5KX $vh7>> 8>>D P/  P/b :": ":J  	@ !	@ )F8<M> =M>\ L L\    <- -"M:c*H h ) * h o  J K , - 0 1 ' ( / 0 1 2 h!"## ###H   > )*RF +RFh	 01*F 2*FX :C C: vh/W 0W: #$ %  12 36 )F8<,> =,>d #fX6S 7Sl  ! / " /B 67
* 8
* &  &2 )E7;-E <-E^ 1E7CC DC@ !"&F #&FR #& & #( ( zGG$G GV s   6EgD&g9g
g(