
    hK4                     R   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mZ d dlmZ d d	lmZ  ej2                  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e      Z  G d d      Z!y)    N)DictAnyList)genai)types)	BaseModel)Session)Project	CandidateApplicationAIAssessment	SoftSkill)GEMINI_API_KEY)SoftSkillResponse)api_keyc                   B    e Zd ZU eed<   eed<   ee   ed<   ee   ed<   y)ProjectSuggestiontitledescriptioncriteriasoft_skillsN)__name__
__module____qualname__str__annotations__r        E/home/www/40-admission.kofcorporation.com/app/services/ai_services.pyr   r      s!    J3icr   r   c                   B    e Zd ZU eed<   eed<   ee   ed<   ee   ed<   y)ProjectSuggestionResponser   r   r   r   N)r   r   r   r   r   r   r   r   r   r   r!   r!      s#    J3i'((r   r!   c                   L    e Zd ZU eed<   eed<   ee   ed<   ee   ed<   eed<   y)CandidateAssessmentscoresummary	strengths
weaknessesrecommendationsN)r   r   r   floatr   r   r   r   r   r   r#   r#      s&    LLCyS	r   r#   c                   4    e Zd ZU eed<   dZeed<   dZeed<   y)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<   y)AICandidateAssessRequestcandidate_id
project_idN)r   r   r   intr   r   r   r   r/   r/   )   s    Or   r/   c                   :    e Zd ZU eed<   eed<   eed<   dZeed<   y)AIMessageCompositionRequestmessage_typecandidate_nameproject_titleNadditional_context)r   r   r   r   r   r8   r   r   r   r4   r4   -   s    ""r   r4   c            	           e Zd Zed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y	)
	AIServicedbrequestreturnc                   K   	 d|j                    d|j                  xs d d|j                  xs d d}t        j                  j                  dt        j                  dt        j                  |      g	      gt        j                  d
t                    }|j                  st        d      t        j                  |j                        }t        di |}g }|j                  D ]  }|j!                         j#                         }| j%                  t&              j)                  t&        j*                  j-                  |            j/                         }	|	s1t'        |d|       }	| j1                  |	       | j3                          |j5                  |	        | j7                          |D ]  }
| j9                  |
        t;        |j"                  |j                   |j<                  |D cg c]  }t?        j@                  |       c}      S c c}w # tB        $ rC}tE        jF                  d|        | jI                          t;        ddg dg       cY d}~S d}~ww xY ww)zRUse Gemini to assist in creating admission projects and align soft skills with DB.z
            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AI-suggested skill: )namer   )r   r   r   r   z'Failed to generate project suggestion: zAI-Generated Projectz\A comprehensive admission project created with AI assistance. Could not process soft skills.)zAcademic excellencezLeadership potentialzCommunication skillsNr   )%r   r,   r-   clientmodelsgenerate_contentr   ContentPartGenerateContentConfigr   rC   
ValueErrorjsonloadsr   stripr   queryr   filterrP   ilikefirstaddflushappendcommitrefreshr!   r   r   model_validate	Exceptionloggingerrorrollback)r;   r<   promptresponsesuggestion_dataai_suggestionsoft_skill_objects
skill_namenormalized_skill_namedb_skillskillses                r   assist_project_creationz!AIService.assist_project_creation4   s9    F	 "--. /"//B?C D%55HI 	JF  }}55&--VEJJF<S;TUV22'9$5 6 H == !?@@"jj7O-@@M "$+77 4
(2(8(8(:(@(@(B%88I.55inn6J6JK`6abhhj(.CSghrgsQtuHFF8$HHJ"))(34 IIK , "

5!" -#)))55&//J\]Q.==a@]	  ^  		MMCA3GHKKM,,z`	 			sG   I+G/H 3HH I+H 	I(%8I#I(I+#I((I+c                   K   	 | j                  t              j                  t        j                  |j                  k(        j                         }| j                  t              j                  t        j                  |j                  k(        j                         }|r|st        d      d|j                   d|j                   d|j                   d|j                  xs d d|j                  xs d d|j                  xs d	 d
}dj                  |j                   D cg c]  }d|j"                    c}      }dj                  |j$                  D cg c]  }d|j&                    c}      }d|j(                   d|j"                   d| d| d| d}	t*        j,                  j/                  dt1        j2                  dt1        j4                  |	      g      gt1        j6                  dt8                    }
|
j:                  rt=        j>                  |
j:                        }t9        d%i |}tA        |j                  |j                  |jB                  |jD                  |jF                  |jH                  |jJ                  dd      }| jM                  |       | jO                          |S t        d      c c}w c c}w # tP        $ r4}tS        jT                  d|        t9        ddd gd!gd"#      cY d$}~S d$}~ww xY w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?   
            
z- 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@   rA   rB   rD   rG   rH   rK   )r&   r'   r(   )r0   r1   r$   r%   detailsmodel_versionrO   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   )+r[   r   r\   idr0   r^   r
   r1   rW   
first_name	last_nameemailacademic_backgroundwork_experiencenationalityjoinr   r   r   rP   r   rQ   rR   rS   r   rT   rU   rV   r#   rC   rX   rY   r   r$   r%   r&   r'   r(   r_   rb   re   rf   rg   )r;   r<   	candidateprojectcandidate_info	criterioncriteria_textrq   soft_skills_textri   rj   data
assessmentai_assessmentrs   s                  r   assess_candidatezAIService.assess_candidate   s    X	+229<<7CWCW3WX^^`Ihhw'..wzzW=O=O/OPVVXGG !ABB"''()*=*=)> ?OO$ %""+"?"?"Q>!R S'77I>J K#//B?C DN !IIU\UeUe&f	I,A,A+B'C&fgM#yyI\I\)]Buzzl*;)]^ mm_ %!--. / O     
F2 }}55&--VEJJF<S;TUV22'9$7 6 H }}zz(--00848
 !-!(!5!5&11$**&..%/%9%9&0&;&;+5+E+E
 #3! }%		!! !?@@w 'g)]x  		MM8<=&N23NO K 		sT   LDK #K9 K K/EK 5L6K 	L)L=L>LLLc           	        K   	 ddddddd}|j                  | j                  d      }d	| d
| j                   d| j                   d| j                  xs d d	}t
        j                  j                  d|      }|j                  xs dS # t        $ r?}t        j                  d|        d| j                   d| j                   dcY d}~S d}~ww xY w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rL   rM   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)getr5   r6   r7   r8   rQ   rR   rS   rC   re   rf   rg   )r<   message_templatestemplate_descriptionri   rj   rs   s         r   compose_messagezAIService.compose_message   s    '	RFT(QC!:$O! $5#8#89M9MOm#n KK_J` a %334 5  ' 5 56 7##*#=#=#P"Q 
RF$ }}55( 6 H
 ==N$NN 	RMM7s;<71122VW^WlWlVm  nQ  R  R	Rs5   CBB 
C	C4CC	CCCr1   c           	        K   	 | j                  t              j                  t        j                  |k(        j	                         }|sddiS | j                  t
              j                  t
        j                  |k(        j                         }|sddiS g }|D ]b  }|j                  }|j                  |j                  j                  |j                  xs d|j                  xs d|j                  xs dd       d d|j                   d	t!        |       d
t#        j$                  |d       d}d| d}t&        j(                  j+                  d|      }	|j                  t!        |      |	j,                  xs dddS # t.        $ r2}
t1        j2                  d|
        ddt5        |
       icY d}
~
S d}
~
ww xY ww)zCGenerate AI insights about a project's applications and performancerg   zProject not foundmessagezNo applications to analyze yetrw   r?   )statuscandidate_background
experiencer   z
            Project: z!
            Total Applications: z
            Application Data:    )indentrx   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)r7   total_applicationsai_insightsgenerated_atz%Failed to generate project insights: zFailed to generate insights: N)r[   r
   r\   r|   r^   r   r1   allr   ra   r   valuer   r   r   r   lenrX   dumpsrQ   rR   rS   rC   re   rf   rg   r   )r;   r1   r   applicationsapp_dataappr   data_summaryri   rj   rs   s              r   generate_project_insightsz#AIService.generate_project_insights  s    9	Ghhw'..wzzZ/GHNNPG!45588K0778N8NR\8\]aacL!#CDD H# MM	!jj..,5,I,I,[^"+";";"M~#,#8#8#KO	!  mm_ %!!$\!2 3 4#zz(1=> ?L N 
F }}55& 6 H ")&),&7'}}M0M %	   	GMMA!EF<SVHEFF	GsO   G AF G AF G C+F G 	F='F82F=3G 8F==G N)r   r   r   staticmethodr	   r+   r!   rt   r/   r#   r   r4   r   r   r2   r   r   r   r   r   r   r:   r:   3   s    H' H<R HWp H HT Z7 Z5M ZRe Z Zx )R'B )Rs )R )RV ;GG ;G ;GcSVh ;G ;Gr   r:   )"rX   rf   ostypingr   r   r   googler   google.genair   pydanticr   sqlalchemy.ormr	   
app.modelsr
   r   r   r   r   app.core.configr   app.schemas.soft_skillr   ClientrQ   r   r!   r#   r+   r/   r4   r:   r   r   r   <module>r      s      	 " "    " O O * 4 
n	-	 )	 ))  Y  
y #) #QG QGr   