o
    bh8                     @   s  d dl mZ d dlmZ d dlZd dlmZmZmZ d dl	m
Z
 d dlmZ e  dd Ze Zd	d
 Zdd Zdd Zdd Zdd Zd>ddZdd Zdd Zdd Zdd ZededdZejd d!gd"d#d$ Zejd%d!gd"d&d' Zejd(d!gd"d)d* Zejd+d!gd"d,d- Zejd.d/gd"d0d1 Zejd2d/gd"d3d4 Z ejd5d/gd"d6d7 Z!ejd8d/gd"d9d: Z"ejd;d/gd"d<d= Z#dS )?    )MongoClient)load_dotenvN)	Blueprintrequestjsonify)ObjectId)datetimec                  C   s"   t d} | stdt| ddS )z#Create and return a MongoDB client.Z	MONGO_URIz"MongoDB URI not found in .env filei )ZserverSelectionTimeoutMS)osgetenv
ValueErrorr   )uri r   </var/www/html/aiverses.in/BackEnd/app/database/fetch_data.pyget_mongo_client   s   
r   c                 C      | d }|d }t | S )z3Fetch all documents from the 'sections' collection.narrative_design_testsectionslistfindclientdb
collectionr   r   r   fetch_sections      r   c                 C   r   )z3Fetch all documents from the 'triggers' collection.r   triggersr   r   r   r   r   fetch_triggers    r   r   c                 C   r   )z;Fetch all documents from the 'mannual_triggers' collection.r   mannual_triggersr   r   r   r   r   fetch_mannual_triggers&   r   r   c                 C   r   )zAFetch all documents from the 'character_descriptions' collection.character_testcharacter_descriptionsr   r   r   r   r   fetch_characters,   r   r"   c                 C   sR   t d }|d }t|dd| idddiiddigi}|D ]}|dd	 q|S )
zk
    Fetch all characters belonging to a specific client, as well as public characters (no client_id).
    r    r!   z$or	client_idz$existsF _idN)r   r   r   pop)r#   r   r   
characters	characterr   r   r   get_characters_by_client_id2   s   
r)   c                 C   sh   t d }|d }d| i}|r||d< ||}|s,|r%td|  d| td|  |dd  |S )Nr    r!   character_idr#   &No character found with character_id: z for client_id: r%   )r   find_oner   r&   )r*   r#   db_2character_collectionqueryr(   r   r   r   get_character_by_idE   s   
r0   c                 C   sD   t d }|d }|d| id|i}|jdkrd|  S d|  dS )	z
    Updates a character's details in the database.
    
    :param character_id: The unique ID of the character to update.
    :param update_data: A dictionary with the fields to update.
    :return: Success message or error.
    r    r!   r*   $setr   r+   zCharacter with character_id  updated successfully.r   
update_oneZmatched_count)r*   Zupdate_datar-   r.   resultr   r   r   update_character_by_id[   s   

r6   c                 C   sh   | d }|d }| d|i}|d}|d }|d|idd|ii}|jdkr.d	| S d
| dS )a:  
    Updates the token usage for a character in the database.
    
    Args:
        client: The MongoDB client.
        character_id: The ID of the character to update.
        token_usage: The token usage to set.
    
    Returns:
        A success message or an error message if the character is not found.
    r    r!   r*   r#   clientsr1   Z
token_usedr   z#No client found with character_id: zToken usage for character_id r2   )r,   getr4   Zmodified_count)r   r*   Ztoken_usager   r   r5   r#   datar   r   r   update_token_usageq   s   



r:   c                 C   sN   t d }|d }|d| idd|ii}|jdkrd|  S d|  d	| d
S )z
    Updates the selected_character_id for a client in the database.
    :param client_id: The unique ID of the client to update.
    :param character_id: The character ID to set as selected.
    :return: Success message or error.
    r    r7   r#   r1   Zselected_character_idr   z No client found with client_id: zClient z$ updated with selected_character_id .r3   )r#   r*   r   Zclients_collectionr5   r   r   r   update_selected_character_id   s   


r<   c                    s@    fdd|D } fdd|D } fdd|D }|||fS )aq  
    Filter the arrays to keep only objects with the given character_id.
    
    Args:
        character_id: The character_id to filter by.
        mannual_triggers: List of mannual triggers.
        triggers: List of triggers.
        sections: List of sections.
    
    Returns:
        A tuple containing the filtered mannual_triggers, triggers, and sections.
    c                       g | ]}| d  kr|qS r*   r8   .0triggerr>   r   r   
<listcomp>       z/filter_data_by_character_id.<locals>.<listcomp>c                    r=   r>   r?   r@   r>   r   r   rC      rD   c                    r=   r>   r?   )rA   sectionr>   r   r   rC      rD   r   )r*   r   r   r   Zfiltered_mannual_triggersZfiltered_triggersZfiltered_sectionsr   r>   r   filter_data_by_character_id   s   
rF   apiz/api)
url_prefixz/get-objectiveGET)methodsc               
   C   s   t jd} t jd}| r|stddidfS z$t d }|d d| i}|s2tdd	id
fW S td|ddiW S  tyX } ztdt|idfW  Y d }~S d }~ww )N
section_idr*   errorz"Missing section ID or character ID  r   r   idSection not found  	objectiver$     r   argsr8   r   r   r,   	Exceptionstr)rK   r*   r   rE   er   r   r   get_objective   s   
 rX   z/get-sectionc               
      s   t jd} t jd z@t d }|d |  d}|s'tddidfW S  fd	d
|dg D }t|d |dd|dd||dg dW S  tyh } ztdt|idfW  Y d }~S d }~ww )NrK   r*   r   r   )rN   r*   rL   rO   rP   c                    r=   r>   r?   rA   dr>   r   r   rC      rD   zget_section.<locals>.<listcomp>	decisionsrN   labelr$   rQ   r   )rN   r\   rQ   r[   r   rR   r   rT   r8   r   r,   r   rU   rV   )rK   r   rE   Zfiltered_decisionsrW   r   r>   r   get_section   s&   




 r^   z/get-trigger-messagec               
   C   s   t jd} t jd}| r|stddidfS z#t d }|d | |d}|s1td	d
iW S td	|d	d
iW S  tyW } ztdt|idfW  Y d }~S d }~ww )N
trigger_idr*   rL   Missing required fieldsrM   r   r   r_   r*   messager$   rR   rS   )r_   r*   r   rB   rW   r   r   r   get_trigger_message   s   
 rc   z/load-nodesc               
   C   s   t jd} z*t d }|d d| i}t|r d|v r |d ng |r+d|v r+|d ng dW S  tyM } ztdt|dd	fW  Y d }~S d }~ww )
Nr*   
save-nodesdetailsnodesedgesrf   rg   zFailed to load nodesrL   re   rR   r]   )r*   r   r5   rW   r   r   r   
load_nodes   s   

"rj   z/save-nodesPOSTc               
   C   s   t  } | d}| dg }| dg }zt d }|d jd|id||didd	 td
diW S  tyO } ztdt|ddfW  Y d }~S d }~ww )Nr*   rf   rg   rd   re   r1   rh   TZupsertrb   z"Nodes and edges saved successfullyzFailed to save nodesri   rR   )r   get_jsonr8   r   r4   r   rU   rV   )r9   r*   rf   rg   r   rW   r   r   r   
save_nodes   s    

"rn   z/update-manual-triggerc               
   C   s   t  } | d}| d}| d}| d}| dd}| dd}|r,|r,|r,|s7td	g d
ddfS z;t d }||||||t  d}|d j||d|dt  iddd |d 	||d}	td|	dW S  t
y }
 ztdt|
ddfW  Y d }
~
S d }
~
ww )Nr_   destination_idr*   r\   descriptionr$   isActiveTr`   )r_   ro   r*   r\   )rL   requiredrM   r   )r_   r*   ro   r\   rp   rq   
updated_atr   ra   Z
created_at)r1   z$setOnInsertrl   )successrB   Internal Server Errorri   rR   )r   rm   r8   r   r   r   utcnow	isoformatr4   r,   rU   rV   )r9   r_   ro   r*   r\   rp   rq   r   Zmanual_trigger_docZupdated_triggerrW   r   r   r   update_manual_trigger  s<   





	"rx   z/update-sectionc            	   
      s   t  } | d}| d | d}| d}| dg }| dg }|s.tddid	fS z.t d
 }| || fdd|D |t d}|d jd|id|idd tdddW S  tyy } ztdt	|ddfW  Y d }~S d }~ww )NrN   r*   r\   rQ   r[   rB   rL   zMissing section IDrM   r   c                    s   g | ]
}i |d  iqS r>   r   rY   r>   r   r   rC   7  s    z"update_section.<locals>.<listcomp>)rN   r*   r\   rQ   r[   r   Z	updatedAtr   r1   Trl   zSection updated successfully)rt   rb   ru   ri   rR   )
r   rm   r8   r   r   r   rv   r4   rU   rV   )	r9   rN   r\   rQ   r[   rB   r   Zsection_docrW   r   r>   r   update_section%  s:   




	"ry   z/update-triggerc               
   C   s   t  } | d}| d}| d}| d}| d}|r!|s)tddidfS z!td	 }|d
 jd|id||||t didd tddiW S  tyg } ztdt	|ddfW  Y d }~S d }~ww )Nr_   rb   ro   typer*   rL   r`   rM   r   r   r1   )rb   ro   rz   r*   rs   Trl   rt   ru   ri   rR   )
r   rm   r8   r   r   r4   r   rv   rU   rV   )r9   r_   rb   ro   type_r*   r   rW   r   r   r   update_triggerD  s4   




"r|   z/uploadc               
   C   s   t jd} t jd}| stddidfS |s tddidfS z.td }|d }| j| jt| 	 t
 |d	}| jd
 ||}tdt|jdW S  tyk } ztdt|ddfW  Y d }~S d }~ww )Nfiler*   rL   zNo file uploadedrM   zCharacter ID is requiredZKnowledge_bankupload)filenameZcontentTypesizeZ
uploadDater*   r   zFile uploaded successfully)rb   r5   zError uploading fileri   rR   )r   filesr8   formr   r   r   content_typelenreadr   rv   streamseekZ
insert_onerV   Zinserted_idrU   )r}   r*   r   r   Z	file_datar5   rW   r   r   r   r~   _  s,   

"r~   )N)$Zpymongor   dotenvr   r	   flaskr   r   r   Zbsonr   r   r   r   r   r   r   r"   r)   r0   r6   r:   r<   rF   __name__Zapi_bprouterX   r^   rc   rj   rn   rx   ry   r|   r~   r   r   r   r   <module>   sL   








