
    Uh-                     N   d dl Z d dlZd dlZd dlmZmZmZ d dlmZ d dl	m
Z
 d dlmZ d dlmZ d dlmZmZmZmZ d dlmZ  ej        e	          Z G d
 de          Z G d de          Z G d de          Z G d de          Z G d de          Z G d d          ZdS )    N)DictAnyList)genai)types)	BaseModel)Session)Project	CandidateApplicationAIAssessment)GEMINI_API_KEY)api_keyc                   P    e Zd ZU eed<   eed<   ee         ed<   ee         ed<   dS )ProjectSuggestiontitledescriptioncriteriasoft_skillsN)__name__
__module____qualname__str__annotations__r        2/home/runner/workspace/app/services/ai_services.pyr   r      sG         JJJ3icr   r   c                   Z    e Zd ZU eed<   eed<   ee         ed<   ee         ed<   eed<   dS )CandidateAssessmentscoresummary	strengths
weaknessesrecommendationsN)r   r   r   floatr   r   r   r   r   r   r   r      sP         LLLLLLCyS	r   r   c                   6    e Zd ZU eed<   dZeed<   dZeed<   dS )AIProjectAssistRequestr   Nrequirementstarget_audience)r   r   r   r   r   r(   r)   r   r   r   r'   r'      s>         L#OSr   r'   c                   $    e Zd ZU eed<   eed<   dS )AICandidateAssessRequestcandidate_id
project_idN)r   r   r   intr   r   r   r   r+   r+   !   s%         OOOOOr   r+   c                   <    e Zd ZU eed<   eed<   eed<   dZeed<   dS )AIMessageCompositionRequestmessage_typecandidate_nameproject_titleNadditional_context)r   r   r   r   r   r4   r   r   r   r0   r0   %   sG         """"""r   r0   c            	           e Zd Zededefd            Zededede	fd            Z
ededefd            Zedededeeef         fd            Zd	S )
	AIServicerequestreturnc           	        K   	 d| j          d| j        pd d| j        pd d}t          j                            dt          j        dt          j        |          g	          gt          j	        d
t                              }|j        r%t          j        |j                  }t          di |S t          d          # t          $ r8}t!          j        d|            t          ddg dg d          cY d}~S d}~ww xY w)z3Use Gemini to assist in creating admission projectsz
            You are an expert university admission consultant. Based on the following information, create a detailed admission project proposal.
            
            Description: z
            Requirements: Not specifiedz
            Target Audience: a  
            
            Please provide:
            1. A compelling project title
            2. A detailed description (200-300 words)
            3. 5-8 selection criteria that would help evaluate candidates
            4. 4-6 relevant soft skills required for success
            
            Make the project professional, clear, and attractive to potential students.
            gemini-2.5-prousertextrolepartsapplication/jsonresponse_mime_typeresponse_schemamodelcontentsconfigEmpty response from AI modelz'Failed to generate project suggestion: zAI-Generated Projectz=A comprehensive admission project created with AI assistance.)zAcademic excellencezLeadership potentialzCommunication skills)TeamworkzProblem-solvingAdaptability)r   r   r   r   Nr   )r   r(   r)   clientmodelsgenerate_contentr   ContentPartGenerateContentConfigr   r>   jsonloads
ValueError	Exceptionloggingerror)r7   promptresponsedataes        r   assist_project_creationz!AIService.assist_project_creation,   sy     (	 "-  #/B?	 
 &5H  F  }55&-VEJF<S<S<S;TUUUV2'9$5   6  H } Az(-00(004000 !?@@@ 	 	 	MGAGGHHH$,[```KKK	        	s$   B.C 3C 
D-C?9D?Ddbc                 D  K   	 |                      t                                        t          j        |j        k                                              }|                      t                                        t          j        |j        k                                              }|r|st          d          d|j	         d|j
         d|j         d|j        pd d|j        pd d|j        pd	 d
}d                    d |j        D                       }d                    d |j        D                       }d|j         d|j         d| d| d| d}t(          j                            dt/          j        dt/          j        |          g          gt/          j        dt6                              }|j        rt;          j        |j                  }	t7          d&i |	}
t?          |j        |j        |
j         |
j!        |
j"        |
j#        |
j$        dd          }| %                    |           | &                                 |
S t          d          # tN          $ r7}tQ          j)        d|            t7          dd d!gd"gd#$          cY d%}~S d%}~ww xY w)'z7Use Gemini to assess a candidate for a specific projectzCandidate or project not foundz
            Name:  z
            Email: z"
            Academic Background: Not providedz
            Work Experience: z
            Nationality: r:   
            
c                 "    g | ]}d |j          S z- )r   ).0	criterions     r   
<listcomp>z.AIService.assess_candidate.<locals>.<listcomp>n   s$    &f&f&f	'CI,A'C'C&f&f&fr   c                 "    g | ]}d |j          S re   )name)rf   skills     r   rh   z.AIService.assess_candidate.<locals>.<listcomp>o   s#    )])])]*;uz*;*;)])])]r   z
            You are an expert university admission evaluator. Assess this candidate for the specified project.
            
            PROJECT: z
            Description: z:
            
            Selection Criteria:
            z<
            
            Required Soft Skills:
            z9
            
            CANDIDATE PROFILE:
            a  
            
            Please provide:
            1. Overall score (0-100)
            2. Summary assessment (2-3 sentences)
            3. Key strengths (list of 3-5 points)
            4. Areas for improvement (list of 3-5 points)
            5. Specific recommendations for this candidate
            
            Be fair, objective, and constructive in your assessment.
            r;   r<   r=   r?   rB   rC   rF   )r"   r#   r$   )r,   r-   r    r!   detailsmodel_versionrJ   zFailed to assess candidate: g      I@z4Unable to generate detailed assessment at this time.zApplication submittedz0Insufficient information for complete evaluationz)Please review candidate profile manually.)r    r!   r"   r#   r$   Nr   )*queryr   filteridr,   firstr
   r-   rU   
first_name	last_nameemailacademic_backgroundwork_experiencenationalityjoinr   r   r   r   rM   rN   rO   r   rP   rQ   rR   r   r>   rS   rT   r   r    r!   r"   r#   r$   addcommitrV   rW   rX   )r^   r7   	candidateprojectcandidate_infocriteria_textsoft_skills_textrY   rZ   r[   
assessmentai_assessmentr\   s                r   assess_candidatezAIService.assess_candidateY   sP     X	++229<7CW3WXX^^``Ihhw''..wzW=O/OPPVVXXG CG C !ABBB' *3*= O  #,"?"Q>  (7I>	 
 $/B?  N !II&f&fU\Ue&f&f&fggM#yy)])]I\)])])]^^ m  "-	        F2 }55&-VEJF<S<S<S;TUUUV2'9$7   6  H } Az(-00088488
 !-!(!5&1$*&.%/%9&0&;+5+E 
 #3! ! ! }%%%		!! !?@@@ 		 		 		M<<<===&N23NO K        		s$   I
I I 
J(,JJJc           	      f  K   	 ddddddd}|                     | j        d          }d	| d
| j         d| j         d| j        pd d	}t
          j                            d|          }|j        pdS # t          $ r4}t          j        d|            d| j         d| j         dcY d}~S d}~ww xY w)z9Use Gemini to compose professional messages to candidatesz)a welcoming message for a new applicationz5a polite rejection message with constructive feedbackz'an interview invitation with next stepsz#a congratulatory acceptance messageza status update messagez)a message requesting additional documents)welcome	rejectioninterview_invitation
acceptancestatus_updatedocument_requestza professional communicationzK
            You are a professional university admissions officer. Compose zN for a student.
            
            Details:
            - Student Name: z 
            - Project/Program: z#
            - Additional Context: zNone provideda  
            
            Requirements:
            1. Professional and respectful tone
            2. Clear and concise language
            3. Appropriate for university admissions context
            4. Include specific details provided
            5. End with appropriate next steps or contact information
            
            The message should be 150-300 words and ready to send.
            zgemini-2.5-flashrG   rH   z(Unable to generate message at this time.zFailed to compose message: zDear z",

Thank you for your interest in z .

Best regards,
Admissions TeamN)getr1   r2   r3   r4   rM   rN   rO   r>   rV   rW   rX   )r7   message_templatestemplate_descriptionrY   rZ   r\   s         r   compose_messagezAIService.compose_message   s^     '	RFT(QC!:$O! ! $5#8#89MOm#n#n K_  %3	 
 !( 5  $+#=#P  F$ }55( 6  H
 =N$NN 	R 	R 	RM;;;<<< R71  R  RW^Wl  R  R  R  R  R  R  R  R  R	Rs   A-A2 2
B0<)B+%B0+B0r-   c           	      X  K   	 |                      t                                        t          j        |k                                              }|sddiS |                      t
                                        t
          j        |k                                              }|sddiS g }|D ]B}|j        }|	                    |j
        j        |j        pd|j        pd|j        pdd           Cd|j         d	t!          |           d
t#          j        |d           d}d| d}t&          j                            d|          }	|j        t!          |          |	j        pdddS # t.          $ r5}
t1          j        d|
            ddt5          |
           icY d}
~
S d}
~
ww xY w)zCGenerate AI insights about a project's applications and performancerX   zProject not foundmessagezNo applications to analyze yetra   r:   )statuscandidate_background
experiencerw   z
            Project: z!
            Total Applications: z
            Application Data:    )indentrb   zn
            Analyze this admission project's application data and provide insights:
            
            a  
            
            Please provide:
            1. Overall application quality assessment
            2. Common patterns in applicant profiles
            3. Recommendations for improving the selection process
            4. Suggestions for attracting better candidates
            5. Any notable trends or observations
            
            Keep your analysis professional and actionable.
            r;   r   zUnable to generate insightsnow)r3   total_applicationsai_insightsgenerated_atz%Failed to generate project insights: zFailed to generate insights: N)rn   r
   ro   rp   rq   r   r-   allr{   appendr   valueru   rv   rw   r   lenrS   dumpsrM   rN   rO   r>   rV   rW   rX   r   )r^   r-   r|   applicationsapp_dataappr{   data_summaryrY   rZ   r\   s              r   generate_project_insightsz#AIService.generate_project_insights   s)     9	Ghhw''..wzZ/GHHNNPPG 6!45588K00778NR\8\]]aaccL E!#CDD H#  M	!j.,5,I,[^"+";"M~#,#8#KO	! !    m !$\!2!2   $z(1===  L   F }55& 6  H ")&),&7&7'}M0M %	    	G 	G 	GME!EEFFFESVVEEFFFFFFF	Gs,   AE* AE* *B?E* *
F)4*F$F)$F)N)r   r   r   staticmethodr'   r   r]   r	   r+   r   r   r0   r   r   r.   r   r   r   r   r   r   r6   r6   +   s        */E *J[ * * * \*X Z7 Z5M ZRe Z Z Z \Zx )R'B )Rs )R )R )R \)RV ;GG ;G ;GcSVh ;G ;G ;G \;G ;G ;Gr   r6   )rS   rW   ostypingr   r   r   googler   google.genair   pydanticr   sqlalchemy.ormr	   
app.modelsr
   r   r   r   app.core.configr   ClientrM   r   r   r'   r+   r0   r6   r   r   r   <module>r      s     				 " " " " " " " " " "                   " " " " " " D D D D D D D D D D D D * * * * * * 
n	-	-	-    	       )            Y      
    y   # # # # #) # # #sG sG sG sG sG sG sG sG sG sGr   