"""
Specialized prompt templates for different query types.
These templates help the agent provide more specific and helpful responses.
"""

from typing import Dict, Any, List, Optional
from utils.agent_config import agent_config
from utils.user_context_extractor import user_context_extractor
from utils.company_info import COMPANY_NAME, OFFICE_ADDRESS, CONTACT_EMAIL, CONTACT_PHONE, WEBSITE, SCHEDULING_LINK, BUSINESS_HOURS, MEETING_AVAILABILITY

class PromptTemplates:
    """Collection of specialized prompt templates for different query types"""
    
    @staticmethod
    def get_technical_prompt(query: str, 
                            retrieved_info: Dict[str, Any], 
                            conversation_history: str,
                            detected_technologies: Optional[List[str]] = None) -> str:
        """
        Generate a prompt template for technical queries
        
        Args:
            query: The user's query
            retrieved_info: Information retrieved from the knowledge base
            conversation_history: Previous conversation history
            detected_technologies: List of technologies mentioned in the query
            
        Returns:
            str: Formatted prompt for the LLM
        """
        # Extract content snippets from retrieved info
        content_snippets = []
        if isinstance(retrieved_info.get("results"), list):
            for result in retrieved_info.get("results", [])[:5]:
                if "content" in result:
                    content_snippets.append(result.get("content", "")[:300])
        
        # Format detected technologies if available
        tech_context = ""
        if detected_technologies and len(detected_technologies) > 0:
            tech_list = ", ".join(detected_technologies)
            tech_context = f"\nThe user has mentioned or asked about these specific technologies: {tech_list}."
        
        # Get length instruction based on config
        length_instruction = ""
        if agent_config.RESPONSE_LENGTH == "concise":
            length_instruction = "Keep your response brief and to the point, no more than 2-3 sentences unless detailed information is specifically requested."
        elif agent_config.RESPONSE_LENGTH == "detailed":
            length_instruction = "Provide comprehensive and detailed information in your response."
        
        # Build the prompt
        prompt = f"""You are {agent_config.AGENT_NAME}, the AI assistant for {agent_config.COMPANY_NAME}, a software export company based in Indore, India.
        
Previous conversation:
{conversation_history}

User's technical query: {query}{tech_context}

When responding to technical questions, follow these guidelines:
1. Be specific and detailed about technologies, frameworks, and tools used at MangoIT
2. Provide concrete examples of projects or use cases when relevant
3. Demonstrate deep technical knowledge and expertise
4. Mention specific versions, features, or advantages of technologies when appropriate
5. If you don't have specific information, be honest but suggest related technologies MangoIT does work with
6. {length_instruction}

Technical information from knowledge base:
{chr(10).join(content_snippets) if content_snippets else "No specific technical information found in knowledge base."}

MangoIT's core technical capabilities include:
- Frontend: React, Angular, Vue.js, Next.js, Svelte
- Backend: Node.js, Python (Django/Flask), PHP (Laravel/Symfony), Java (Spring), .NET Core
- Mobile: React Native, Flutter, Swift, Kotlin
- AI/ML: TensorFlow, PyTorch, Hugging Face transformers, LangChain, OpenAI API
- Cloud: AWS, Azure, Google Cloud, Digital Ocean
- Database: MongoDB, PostgreSQL, MySQL, Redis, Elasticsearch
- DevOps: Docker, Kubernetes, Jenkins, GitHub Actions, GitLab CI/CD

Respond to the user's technical query with specific, accurate, and helpful information:
"""
        return prompt
    
    @staticmethod
    def get_pricing_prompt(query: str, 
                          retrieved_info: Dict[str, Any], 
                          conversation_history: str,
                          project_type: Optional[str] = None) -> str:
        """
        Generate a prompt template for pricing queries
        
        Args:
            query: The user's query
            retrieved_info: Information retrieved from the knowledge base
            conversation_history: Previous conversation history
            project_type: Type of project being discussed
            
        Returns:
            str: Formatted prompt for the LLM
        """
        # Extract content snippets from retrieved info
        content_snippets = []
        if isinstance(retrieved_info.get("results"), list):
            for result in retrieved_info.get("results", [])[:3]:
                if "content" in result:
                    content_snippets.append(result.get("content", "")[:300])
        
        # Project context
        project_context = f"\nThe user is asking about pricing for: {project_type}" if project_type else ""
        
        # Get length instruction based on config
        length_instruction = ""
        if agent_config.RESPONSE_LENGTH == "concise":
            length_instruction = "Keep your response brief and to the point, no more than 2-3 sentences unless detailed information is specifically requested."
        elif agent_config.RESPONSE_LENGTH == "detailed":
            length_instruction = "Provide comprehensive and detailed information in your response."
        
        # Build the prompt
        prompt = f"""You are {agent_config.AGENT_NAME}, the AI assistant for {agent_config.COMPANY_NAME}, a software export company based in Indore, India.
        
Previous conversation:
{conversation_history}

User's pricing query: {query}{project_context}

When responding to pricing questions, follow these guidelines:
1. Be transparent about pricing ranges while noting that exact pricing depends on project specifics
2. Provide hourly rates for different developer levels when appropriate
3. Mention project-based and dedicated team pricing models
4. Explain factors that affect pricing (complexity, timeline, features)
5. Always offer to connect the user with a sales representative for a detailed quote
6. Never make up exact prices if you don't have the information
7. {length_instruction}

Pricing information from knowledge base:
{chr(10).join(content_snippets) if content_snippets else "No specific pricing information found in knowledge base."}

MangoIT's general pricing structure:
- Junior developers: $25-40/hour
- Mid-level developers: $40-60/hour
- Senior developers/architects: $60-90/hour
- Project-based pricing available for well-defined projects
- Dedicated team model available for ongoing development needs
- Discounts available for long-term engagements

Respond to the user's pricing query with transparent, helpful information:
"""
        return prompt
    
    @staticmethod
    def get_scheduling_prompt(query: str, 
                             retrieved_info: Dict[str, Any], 
                             conversation_history: str,
                             meeting_details: Optional[Dict[str, Any]] = None) -> str:
        """
        Generate a prompt template for scheduling queries
        
        Args:
            query: The user's query
            retrieved_info: Information retrieved from the knowledge base
            conversation_history: Previous conversation history
            meeting_details: Details about the requested meeting
            
        Returns:
            str: Formatted prompt for the LLM
        """
        # Format meeting details if available
        meeting_context = ""
        if meeting_details:
            details = []
            if meeting_details.get("date"):
                details.append(f"Date: {meeting_details['date']}")
            if meeting_details.get("time"):
                details.append(f"Time: {meeting_details['time']}")
            if meeting_details.get("timezone"):
                details.append(f"Timezone: {meeting_details['timezone']}")
            if meeting_details.get("topic"):
                details.append(f"Topic: {meeting_details['topic']}")
                
            if details:
                meeting_context = "\nThe user has provided these meeting details:\n- " + "\n- ".join(details)
        
        # Get length instruction based on config
        length_instruction = ""
        if agent_config.RESPONSE_LENGTH == "concise":
            length_instruction = "Keep your response brief and to the point, no more than 2-3 sentences unless detailed information is specifically requested."
        elif agent_config.RESPONSE_LENGTH == "detailed":
            length_instruction = "Provide comprehensive and detailed information in your response."
        
        # Build the prompt
        prompt = f"""You are {agent_config.AGENT_NAME}, the AI assistant for {COMPANY_NAME}, a software export company based in Indore, India.
        
Previous conversation:
{conversation_history}

User's scheduling query: {query}{meeting_context}

When responding to scheduling requests, follow these guidelines:
1. Collect necessary information: preferred date/time, timezone, meeting topic, contact details
2. Explain the next steps in the scheduling process clearly
3. Offer multiple contact options (email, phone, direct scheduling link)
4. Set clear expectations about when they will receive confirmation
5. If all details are provided, confirm that the request will be sent to the scheduling team
6. Always maintain a helpful and professional tone
7. {length_instruction}

Scheduling information:
- Office address: {OFFICE_ADDRESS['full']}
- Business hours: {BUSINESS_HOURS}
- Meeting availability: {MEETING_AVAILABILITY}
- Email: {CONTACT_EMAIL}
- Phone: {CONTACT_PHONE}
- Online scheduling: {SCHEDULING_LINK}

Respond to the user's scheduling request with clear, actionable information:
"""
        return prompt
    
    @staticmethod
    def get_general_prompt(query: str, 
                          retrieved_info: Dict[str, Any], 
                          conversation_history: str) -> str:
        """
        Generate a prompt template for general queries
        
        Args:
            query: The user's query
            retrieved_info: Information retrieved from the knowledge base
            conversation_history: Previous conversation history
            
        Returns:
            str: Formatted prompt for the LLM
        """
        # Extract content snippets from retrieved info
        content_snippets = []
        if isinstance(retrieved_info.get("results"), list):
            for result in retrieved_info.get("results", [])[:5]:
                if "content" in result:
                    content_snippets.append(result.get("content", "")[:300])
        
        # Get length instruction based on config
        length_instruction = ""
        if agent_config.RESPONSE_LENGTH == "concise":
            length_instruction = "Keep your response brief and to the point, no more than 2-3 sentences unless detailed information is specifically requested."
        elif agent_config.RESPONSE_LENGTH == "detailed":
            length_instruction = "Provide comprehensive and detailed information in your response."
        
        # Build the prompt
        prompt = f"""You are {agent_config.AGENT_NAME}, the AI assistant for {COMPANY_NAME}, a software export company based in Indore, India.
        
Previous conversation:
{conversation_history}

User's query: {query}

When responding to general questions, follow these guidelines:
1. Be friendly, helpful, and professional but concise
2. Provide accurate information about MangoIT's services and capabilities
3. If the query is unclear, politely ask for clarification
4. If you don't have specific information, be honest but provide related helpful information
5. Always aim to move the conversation toward MangoIT's services and how they can help the user
6. Avoid unnecessary repetition of company information if already mentioned in the conversation
7. {length_instruction}

Information from knowledge base:
{chr(10).join(content_snippets) if content_snippets else "No specific information found in knowledge base."}

About MangoIT:
- Founded in 2008 in Indore, India
- Provides software development services globally
- Specializes in web, mobile, and AI development
- Has delivered over 3000 projects
- Serves clients in the US, Europe, Australia, and other regions
- Known for high-quality, cost-effective solutions

Company contact information:
- Office address: {OFFICE_ADDRESS['full']}
- Email: {CONTACT_EMAIL}
- Phone: {CONTACT_PHONE}
- Website: {WEBSITE}

Respond to the user's query with helpful, accurate, and concise information:
"""
        return prompt
