
    ei                     .   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mZmZmZmZmZmZmZ ddlmZ  e j0                  e      Z e       Zej9                  d	ed
g       ee      fdedefd       Zej=                  ded
g       edd       edd       edd       eddd       edddd       ee      fdedededededefd        Z ej=                  d!ed
g       ee      fd"e!defd#       Z"y# e	$ r	 d dl
mZ Y w xY w)$    N)	APIRouterDependsQuery)Session)get_db   )
controller)ChatRequestChatResponseChatDataChatErrorResponseChatHistoryListResponseChatHistoryDetailResponseChatSessionListItemChatSessionDetail)chat_history_servicez/chatzSmart Inventory - Frontend)response_modeltagsrequestdbc                     	 t        j                  || j                  | j                  | j                  | j
                  | j                  | j                        }t        dt        di |d      S # t        $ r}t        j                  dt        |              ddlm} | j                  }|.	 |j!                  | j                        }n# t        $ r d	}Y nw xY wt        d
t        |ddt        |             d      cY d}~S d}~ww xY w)a^  
    AI-powered chat endpoint for querying inventory data using natural language.
    Supports continuous conversation with context memory.
    All conversations are persisted to the database.
    
    **Session Management:**
    - **First message**: Send `chat_session_id: null` to start a new conversation
    - **Response**: You'll receive a `chat_session_id` in the response
    - **Follow-up**: Send the same `chat_session_id` to continue the conversation
    - **New chat**: Send `chat_session_id: null` again to start fresh
    - **Context**: Last 5 questions and answers are sent to LLM for context
    
    **Example questions:**
    - "What are the top 10 fast-moving products?"
    - "Tell me more about the first one" (follow-up)
    - "What about location 2?" (follow-up with context)
    - "Show me products that are out of stock"
    
    **Request body:**
    ```json
    {
        "chat_session_id": null,  // or existing session ID
        "company_id": 1,
        "user_id": 1,
        "store_id": 1,
        "branch_id": 1,
        "question": "What are my top selling products?"
    }
    ```
    )r   
company_idquestionuser_idstore_id	branch_idchat_session_idTzQuery processed successfullysuccessdatamessagez"Error in inventory chat endpoint: r   )chat_session_serviceNzerror-sessionFz2An error occurred while processing your question: )r   raw_dataanswerzError processing query )r	   process_chat_queryr   r   r   r   r   r   r   r   	Exceptionloggererrorstrservicesr"   create_session)r   r   resulter"   
session_ids         G/var/www/html/hubwallet-dev/src/smart_inventory/apps/chat_bot/router.pyinventory_chatr1      s   F%
..))%%OO%%''#33
 #F#2
 	
  
9#a&BC 	3,,
-1@@ASAST
 -,
-  *KCPQF8T
 -
 	

sB   A.A1 1	D:5D0CDCDC(DDDz/chat/history.zUser ID)descriptionzStore IDz	Branch IDzPage number (1-indexed))ger2      d   zNumber of items per page)r3   ler2   r   r   r   page	page_sizec                 B   	 t        j                  || ||||      \  }}t        d|D cg c]  }t        d
i | c}|||d      S c c}w # t        $ rH}	t
        j                  dt        |	              t        dg d||dt        |	             cY d	}	~	S d	}	~	ww xY w)a  
    Get paginated list of chat sessions for a user/store/branch.
    
    Returns chat sessions ordered by most recently updated first.
    Each session includes:
    - `chat_session_id`: Use this to open/continue a chat
    - `chat_name`: Derived from the first question asked
    - `message_count`: Total number of messages in the conversation
    
    **Usage:**
    - Display as a list of previous chats in the sidebar
    - Click on a chat to load its details using the `/chat/history/{chat_session_id}` endpoint
    )r   r   r   r   r7   r8   Tz#Chat history retrieved successfully)r   r    totalr7   r8   r!   z!Error getting chat history list: Fr   zError retrieving chat history: Nr%   )r   get_chat_history_listr   r   r'   r(   r)   r*   )
r   r   r   r7   r8   r   sessionsr:   sr.   s
             r0   r;   r;   b   s    ,
.DD
% '4<=q%**=9
 	
=  	
8QAB&5c!fX>
 	
	
s-   (A A
A A 	B=BBBz/chat/history/{chat_session_id}r   c           	      "   	 t        j                  ||       }|t        ddd      S t        dt        d
i |d      S # t        $ rE}t
        j                  dt        |              t        ddd	t        |             cY d}~S d}~ww xY w)aZ  
    Get detailed chat session with all messages.
    
    Use this endpoint when user clicks on a chat from the history list.
    Returns all messages in chronological order.
    
    **Usage:**
    - Load all messages to display the full conversation
    - User can continue the chat by sending new messages with the same `chat_session_id`
    )r   r   NFzChat session not foundr   Tz#Chat session retrieved successfullyz#Error getting chat history detail: zError retrieving chat session: r%   )r   get_chat_session_detailr   r   r'   r(   r)   r*   )r   r   session_detailr.   s       r0   get_chat_history_detailrA      s    
-EE+

 !,0  )"4^49
 	
  
:3q6(CD(5c!fX>
 	

s"   &A  A   	B	:B	B	B)#loggingfastapir   r   r   sqlalchemy.ormr   src.utils.dbr   ImportErrorutils.db r	   schemasr
   r   r   r   r   r   r   r   r+   r   	getLogger__name__r(   routerpostr1   getintr;   r*   rA   r%       r0   <module>rQ      s    - - " #   
 +			8	$	 W\9U8VW &/G
G
G
 XG
T O,CKgJhi)4#:63K8aA+DE2!9ST&/1
1
1
 1
 	1

 1
 	1
 j1
h ->W_{^|} &/'
'
'
 ~'
c    s   D DD