"""
Report detail levels module for the intelligent research system.

This module provides functionality to define and configure different levels of detail
for generated reports, allowing users to customize the depth and breadth of information
included in reports.
"""

import enum
from typing import Dict, Any, Optional, List, Tuple


class DetailLevel(enum.Enum):
    """Enum for different report detail levels."""
    BRIEF = "brief"
    STANDARD = "standard"
    DETAILED = "detailed"
    COMPREHENSIVE = "comprehensive"


class ReportDetailLevelManager:
    """
    Manager for report detail levels.
    
    This class provides methods to get configuration parameters for different
    report detail levels, allowing users to customize the depth and breadth of
    information included in reports.
    """
    
    def __init__(self):
        """Initialize the report detail level manager."""
        # Define default configurations for different detail levels
        self.detail_level_configs = {
            DetailLevel.BRIEF: {
                "num_results": 3,
                "token_budget": 50000,
                "chunk_size": 800,
                "overlap_size": 50,
                "model": "llama-3.1-8b-instant",
                "description": "A concise summary of key findings and conclusions."
            },
            DetailLevel.STANDARD: {
                "num_results": 7,
                "token_budget": 100000,
                "chunk_size": 1000,
                "overlap_size": 100,
                "model": "llama-3.1-8b-instant",
                "description": "A balanced report with key findings, analysis, and conclusions."
            },
            DetailLevel.DETAILED: {
                "num_results": 12,
                "token_budget": 150000,
                "chunk_size": 1200,
                "overlap_size": 150,
                "model": "llama-3.3-70b-versatile",
                "description": "A comprehensive report with in-depth analysis, methodology, and implications."
            },
            DetailLevel.COMPREHENSIVE: {
                "num_results": 12,
                "token_budget": 200000,
                "chunk_size": 1200,
                "overlap_size": 120,
                "model": "gemini-2.0-flash-lite",
                "description": "An exhaustive report with all available information, extensive analysis, and detailed references."
            }
        }
        
        # Define template modifiers for different detail levels
        self.template_modifiers = {
            DetailLevel.BRIEF: {
                "factual": "Create a brief factual report that directly answers the query. Focus on accuracy and clarity. Include:\n"
                           "1. A clear, direct answer to the query\n"
                           "2. Key supporting evidence and facts\n"
                           "3. Citations for information (use numbered citations in square brackets [1], [2], etc.)\n"
                           "4. A concise references section\n\n"
                           "Keep the report concise and to the point, focusing only on the most essential information.",
                
                "comparative": "Create a brief comparative report that analyzes different perspectives on the query. Include:\n"
                              "1. A concise overview of the topic\n"
                              "2. Key similarities and differences between perspectives\n"
                              "3. Citations for information (use numbered citations in square brackets [1], [2], etc.)\n"
                              "4. A concise references section\n\n"
                              "Keep the report concise and to the point, focusing only on the most essential comparisons.",
                
                "exploratory": "Create a brief exploratory report that investigates the query. Include:\n"
                              "1. A concise introduction to the topic\n"
                              "2. Key findings and insights\n"
                              "3. Citations for information (use numbered citations in square brackets [1], [2], etc.)\n"
                              "4. A concise references section\n\n"
                              "Keep the report concise and to the point, focusing only on the most essential information."
            },
            
            DetailLevel.STANDARD: {
                "factual": "Create a standard factual report that directly answers the query. Focus on accuracy and clarity. Include:\n"
                           "1. A clear, direct answer to the query\n"
                           "2. Supporting evidence and facts from the sources\n"
                           "3. Any relevant context needed to understand the answer\n"
                           "4. Citations for all information (use numbered citations in square brackets [1], [2], etc.)\n"
                           "5. A references section at the end listing all sources",
                
                "comparative": "Create a standard comparative report that analyzes different perspectives on the query. Include:\n"
                              "1. An overview of the topic and why it's significant\n"
                              "2. A balanced presentation of different viewpoints or approaches\n"
                              "3. Analysis of similarities and differences\n"
                              "4. Evidence supporting each perspective\n"
                              "5. A synthesis of the information that highlights key insights\n"
                              "6. Citations for all information (use numbered citations in square brackets [1], [2], etc.)\n"
                              "7. A references section at the end listing all sources",
                
                "exploratory": "Create a standard exploratory report that investigates the query in depth. Include:\n"
                              "1. An introduction that frames the topic and its significance\n"
                              "2. Key concepts and definitions\n"
                              "3. Main findings and insights from the sources\n"
                              "4. Analysis of the information that highlights patterns and connections\n"
                              "5. Implications or applications of the findings\n"
                              "6. Citations for all information (use numbered citations in square brackets [1], [2], etc.)\n"
                              "7. A references section at the end listing all sources"
            },
            
            DetailLevel.DETAILED: {
                "factual": "Create a detailed factual report that thoroughly answers the query with deeper analysis. Focus on accuracy, clarity, and analytical depth. Include:\n"
                           "1. A comprehensive answer to the query with nuanced details and multi-layered analysis\n"
                           "2. Extensive supporting evidence including statistics, expert opinions, and case examples\n"
                           "3. Deeper exploration of causal relationships and underlying mechanisms\n"
                           "4. Analysis of how different factors interact and influence each other\n"
                           "5. Examination of historical context and how it shapes current understanding\n"
                           "6. Consideration of diverse perspectives and interpretations of the evidence\n"
                           "7. Citations for all information (use numbered citations in square brackets [1], [2], etc.)\n"
                           "8. A detailed references section at the end listing all sources\n\n"
                           "Prioritize depth of analysis over breadth of topics. Focus on providing rich, insightful explanations rather than just adding more sections.",
                
                "comparative": "Create a detailed comparative report with deeper analytical insights. Include:\n"
                              "1. A comprehensive overview of the topic with analysis of underlying principles\n"
                              "2. In-depth presentation of different viewpoints with exploration of their theoretical foundations\n"
                              "3. Detailed analysis of why differences exist and their historical development\n"
                              "4. Examination of how different perspectives might apply in various contexts or scenarios\n"
                              "5. Analysis of trade-offs, with quantitative measures where possible\n"
                              "6. Exploration of hybrid approaches or potential reconciliation of different viewpoints\n"
                              "7. Citations for all information (use numbered citations in square brackets [1], [2], etc.)\n"
                              "8. A detailed references section at the end listing all sources\n\n"
                              "Prioritize depth of analysis over breadth of topics. Focus on providing rich, insightful explanations rather than just adding more sections.",
                
                "exploratory": "Create a detailed exploratory report with deeper analytical insights. Include:\n"
                              "1. A comprehensive introduction with analysis of why this topic matters and to whom\n"
                              "2. Detailed explanation of key concepts with exploration of their evolution and interconnections\n"
                              "3. In-depth analysis of cause-and-effect relationships and systemic factors\n"
                              "4. Examination of apparent contradictions and how they might be resolved\n"
                              "5. Analysis of how different stakeholders might be affected differently\n"
                              "6. Exploration of second and third-order effects or implications\n"
                              "7. Citations for all information (use numbered citations in square brackets [1], [2], etc.)\n"
                              "8. A detailed references section at the end listing all sources\n\n"
                              "Prioritize depth of analysis over breadth of topics. Focus on providing rich, insightful explanations rather than just adding more sections."
            },
            
            DetailLevel.COMPREHENSIVE: {
                "factual": "Create an exhaustive factual report with the deepest possible analysis. Include:\n"
                           "1. A multi-dimensional answer that explores all facets of the query with layered analysis\n"
                           "2. Comprehensive evidence including statistical data, expert consensus, minority viewpoints, and case studies\n"
                           "3. Detailed exploration of complex causal networks and feedback loops\n"
                           "4. Analysis of how the topic intersects with related domains and disciplines\n"
                           "5. Examination of historical evolution, current state, and future trajectories\n"
                           "6. Critical evaluation of the quality and reliability of different evidence sources\n"
                           "7. Synthesis of insights across multiple analytical frameworks\n"
                           "8. Visual elements such as tables or bullet points to organize complex information\n"
                           "9. Citations for all information (use numbered citations in square brackets [1], [2], etc.)\n"
                           "10. A comprehensive references section at the end listing all sources\n\n"
                           "Maximize analytical depth while maintaining clarity. Provide the richest possible understanding rather than simply covering more ground.",
                
                "comparative": "Create an exhaustive comparative report with the deepest possible analysis. Include:\n"
                              "1. A multi-layered overview that places the comparison in broader theoretical and practical contexts\n"
                              "2. Comprehensive presentation of all viewpoints with analysis of their epistemological foundations\n"
                              "3. Detailed examination of how different perspectives have evolved in response to each other\n"
                              "4. Analysis of how cultural, historical, and disciplinary contexts shape different viewpoints\n"
                              "5. Quantitative and qualitative comparison using multiple frameworks and metrics\n"
                              "6. Exploration of edge cases where different perspectives might converge or diverge\n"
                              "7. Synthesis that identifies meta-patterns across different analytical dimensions\n"
                              "8. Visual elements such as tables or matrices to organize complex comparisons\n"
                              "9. Citations for all information (use numbered citations in square brackets [1], [2], etc.)\n"
                              "10. A comprehensive references section at the end listing all sources\n\n"
                              "Maximize analytical depth while maintaining clarity. Provide the richest possible understanding rather than simply covering more ground.",
                
                "exploratory": "Create an exhaustive exploratory report with the deepest possible analysis. Include:\n"
                              "1. A multi-dimensional introduction that situates the topic within broader intellectual landscapes\n"
                              "2. Comprehensive explanation of all concepts with analysis of their theoretical underpinnings\n"
                              "3. In-depth exploration of complex interaction effects and emergent properties\n"
                              "4. Detailed examination of how different methodological approaches yield different insights\n"
                              "5. Analysis of how the topic might be understood differently across disciplines or paradigms\n"
                              "6. Exploration of counterfactuals, thought experiments, and alternative scenarios\n"
                              "7. Synthesis that integrates insights across multiple levels of analysis\n"
                              "8. Visual elements such as tables or concept maps to organize complex information\n"
                              "9. Citations for all information (use numbered citations in square brackets [1], [2], etc.)\n"
                              "10. A comprehensive references section at the end listing all sources\n\n"
                              "Maximize analytical depth while maintaining clarity. Provide the richest possible understanding rather than simply covering more ground."
            }
        }
    
    def get_detail_level_config(self, detail_level: str) -> Dict[str, Any]:
        """
        Get configuration parameters for a specific detail level.
        
        Args:
            detail_level: Detail level as a string (brief, standard, detailed, comprehensive)
            
        Returns:
            Dictionary of configuration parameters for the specified detail level
            
        Raises:
            ValueError: If the detail level is not valid
        """
        try:
            level = DetailLevel(detail_level.lower())
            return self.detail_level_configs[level]
        except (ValueError, KeyError):
            valid_levels = [level.value for level in DetailLevel]
            raise ValueError(f"Invalid detail level: {detail_level}. Valid levels are: {', '.join(valid_levels)}")
    
    def get_template_modifier(self, detail_level: str, query_type: str) -> str:
        """
        Get template modifier for a specific detail level and query type.
        
        Args:
            detail_level: Detail level as a string (brief, standard, detailed, comprehensive)
            query_type: Query type as a string (factual, exploratory, comparative)
            
        Returns:
            Template modifier as a string
            
        Raises:
            ValueError: If the detail level or query type is not valid
        """
        try:
            level = DetailLevel(detail_level.lower())
            if query_type not in ["factual", "exploratory", "comparative"]:
                query_type = "exploratory"  # Default to exploratory if query type is not valid
            
            return self.template_modifiers[level][query_type]
        except (ValueError, KeyError):
            valid_levels = [level.value for level in DetailLevel]
            raise ValueError(f"Invalid detail level: {detail_level}. Valid levels are: {', '.join(valid_levels)}")
    
    def get_available_detail_levels(self) -> List[Tuple[str, str]]:
        """
        Get a list of available detail levels with descriptions.
        
        Returns:
            List of tuples containing detail level and description
        """
        return [(level.value, config["description"]) 
                for level, config in self.detail_level_configs.items()]


# Create a singleton instance for global use
report_detail_level_manager = ReportDetailLevelManager()


def get_report_detail_level_manager() -> ReportDetailLevelManager:
    """
    Get the global report detail level manager instance.
    
    Returns:
        ReportDetailLevelManager instance
    """
    return report_detail_level_manager
