
    hJj
'                       S r SSKJr  SSKrSSKJr  SSKJr  SSKJ	r	  SSK
Jr  SSKJrJrJrJr  \R"                  " S	\R$                  5      rS
r\R"                  " S\R$                  5      r\R"                  " S\R$                  5      r\" 1 Sk5      rSrSrSS jrSS jr  S       SS jjrSSS jjrSSS jjrS S jr             S!S jr!          S"S jr" S       S#S jjr#g)$uF   Resolución de estudiante/documento para generación en chat Agent v2.    )annotationsN)Any)Session)AgentV2DocumentTemplateModel)StudentPersonalInfoModel)FAMILIA_DOCUMENT_IDbuild_familia_pie360_contextfamilia_pie360_hint_linesis_familia_documentzC\b(\d{1,2}[.\s]?\d{3}[.\s]?\d{3}[-\s]?[\dkK]|\d{7,8}[-\s]?[\dkK])\b)Qzgenera el informezgenerar el informezgenera el documentozgenerar el documentozgenera el wordzgenerar el wordzgenera el docxzgenerar el docxzgenera un informezgenerar un informezgenera un documentozgenerar un documentozrealiza el informezrealizar el informezrealiza el documentozrealizar el documentozrealiza un informezrealizar un informezrealiza un documentozrealizar un documentozelabora el informezelaborar el informezelabora el documentozelaborar el documentozredacta el informezredactar el informezredacta el documentozredactar el documentozescribe el informezescribir el informezescribe el documentozescribir el documentozcrea el informezcrear informezcrear el informezcompleta el informezcompletar el informezcompleta el documentozcompletar el documentozfinaliza el informezfinalizar el informezemite el informezemitir el informezconfecciona el informezconfeccionar el informezarma el informezarmar el informezproduce el informezproducir el informezexporta el informezexportar el informezexporta el documentozexportar el documentozdescarga el informezdescargar el informezdescarga el documentozdescargar el documentoznecesito el informeznecesito el documentozquiero el informezquiero el documentozentrega el informezentregar el informezhaz el informezhacer el informezhaz el documentozhacer el documentozprepara el informezpreparar el informezprepara el documentozpreparar el documentozdeja listo el informezdejar listo el informezgenera de nuevozgenerar de nuevozrealiza de nuevozrealizar de nuevozvuelve a generarzvuelve a realizarzregenera el informezregenerar el informea  \b(genera(r)?|realiza(r)?|elabora(r)?|redacta(r)?|escribe(r)?|crea(r)?|completa(r)?|finaliza(r)?|emite(r)?|confecciona(r)?|arma(r)?|produce(r)?|exporta(r)?|descarga(r)?|prepara(r)?|regenera(r)?|haz|hacer|entrega(r)?)\s+(el\s+|un\s+|la\s+)?(informe|documento|word|docx)\ba0  ^\s*(genera|generar|realiza|realizar|elabora|elaborar|redacta|redactar|escribe|escribir|crea|crear|completa|completar|finaliza|finalizar|emite|emitir|confecciona|confeccionar|arma|armar|produce|producir|exporta|exportar|descarga|descargar|prepara|preparar|regenera|regenerar|haz|hacer|entrega|entregar)\b>   nooksiholaokayvalebuenolistothanksgraciasperfecto	entendido   sí
de acuerdo)informe para la familiazinforme a la familiazinforme de familiazinforme familiar   )
psicopedagpsicopedc                    [         R                  " SSU =(       d    SR                  5       5      R                  5       nU$ )Nz[^0-9kK] )resubstripupper)valuecleaneds     YC:\Users\jesus\Desktop\proyecto_pie360\backend\app\backend\utils\agent_v2_chat_context.pynormalize_rutr&      s/    ff["u{&9&9&;<BBDGN    c                    U (       d  g [         R                  U 5      nU(       a  UR                  S5      R                  5       $ S $ )N   )_RUT_REsearchgroupr!   )textmatchs     r%   extract_rut_from_textr/      s4    NN4 E%*5;;q>!44r'   c                D   U(       a%  UR                  5       (       a  UR                  5       $ [        U 5      nU(       a  U$ [        U=(       d    / 5       HH  nUR                  S5      S:w  a  M  [        UR                  S5      =(       d    S5      nU(       d  MF  Us  $    g )Nroleusercontentr   )r!   r/   reversedget)messagehistoryexplicit_rutfounditems        r%   extract_rut_from_conversationr;      s    
 **,,!!##!'*EB'88Fv%%dhhy&9&?R@5L ( r'   c                    U =(       d    S/nU=(       d    /  H,  nUR                  UR                  S5      =(       d    S5        M.     SR                  U5      $ )Nr   r3   
)appendr5   join)r6   r7   partsr:   s       r%   conversation_blobrA      sF    ]OE2TXXi(.B/ 99Ur'   c                *  ^ AU =(       d    SR                  5       nU(       d  gUR                  5       mT[        ;   a  g[        U4S j[         5       5      (       a  g[
        R                  U5      (       a  g[        R                  U5      (       a  gg)u   
True solo si el mensaje ACTUAL del usuario pide generar el Word.
No usa historial: evita regenerar en cada turno tras un «genera el informe» previo
o por palabras del asistente («informe», «genera», etc.) en mensajes anteriores.
r   Fc              3  ,   >#    U  H	  oT;   v   M     g 7fN ).0hintlows     r%   	<genexpr>,wants_document_generation.<locals>.<genexpr>   s     
5#443;#4   T)	r!   lower_SHORT_NON_GENERATIONany_GENERATION_HINTS_GENERATION_PHRASE_REr+   _GENERATION_START_REr.   )r6   r7   r-   rH   s      @r%   wants_document_generationrR      sw     	Mr  "D
**,C
##

5#4
555##D))!!$''r'   c                   [        U5      n[        U5      S:  a  g U R                  [        R                  [        R
                  5      R                  [        R
                  R                  S 5      5      R                  [        R
                  S:g  5      R                  5       nU H*  u  pE[        U=(       d    S5      U:X  d  M  [        U5      s  $    g )N   r   )
r&   lenqueryr   
student_ididentification_numberfilterisnotallint)dbruttargetrowsrW   identifications         r%   lookup_student_id_by_rutrb      s    3F
6{Q
)446N6d6de	(>>DDTJ	K	(>>"D	E		 	 '+"
-2.&8z?" '+ r'   c               p    U(       a  USS4$ [        X4U5      nU(       d  g[        X5      nUc  SUS4$ XeS4$ )zP
Returns (student_id, rut_used, issue).
issue: None | 'needs_rut' | 'not_found'
N)NN	needs_rut	not_found)r;   rb   )r]   rW   student_rutr6   r7   rut_rawr9   s          r%   resolve_student_idrh      sM     4%%+GkJG&$R1E}Wk))4r'   c                
  ^ U R                  [        5      R                  [        R                  U:H  5      R	                  [        R
                  R                  5       5      R                  5       nU(       d  g [        U5      S:X  a  [        US   R                  5      $ [        X#5      R                  5       m[        U4S j[         5       5      (       d  ST;   al  ST;   af  U H`  nUR
                  =(       d    SR                  5       nSU;   d  [        UR                  5      [        :X  d  MK  [        UR                  5      s  $    [        U4S j[          5       5      (       aG  U HA  nSUR
                  =(       d    SR                  5       ;   d  M,  [        UR                  5      s  $    [#        X#5      (       aG  U HA  nSUR
                  =(       d    SR                  5       ;   d  M,  [        UR                  5      s  $    g )	Nr)   r   c              3  ,   >#    U  H	  oT;   v   M     g 7frD   rE   rF   hblobs     r%   rI   $infer_document_id.<locals>.<genexpr>  s     
,m9mrK   familiainformer   c              3  ,   >#    U  H	  oT;   v   M     g 7frD   rE   rk   s     r%   rI   rn     s     
.o9orK   r   )rV   r   rY   agent_idorder_bydocument_nameascr[   rU   r\   document_idrA   rL   rN   _FAMILY_HINTSr   _PSICOPED_HINTSrR   )r]   rr   r6   r7   r`   rownamerm   s          @r%   infer_document_idr{     s    	-.	,55A	B	.<<@@B	C		 	 
4yA~47&&''W.446D

,m
,,,d1ByTXGXC%%+224DD C$8<O$O3??++  
.o
...Cc//52<<>>3??++  !22CS..4";;==3??++  r'   c                   U R                  [        5      R                  [        R                  U:H  5      R	                  5       nU(       d  SU S3$ UR
                  =(       d    SR                  5       nUR                  =(       d    SR                  5       nUR                  =(       d    SR                  5       nU SU SU 3R                  5       nUR                  =(       d    SR                  5       nSU=(       d    SU 3 3/n	U(       a  U	R                  SU 35        [        U5      (       a6  [        X5      n
U	R                  [        U
5      5        U	R                  S5        S	R                  U	5      S
-   $ )Nz&Estudiante identificado en PIE360 (id z).r    zEstudiante en PIE360: zid z	RUT/IPE: zzPara Informe a la Familia: si Files/Excel no traen apoderado o profesional, usa estos datos de ficha PIE360 como respaldo.z. .)rV   r   rY   rW   firstnamesr!   father_lastnamemother_lastnamerX   r>   r   r	   extendr
   r?   )r]   rW   rv   personalr   fathermotherfullr^   r@   pies              r%   student_identification_hintr   (  sH    	)*	(33zA	B	 
 7
|2FF^^!r((*E&&,"335F&&,"335FWAfXQvh'--/D))/R
6
6
8C%d&@J<.@%ABCE
y&';''*2:.s34=	

 99Uc!!r'   )r#   strreturnr   )r-   r   r   
str | None)NN)r6   r   r7   list[dict[str, str]] | Noner8   r   r   r   rD   )r6   r   r7   r   r   r   )r6   r   r7   r   r   bool)r]   r   r^   r   r   
int | None)r]   r   rW   r   rf   r   r6   r   r7   r   r   z)tuple[int | None, str | None, str | None])
r]   r   rr   r   r6   r   r7   r   r   r   )r]   r   rW   r\   rv   r   r   r   )$__doc__
__future__r   r   typingr   sqlalchemy.ormr   (app.backend.db.models.agent_v2_documentsr   app.backend.db.models.pie_corer   )app.backend.utils.agent_v2_familia_pie360r   r	   r
   r   compile
IGNORECASEr*   rO   rP   rQ   	frozensetrM   rw   rx   r&   r/   r;   rA   rR   rb   rh   r{   r   rE   r'   r%   <module>r      s   L " 	  " Q C  **JMM
R j 

? MM  zz MM	  " & -
5 ,0#(  	&,      	 
   )  / 2  )	
 J #""" " 		"r'   