o
    d6i+                     @   s   d Z ddlZddlmZ ddlmZmZ ddlmZ ddlm	Z	 ddl
mZ ddlmZ eeZd	ed
efddZdeded
dfddZdeded
efddZ		ddedededededed
efddZdS )z
Main LLM module for Karishye AI chat functionality.

This module contains the main chat_with_karishye function that orchestrates
the conversation flow with natural AI-driven booking (no rigid question flow).
    N)datetime)karishye_agentChatContext)karishye_agent_tools)load_chat_history)get_user_puja_state)PUJA_PATTERNStextreturnc                 C   s   ddl }| sdS |jdd| |jd} |dd| } |jdd	| |jd} |d
d| } |dd| } |dd| } |dd| } |jdd| |jd} |jdd| |jd} |dd| } |dd| } |  S )u  
    Convert markdown to WhatsApp format with proper spacing and readability.
    
    Converts:
    - Headers (# text) → text with spacing (plain text, no bold)
    - Bold (**text**) → *text*
    - Italic (_text_) → _text_ (preserved)
    - Links [text](url) → text: url
    - Lists → • item (bullets) or numbered
    - Code blocks → preserved with backticks
    - Removes HTML tags
    r   N z```[\w]*\n?(.*?)```z\1)flagsz<[^>]+>z^#{1,6}\s+(.+)$z\1\nz\*\*(.+?)\*\*z*\1*z	__(.+?)__z	~~(.+?)~~z~\1~z\[([^\]]+)\]\(([^\)]+)\)z\1: \2z
^[\*\-]\s+u   • z^(\d+)\.\s+z\1. z\n{3,}z

u   (\*[^\*]+\*)\n([•\d])z\1\n\n\2)resubDOTALL	MULTILINEstrip)r	   r    r   +/var/www/html/karishye-ai-python/app/llm.py_format_for_whatsapp   s   r   user_id
session_idc                 C   s   |st d tddS )zValidate required chat inputs.z'[chat_with_karishye] Missing session_idz*session_id is required for chat operationsN)loggererror
ValueError)r   r   r   r   r   _validate_chat_inputsW   s   
r   c                 C   sR   t  D ]"\}}|d|}t| ||}|r&|dr&|ds&||f  S qdS )z
    Find any active puja session for the user.
    
    Returns:
        tuple: (active_puja_state, active_puja_key) or (None, None)
    questions_key	puja_name	completed)NN)r   itemsgetr   )r   r   pattern_keypattern_infor   stater   r   r   _find_active_puja_session^   s   
r#   defaultFuser_messagephone_number	user_nameformat_for_whatsappc              
      s  zt || td g }|rt|ddI dH }d}|r@t|dkr@d}|D ]}|d d	kr1d
nd}	||	 d|d  d7 }q't||\}
}d}|
ry|
dsy|
dd}|
di }|ryd| d}|rud| }|d| d7 }|d7 }d}|rd| d}| | | d|  }t	||||}ddl
}|
 }tj||dI dH }|
 }|| }t|dr|j nt|}td|dd |rt|}|W S  ty } ztdt|j  d t| }|W  Y d}~S d}~ww )!a  
    Main chat function with natural AI-driven booking flow.
    
    The AI agent now handles everything naturally:
    - Detects puja interest
    - Collects information conversationally (no rigid questions)
    - Name and phone are auto-provided from WhatsApp
    - Determines when enough info is gathered
    - Handles urgency and empathy naturally
    
    Args:
        user_message: The user's message
        user_id: User's unique identifier (required)
        session_id: Session identifier (required for proper session isolation)
        phone_number: Pre-collected phone number from WhatsApp
        user_name: Pre-collected user name from WhatsApp
        format_for_whatsapp: If True, format response for WhatsApp (plain text), else use markdown for web
    z,[chat_with_karishye] Processing chat request
   )limitNr   r   z

Recent conversation context:
type	assistant	AssistantUserz: message
r   r   collected_infoz&

[Context: User is currently booking z. z, zAlready collected: z2Continue gathering missing information naturally.]z

[User's name: zr. Use naturally with 'garu' in appropriate contexts - confirmations, empathy, important questions. Don't overuse.]z

Current message: )depsoutputz![chat_with_karishye] Response in z.2fsz[chat_with_karishye] Error: zGI apologize, but I encountered an error while processing your request: )r   r   debugr   lenr#   r   joinkeysr   timer   runhasattrr3   r   strinfor   	Exceptionr   r+   __name__)r%   r   r   r&   r'   r(   chat_historyhistory_contextentryroleactive_puja_stateactive_puja_keybooking_contextr   r1   collected_fieldsname_contextenhanced_messagechat_contextr9   
start_timeresultend_timeresponse_timeresponseeerror_responser   r   r   chat_with_karishyeu   sZ   

rR   )r$   NNNF)__doc__loggingr   app.agents.agentsr   r   
app.agentsr   app.utils.conversation_utilsr   app.utils.utilsr   app.constantsr   	getLoggerr?   r   r<   r   r   tupler#   boolrR   r   r   r   r   <module>   s.    
;