o
    d6i9                  	   @   s   d Z ddlZddlZddlmZ ddlmZmZmZ ddl	m
Z
 ddlmZ eeZejdedefd	d
ZejddededefddZejdedefddZejdee dededefddZdS )a^  
Agent tools for the Karishye AI agent.

This module contains all tool functions that the karishye_agent can call:
- search_structured_knowledge_base: Search Karishye knowledge base
- get_puja_information_and_pricing: Get puja pricing, samagri, and detailed info from API
- generate_booking_confirmation: Generate final booking confirmation with URL
    N)
RunContext)karishye_agentgeneral_agentChatContext)needs_muhurtam_question)get_puja_infoqueryreturnc                    s  z#ddl }ddlm} |t }|jjj}|d }|d }| s'W dS |jddd	}| }W d   n1 s=w   Y  d
| d|  d}	t	
|	I dH }
|
j }g }z|d||j}|ruddl}|d|d d}W n  ty } ztd|  |d|}W Y d}~nd}~ww |std W dS tdt| d g }|dd D ]]}||  }| r	z)|jddd	}| }|d| d| d W d   n1 sw   Y  W q ty } ztd| d|  W Y d}~qd}~ww td|  q|sW dS d|}d | d!}|W S  tyD } ztd"t|j  W Y d}~d#S d}~ww )$ai  
    NEW: Search the structured Karishye knowledge base using intelligent file navigation.
    
    This tool:
    1. First reads the index.md to understand the knowledge base structure
    2. Uses AI to determine which specific MD files are most relevant to the query
    3. Reads those specific files and returns their content
    4. Provides comprehensive, structured information from official documentation
    
    Use this tool for ANY question about:
    - Karishye's vision, mission, goals, values
    - Pujaris, their role, selection, and benefits
    - Specific homams/pujas (Ganapati, Saraswati, Maha Mrityunjaya, etc.)
    - Services, approach, quality standards
    - Sanatana Dharma concepts
    - My Dharma platform
    
    Args:
        query: User's question or topic to search for
    
    Returns:
        Relevant content from knowledge base files
    r   N)Pathzknowledge-basezindex.mdzTKnowledge base index not found. Please ensure the knowledge base is properly set up.rzutf-8)encodingzBased on this knowledge base index structure and the user's query, identify the MOST relevant markdown files to read.

KNOWLEDGE BASE INDEX:
z

USER QUERY: uK  

Analyze the query and return ONLY a JSON array of file paths relative to the knowledge base root.
Consider:
- Direct topic matches (e.g., "Ganapati Homam" → 04-services/03-ganapati-homam.md)
- Related topics (e.g., "health puja" → health-related homam files)
- Conceptual matches (e.g., "why Karishye" → vision/mission files)
- Multiple relevant files if the query is broad

Return 1-4 most relevant files. Format: ["path/file.md", "path/file.md"]
If query is about multiple homams or general services, include the overview file.

RESPOND WITH ONLY THE JSON ARRAY, NO OTHER TEXT.z	\[(.*?)\][   ]zFailed to parse file paths: z["\']([^"\']+\.md)["\']zNo files identified for queryziI couldn't identify the specific files to answer your question. Let me search the general knowledge base.zIdentified z relevant files   z
=== FROM: z ===

zError reading z: zFile not found: zYI found relevant topics but couldn't read the files. Please try rephrasing your question.z

z[Knowledge Base Information]

z

[End of Knowledge Base Information]

This information is from Karishye's official knowledge base. Use it to provide a comprehensive, accurate answer to the user's question.z[KB TOOL] Error: zXI'm having trouble accessing the knowledge base right now. Please try again in a moment.)repathlibr
   __file__resolveparentexistsopenreadr   runoutputstripsearchDOTALLjsonloadsgroup	Exceptionloggerwarningfindalldebuglenappenderrorjointype__name__)r   r   r
   current_fileproject_rootkb_base_path
index_pathfindex_contentselection_promptfile_selection_resultfile_paths_text
file_paths
json_matchjson_libparse_errorretrieved_content	file_path	full_pathcontent
read_errorcombined_contentresulte rB   C/var/www/html/karishye-ai-python/app/agents/karishye_agent_tools.py search_structured_knowledge_base   s~   




"
rD   Finclude_pricingc              
      s\   zt | d|dI dH }|W S  ty- } ztdt|j  dW  Y d}~S d}~ww )u  
    Get puja information from Karishye's backend API - with SPIRITUAL-FIRST approach.
    
    **CRITICAL: Use include_pricing parameter correctly:**
    - include_pricing=False (DEFAULT): Returns ONLY spiritual/ritual details (NO pricing)
    - include_pricing=True: Returns spiritual details + pricing breakdown
    
    **TOKEN-OPTIMIZED APPROACH:**
    This tool uses an intelligent multi-tier search strategy to minimize token usage:
    
    TIER 1 - Simple Keyword Matching (FREE, INSTANT):
    - Extracts lightweight index (just names, IDs, categories) from cache
    - Uses fast keyword matching on index
    - Works for 90% of queries like "Ganapati Homam", "Naamakaranam", etc.
    - Zero LLM tokens used
    
    TIER 2 - LLM Semantic Matching (MINIMAL TOKENS):
    - Triggered only if keyword search finds nothing
    - Sends only lightweight index to LLM (not full data)
    - LLM intelligently matches query to puja IDs
    - Example: "puja for new baby" → finds "Naamakaranam"
    
    TIER 3 - Detailed Fetch (OPTIMIZED):
    - Fetches full details only for matched pujas
    - Returns rich information: ritual details, duration, samagri (and pricing if requested)
    
    This saves 80-90% of tokens compared to sending all puja data to LLM!
    
    **When to use include_pricing=False (DEFAULT):**
    - "Tell me about [puja]"
    - "What is [puja]?"
    - "Explain [puja] procedure"
    - "Benefits of [puja]"
    - "What happens in [puja]?"
    
    **When to use include_pricing=True:**
    - "How much is [puja]?"
    - "What's the cost of [puja]?"
    - "Price for [puja]"
    - "I want to book [puja]"
    
    Args:
        query: User's question about puja
               Example: "Ganapati Homam", "puja for new baby", "Rudrabhishekam procedure"
        include_pricing: If False (default), returns only spiritual/ritual details.
                        If True, includes pricing breakdown.
    
    Returns:
        Formatted puja information (spiritual details always; pricing only if requested)
    T)use_llmrE   Nz[PUJA API TOOL] Error: zI apologize, but I'm having trouble accessing the puja information right now. Please try again in a moment, or contact our support team for details.)r   r"   r#   r)   r+   r,   )r   rE   r@   rA   rB   rB   rC    get_puja_information_and_pricing   s   4rG   puja_keyc                    sV   ddl m}m} || }|r| std|  d |}td|  d|  |S )a  
    Get the advance payment URL for a specific puja.
    
    **WHEN TO USE:**
    - When user asks "where do I pay?" or "send me the payment link"
    - When you need to share the payment URL at any point in the conversation
    - When user wants to proceed but you're still collecting some details
    - When user asks about the booking/payment process
    - Can be used BEFORE collecting all details if user specifically requests the link
    
    **URL LOGIC:**
    - Returns puja-specific URL from PUJA_BOOKING_URLS if available
    - Falls back to general collection page if puja-specific URL not found
    - Always returns a valid URL (never empty)
    
    Args:
        puja_key: The internal puja key (e.g., "ganapathi_homam", "gruhapravesham")
    
    Returns:
        The payment URL for the specified puja
    
    Example:
        url = await get_puja_advance_payment_url("ganapathi_homam")
        # Returns: "https://karishye.co/products/ganapati-homam-telugu"
    r   )get_puja_booking_urlDEFAULT_BOOKING_URLz0[TOOL:get_payment_url] Empty URL for puja_key: 'z', using defaultz*[TOOL:get_payment_url] Retrieved URL for 'z': )app.constantsrI   rJ   r   r#   r)   info)rH   rI   rJ   booking_urlrB   rB   rC   get_puja_advance_payment_url   s   rN   ctx	puja_namec                    s   t |I dH }td| d|  g dj|ddddddd	d
j|ddddddddddddddddddddddddddddddddd}d|}|S )a  
    Generate a professional confirmation message when ALL details are collected.
    
    **CRITICAL: CALL THIS TOOL ONLY ONCE PER PUJA**
    - Once you've sent the booking confirmation for a specific puja, DO NOT call this tool again for that SAME puja
    - If user asks about customization/requirements for a puja AFTER its confirmation is sent, 
      reassure them and reference the payment link already shared for that specific puja
    - DO NOT regenerate confirmations for the same puja
    - **Multiple pujas OK**: User can book multiple different pujas - each puja gets ONE confirmation
    
    **WHEN TO USE:**
    - When you have collected ALL required information for a specific puja:
      * Location (city/area in AP/TG)
      * Date (preferred date/timeframe)
      * Muhurtam (if needed for this puja type)
    - User has completed providing all required information for this puja
    - You're ready to send the final confirmation with payment link
    - **AND you haven't sent a confirmation for THIS specific puja yet**
    
    **DO NOT USE:**
    - When still collecting information for this puja
    - When missing any required fields (location, date, or muhurtam if needed)
    - Just to get the payment URL (use get_puja_advance_payment_url instead)
    - **When you've already sent a booking confirmation for THIS specific puja**
    
    **NOTE:** This tool automatically calls get_puja_advance_payment_url to fetch the URL.
    
    Args:
        puja_name: The display name of the puja (e.g., "Ganapati Homam", "Gruhapravesha Puja")
        puja_key: The internal puja key (e.g., "ganapathi_homam", "gruhapravesham")
    
    Returns:
        A warm, professional confirmation message with booking URL and next steps
    Nz:[TOOL:generate_confirmation] Generating confirmation for 'z' with URL: u   🙏 Thank you for providing all the details for your sacred {puja_name} with such reverence. May this divine ritual bring abundant blessings to you and your loved ones.)rP    z**Next Sacred Steps:**zhTo **secure your preferred slot/date** and start the coordination, kindly proceed with the confirmation:z**Confirmation Link:**z"[Complete Your Arrangement]({url}))urlz**What Happens Next:**u   • **Minimal Advance Payment:** A small token amount to reserve your sacred date and pujari (fully refundable, no questions asked if you change your mind)u   • **Personal Connect:** Our dedicated team will reach out **at the earliest** to confirm all arrangements and help with muhurtam if neededun   • **Final Preparations:** We'll guide you through any preparatory requirements and answer all your questionsz**Our Sacred Promise to You:**zAt Karishye, every puja is performed with the highest spiritual integrity. Our Pujaris are chosen not just for their knowledge, but for their:u[   • **Deep Reverence** – Profound understanding of Vedic scriptures and sacred traditionsuS   • **Pure Conduct** – Adherence to _tapas_, _brahmacharya_, and righteous livinguS   • **Compassionate Hearts** – Gentle, selfless nature that radiates divine graceue   • **Spiritual Authority** – Years of training in proper ritual execution and mantra pronunciationzEach ritual is conducted with complete _shraddha_ (devotion) to invoke the blessings of the Divine for your family's spiritual upliftment.z**We Are Here for You:**zShould you have any questions about ritual preparations, samagri requirements, or the sacred significance of any aspect, please don't hesitate to ask. We're honored to guide you on this spiritual journey.zC**May the Divine bless your endeavor with success and prosperity.**uD   ఓం శాంతిః శాంతిః శాంతిః 🙏r   )rN   r#   rL   formatr*   )rO   rP   rH   rM   response_partsfinal_messagerB   rB   rC   generate_booking_confirmation   s   %

	
 !"#$%&'(
+rV   )F)__doc__loggingr   pydantic_air   app.agents.agentsr   r   r   rK   r   app.utils.puja_api_cacher   	getLoggerr,   r#   
tool_plainstrrD   boolrG   rN   toolrV   rB   rB   rB   rC   <module>   s     	
z?)$