import json
from typing import Dict, Any, List, Optional, Tuple
from utils.gemini_llm import GeminiLLM
from utils.logger import Logger, app_logger

class LLMQueryAnalyzer:
    """
    A class to analyze query intent using LLM instead of hardcoded patterns
    """
    
    def __init__(self, model_name: str = "gemini-2.0-flash", logger: Optional[Logger] = None):
        """Initialize the LLMQueryAnalyzer
        
        Args:
            model_name: Name of the LLM model to use
            logger: Optional logger instance
        """
        self.llm = GeminiLLM(
            model_name=model_name,
            temperature=0.1  # Low temperature for more deterministic results
        )
        self.logger = logger or app_logger
    
    def analyze_query(self, query: str) -> Dict[str, Any]:
        """
        Analyze the query using LLM to determine intent and extract relevant information
        
        Args:
            query: The user's query string
            
        Returns:
            Dict containing analysis results including intent, keywords, and optimized search queries
        """
        try:
            self.logger.info(f"Analyzing query with LLM: {query}")
            
            # Prepare the prompt for the LLM
            prompt = self._create_analysis_prompt(query)
            
            # Get response from LLM
            response = self.llm.generate(prompt)
            
            # Parse the response
            analysis = self._parse_llm_response(response, query)
            
            self.logger.info(f"Query analysis complete: {analysis['intent']} (confidence: {analysis['confidence']})")
            return analysis
            
        except Exception as e:
            self.logger.error(f"Error analyzing query with LLM: {str(e)}")
            # Return a basic analysis as fallback
            return self._fallback_analysis(query)
    
    def _create_analysis_prompt(self, query: str) -> str:
        """Create a prompt for the LLM to analyze the query"""
        return f"""
        You are an expert query analyzer for a RAG system. Your task is to analyze the following query and extract key information to help retrieve the most relevant information from a knowledge base about MangoIT Solutions, a software development company.
        
        Query: "{query}"
        
        Analyze this query and provide the following information in JSON format:
        1. intent: The primary intent of the query (one of: "technology", "service", "company_info", "industry", "approach", "other")
        2. confidence: Your confidence in the intent classification (0.0 to 1.0)
        3. keywords: A list of important keywords from the query
        4. is_tech_list_request: Boolean indicating if this is a request for listing technologies
        5. search_queries: A list of 3-5 optimized search queries that would help retrieve relevant information from a vector database
        
        IMPORTANT GUIDELINES FOR GENERATING SEARCH QUERIES:
        - Generate diverse search queries that approach the question from different angles
        - Include both specific and general queries to ensure broad coverage
        - For technology-related queries, create queries that would find specific technologies, frameworks, and programming languages
        - For service-related queries, create queries that would find specific services and capabilities
        - For company information queries, create queries that would find relevant company details
        - For industry-related queries, create queries that would find specific industries and sectors
        - Use synonyms and related terms to expand the search scope
        - Include the company name "MangoIT" in at least one query
        - Avoid overly generic queries that would return irrelevant information
        
        Respond ONLY with the JSON object, no additional text.
        """
    
    def _parse_llm_response(self, response: str, original_query: str) -> Dict[str, Any]:
        """Parse the LLM response into a structured analysis"""
        try:
            # Extract JSON from the response
            json_str = response.strip()
            
            # Handle potential text before or after the JSON
            if json_str.startswith("```json"):
                json_str = json_str.split("```json")[1]
            if "```" in json_str:
                json_str = json_str.split("```")[0]
                
            # Parse the JSON
            analysis = json.loads(json_str)
            
            # Ensure all required fields are present
            required_fields = ["intent", "confidence", "keywords", "is_tech_list_request", "search_queries"]
            for field in required_fields:
                if field not in analysis:
                    analysis[field] = "" if field == "intent" else [] if field in ["keywords", "search_queries"] else 0.5 if field == "confidence" else False
            
            # Add the original query
            analysis["original_query"] = original_query
            
            return analysis
            
        except Exception as e:
            self.logger.error(f"Error parsing LLM response: {str(e)}")
            return self._fallback_analysis(original_query)
    
    def _fallback_analysis(self, query: str) -> Dict[str, Any]:
        """Provide a fallback analysis when LLM fails"""
        # Simple keyword extraction
        keywords = [word for word in query.lower().split() if len(word) > 3]
        
        # Check if it might be a technology question
        is_tech_question = any(tech_word in query.lower() for tech_word in ["technology", "technologies", "tech", "stack", "framework", "programming", "language"])
        
        return {
            "original_query": query,
            "intent": "technology" if is_tech_question else "company_info",
            "confidence": 0.5,
            "keywords": keywords,
            "is_tech_list_request": is_tech_question,
            "search_queries": [
                query,  # Original query
                f"MangoIT {' '.join(keywords)}",  # Query with company name
                "MangoIT technologies frameworks programming languages"  # Generic tech query
            ]
        }
