"""
Advanced Toxo Prompt Engineering Engine.

This module creates rich, professional-grade system prompts that rival those used in
production AI systems like Cursor, v0, and Bolt. It generates structured, contextual,
and highly detailed prompts that significantly improve LLM performance.
"""

import json
import re
from datetime import datetime
from typing import Dict, Any, List, Optional, Union
from dataclasses import dataclass, field, asdict
from pathlib import Path
import yaml

from ..utils.logger import get_logger
from ..utils.exceptions import ValidationError


@dataclass
class PromptIdentity:
    """Rich identity composition for advanced AI personas."""
    core_role: str
    specialization: str
    expertise_level: str
    domain_authority: List[str]
    capabilities: List[str]
    performance_characteristics: Dict[str, str]
    persona_traits: List[str]
    communication_style: str
    
    def __post_init__(self):
        if not self.domain_authority:
            self.domain_authority = []
        if not self.capabilities:
            self.capabilities = []
        if not self.persona_traits:
            self.persona_traits = []
        if not self.performance_characteristics:
            self.performance_characteristics = {}


@dataclass
class PromptInstructions:
    """Comprehensive instruction framework for AI behavior."""
    primary_directive: str
    secondary_objectives: List[str]
    reasoning_methodology: str
    decision_framework: List[str]
    quality_standards: Dict[str, str]
    output_specifications: Dict[str, Any]
    interaction_patterns: List[str]
    error_handling: Dict[str, str]
    constraints: List[str]
    success_metrics: List[str]
    
    def __post_init__(self):
        if not self.secondary_objectives:
            self.secondary_objectives = []
        if not self.decision_framework:
            self.decision_framework = []
        if not self.quality_standards:
            self.quality_standards = {}
        if not self.output_specifications:
            self.output_specifications = {}
        if not self.interaction_patterns:
            self.interaction_patterns = []
        if not self.error_handling:
            self.error_handling = {}
        if not self.constraints:
            self.constraints = []
        if not self.success_metrics:
            self.success_metrics = []


@dataclass
class PromptContext:
    """Rich contextual information for intelligent prompting."""
    domain_knowledge: Dict[str, List[str]]
    environmental_constraints: Dict[str, Any]
    user_profile: Dict[str, Any]
    session_memory: Dict[str, Any]
    performance_history: Dict[str, float]
    retrieved_documents: List[Dict[str, Any]]
    conversation_context: List[Dict[str, str]]
    temporal_context: Dict[str, str]
    cultural_context: Dict[str, str]
    
    def __post_init__(self):
        if not self.domain_knowledge:
            self.domain_knowledge = {}
        if not self.environmental_constraints:
            self.environmental_constraints = {}
        if not self.user_profile:
            self.user_profile = {}
        if not self.session_memory:
            self.session_memory = {}
        if not self.performance_history:
            self.performance_history = {}
        if not self.retrieved_documents:
            self.retrieved_documents = []
        if not self.conversation_context:
            self.conversation_context = []
        if not self.temporal_context:
            self.temporal_context = {}
        if not self.cultural_context:
            self.cultural_context = {}


@dataclass
class PromptMetadata:
    """Metadata for prompt versioning and optimization."""
    version: str
    created_at: str
    domain: str
    task_type: str
    complexity_level: str
    optimization_target: str
    performance_benchmarks: Dict[str, float]
    revision_history: List[Dict[str, Any]]
    
    def __post_init__(self):
        if not self.performance_benchmarks:
            self.performance_benchmarks = {}
        if not self.revision_history:
            self.revision_history = []


@dataclass
class ToxoMasterPrompt:
    """Complete master prompt structure for Toxo."""
    identity: PromptIdentity
    instructions: PromptInstructions
    context: PromptContext
    metadata: PromptMetadata
    
    def to_dict(self) -> Dict[str, Any]:
        return asdict(self)


class AdvancedPromptTemplateEngine:
    """
    Advanced prompt engineering engine that creates rich, professional-grade system prompts.
    
    This engine produces prompts that rival those used in production AI systems like:
    - Cursor AI Assistant
    - v0 by Vercel
    - Bolt AI
    - Claude Sonnet 
    
    Features:
    - Multi-layered prompt architecture
    - Context-aware prompt adaptation
    - Performance-driven optimization
    - Rich formatting and structure
    - Domain-specific expertise injection
    """
    
    def __init__(self, config: Optional[Dict[str, Any]] = None):
        """Initialize the advanced prompt template engine."""
        self.config = config or {}
        self.logger = get_logger("toxo.prompt_engine")
        
        # Load advanced templates and knowledge bases
        self._load_advanced_templates()
        self._load_domain_expertise()
        self._load_performance_patterns()
        
        self.logger.info("Advanced Prompt Template Engine initialized")

    def create_master_prompt(
        self,
        task_description: str,
        domain: str = "general",
        user_preferences: Optional[Dict[str, Any]] = None,
        context: Optional[Dict[str, Any]] = None,
        performance_metrics: Optional[Dict[str, float]] = None,
        complexity_level: str = "intermediate",
        optimization_target: str = "accuracy"
    ) -> ToxoMasterPrompt:
        """
        Create a rich, professional-grade master prompt.
        
        Args:
            task_description: Detailed description of the AI task
            domain: Domain specialization (finance, legal, medical, etc.)
            user_preferences: User-specific preferences and requirements
            context: Additional contextual information
            performance_metrics: Historical performance data
            complexity_level: simple, intermediate, advanced, expert
            optimization_target: accuracy, speed, creativity, safety
            
        Returns:
            Complete ToxoMasterPrompt with rich structure
        """
        user_preferences = user_preferences or {}
        context = context or {}
        performance_metrics = performance_metrics or {}
        
        # Create rich identity
        identity = self._create_advanced_identity(
            task_description, domain, complexity_level, performance_metrics
        )
        
        # Create comprehensive instructions
        instructions = self._create_comprehensive_instructions(
            task_description, domain, user_preferences, optimization_target
        )
        
        # Create rich context
        rich_context = self._create_rich_context(
            context, domain, user_preferences, performance_metrics
        )
        
        # Create metadata
        metadata = PromptMetadata(
            version="1.0.0",
            created_at=self._get_timestamp(),
            domain=domain,
            task_type=self._infer_task_type(task_description),
            complexity_level=complexity_level,
            optimization_target=optimization_target,
            performance_benchmarks=performance_metrics,
            revision_history=[]
        )
        
        master_prompt = ToxoMasterPrompt(
            identity=identity,
            instructions=instructions,
            context=rich_context,
            metadata=metadata
        )
        
        self.logger.info(f"Created master prompt for domain: {domain}, complexity: {complexity_level}")
        return master_prompt
    def render_rich_prompt(
        self,
        master_prompt: ToxoMasterPrompt,
        user_input: str,
        template_format: str = "professional"
    ) -> str:
        """
        Render a rich, structured system prompt.
        
        Args:
            master_prompt: Master prompt structure
            user_input: Current user input
            template_format: professional, technical, creative, conversational
            
        Returns:
            Fully rendered rich system prompt
        """
        # Select appropriate template
        template = self._get_rich_template(template_format, master_prompt.metadata.task_type)
        
        # Prepare comprehensive variables
        variables = self._prepare_rich_variables(master_prompt, user_input)
        
        # Render with advanced formatting
        rendered_prompt = self._render_rich_template(template, variables)
        
        # Apply post-processing optimizations
        optimized_prompt = self._optimize_prompt_structure(rendered_prompt, master_prompt)
        
        self.logger.debug(f"Rendered rich prompt with {len(optimized_prompt)} characters")
        return optimized_prompt
    
    def adapt_prompt_from_feedback(
        self,
        master_prompt: ToxoMasterPrompt,
        feedback: Dict[str, Any],
        performance_metrics: Dict[str, float]
    ) -> ToxoMasterPrompt:
        """
        Adapt and evolve the prompt based on feedback and performance.
        
        Args:
            master_prompt: Current master prompt
            feedback: User and system feedback
            performance_metrics: Current performance data
            
        Returns:
            Enhanced master prompt
        """
        # Clone the current prompt
        enhanced_prompt = self._clone_master_prompt(master_prompt)
        
        # Analyze feedback patterns
        feedback_analysis = self._analyze_feedback_patterns(feedback, performance_metrics)
        
        # Update identity based on performance
        if feedback_analysis.get("enhance_expertise"):
            enhanced_prompt.identity = self._enhance_identity_expertise(
                enhanced_prompt.identity, feedback_analysis
            )
        
        # Refine instructions based on specific feedback
        if feedback_analysis.get("instruction_refinements"):
            enhanced_prompt.instructions = self._refine_instructions(
                enhanced_prompt.instructions, feedback_analysis
            )
        
        # Update context with new learnings
        enhanced_prompt.context.performance_history.update(performance_metrics)
        
        # Update metadata
        enhanced_prompt.metadata.revision_history.append({
            "timestamp": self._get_timestamp(),
            "feedback_summary": feedback_analysis.get("summary", ""),
            "performance_change": self._calculate_performance_delta(
                master_prompt.context.performance_history, performance_metrics
            ),
            "adaptations_made": feedback_analysis.get("adaptations", [])
        })
        
        # Increment version
        enhanced_prompt.metadata.version = self._increment_version(master_prompt.metadata.version)
        
        self.logger.info(f"Adapted prompt based on feedback, new version: {enhanced_prompt.metadata.version}")
        return enhanced_prompt
    
    def _create_advanced_identity(
        self,
        task_description: str,
        domain: str,
        complexity_level: str,
        performance_metrics: Dict[str, float]
    ) -> PromptIdentity:
        """Create a rich, sophisticated AI identity."""
        # Determine core role with sophistication
        core_role = self._determine_sophisticated_role(task_description, domain)
        
        # Create specialized expertise areas
        specialization = self._create_domain_specialization(domain, complexity_level)
        
        # Determine expertise level
        expertise_level = self._assess_expertise_level(complexity_level, performance_metrics)
        
        # Build domain authority
        domain_authority = self._build_domain_authority(domain, task_description)
        
        # Define comprehensive capabilities
        capabilities = self._define_advanced_capabilities(task_description, domain, complexity_level)
        
        # Create performance characteristics
        performance_characteristics = self._define_performance_characteristics(
            complexity_level, performance_metrics
        )
        
        # Define persona traits
        persona_traits = self._select_optimal_persona_traits(domain, task_description)
        
        # Determine communication style
        communication_style = self._select_communication_style(domain, complexity_level)
        
        return PromptIdentity(
            core_role=core_role,
            specialization=specialization,
            expertise_level=expertise_level,
            domain_authority=domain_authority,
            capabilities=capabilities,
            performance_characteristics=performance_characteristics,
            persona_traits=persona_traits,
            communication_style=communication_style
        )
    
    def _create_comprehensive_instructions(
        self,
        task_description: str,
        domain: str,
        user_preferences: Dict[str, Any],
        optimization_target: str
    ) -> PromptInstructions:
        """Create comprehensive, detailed instructions."""
        # Primary directive with clarity and purpose
        primary_directive = self._craft_primary_directive(task_description, domain)
        
        # Secondary objectives
        secondary_objectives = self._define_secondary_objectives(task_description, domain)
        
        # Reasoning methodology
        reasoning_methodology = self._select_reasoning_methodology(domain, optimization_target)
        
        # Decision framework
        decision_framework = self._build_decision_framework(domain, user_preferences)
        
        # Quality standards
        quality_standards = self._define_quality_standards(domain, optimization_target)
        
        # Output specifications
        output_specifications = self._create_output_specifications(
            task_description, user_preferences
        )
        
        # Interaction patterns
        interaction_patterns = self._define_interaction_patterns(domain, user_preferences)
        
        # Error handling
        error_handling = self._create_error_handling_framework(domain)
        
        # Constraints
        constraints = self._extract_domain_constraints(domain, task_description)
        
        # Success metrics
        success_metrics = self._define_success_metrics(domain, optimization_target)
        
        return PromptInstructions(
            primary_directive=primary_directive,
            secondary_objectives=secondary_objectives,
            reasoning_methodology=reasoning_methodology,
            decision_framework=decision_framework,
            quality_standards=quality_standards,
            output_specifications=output_specifications,
            interaction_patterns=interaction_patterns,
            error_handling=error_handling,
            constraints=constraints,
            success_metrics=success_metrics
        )
    
    def _create_rich_context(
        self,
        context: Dict[str, Any],
        domain: str,
        user_preferences: Dict[str, Any],
        performance_metrics: Dict[str, float]
    ) -> PromptContext:
        """Create rich, comprehensive context."""
        # Domain knowledge base
        domain_knowledge = self._build_domain_knowledge_base(domain)
        
        # Environmental constraints
        environmental_constraints = self._assess_environmental_constraints(context)
        
        # User profile
        user_profile = self._build_user_profile(user_preferences, context)
        
        # Session memory
        session_memory = context.get("session_memory", {})
        
        # Performance history
        performance_history = performance_metrics
        
        # Retrieved documents
        retrieved_documents = context.get("retrieved_documents", [])
        
        # Conversation context
        conversation_context = context.get("conversation_history", [])
        
        # Temporal context
        temporal_context = self._create_temporal_context()
        
        # Cultural context
        cultural_context = self._infer_cultural_context(user_preferences)
        
        return PromptContext(
            domain_knowledge=domain_knowledge,
            environmental_constraints=environmental_constraints,
            user_profile=user_profile,
            session_memory=session_memory,
            performance_history=performance_history,
            retrieved_documents=retrieved_documents,
            conversation_context=conversation_context,
            temporal_context=temporal_context,
            cultural_context=cultural_context
        )
    
    def _get_rich_template(self, format_type: str, task_type: str) -> str:
        """Get rich template based on format and task type."""
        templates = {
            "professional": self._get_professional_template(task_type),
            "technical": self._get_technical_template(task_type),
            "creative": self._get_creative_template(task_type),
            "conversational": self._get_conversational_template(task_type)
        }
        
        return templates.get(format_type, templates["professional"])
    
    def _get_professional_template(self, task_type: str) -> str:
        """Get professional template with rich structure."""
        return """## Core Identity
You are {core_role}, {specialization} with {expertise_level} expertise.

{domain_authority_section}

## Primary Directive
{primary_directive}

<core_capabilities>
{capabilities_section}
</core_capabilities>

<operational_guidelines>
## Reasoning Methodology
{reasoning_methodology}

## Decision Framework
{decision_framework_section}

## Quality Standards
{quality_standards_section}

## Output Specifications
{output_specifications_section}
</operational_guidelines>

<interaction_protocol>
## Communication Style
{communication_style}

## Interaction Patterns
{interaction_patterns_section}

## Error Handling
{error_handling_section}
</interaction_protocol>

<context_awareness>
## Domain Knowledge
{domain_knowledge_section}

## Environmental Constraints
{environmental_constraints_section}

## User Profile
{user_profile_section}

## Performance History
{performance_history_section}
</context_awareness>

<constraints_and_guidelines>
{constraints_section}
</constraints_and_guidelines>

<success_metrics>
{success_metrics_section}
</success_metrics>

## Current Task Context
User Input: {user_input}

## Instructions
{task_specific_instructions}

{additional_context}"""
    
    def _prepare_rich_variables(
        self, 
        master_prompt: ToxoMasterPrompt, 
        user_input: str
    ) -> Dict[str, str]:
        """Prepare comprehensive variables for template rendering."""
        variables = {}
        
        # Identity variables
        variables.update({
            "core_role": master_prompt.identity.core_role,
            "specialization": master_prompt.identity.specialization,
            "expertise_level": master_prompt.identity.expertise_level,
            "communication_style": master_prompt.identity.communication_style,
        })
        
        # Formatted sections
        variables.update({
            "domain_authority_section": self._format_domain_authority(
                master_prompt.identity.domain_authority
            ),
            "capabilities_section": self._format_capabilities(
                master_prompt.identity.capabilities
            ),
            "primary_directive": master_prompt.instructions.primary_directive,
            "reasoning_methodology": master_prompt.instructions.reasoning_methodology,
            "decision_framework_section": self._format_decision_framework(
                master_prompt.instructions.decision_framework
            ),
            "quality_standards_section": self._format_quality_standards(
                master_prompt.instructions.quality_standards
            ),
            "output_specifications_section": self._format_output_specifications(
                master_prompt.instructions.output_specifications
            ),
            "interaction_patterns_section": self._format_interaction_patterns(
                master_prompt.instructions.interaction_patterns
            ),
            "error_handling_section": self._format_error_handling(
                master_prompt.instructions.error_handling
            ),
            "domain_knowledge_section": self._format_domain_knowledge(
                master_prompt.context.domain_knowledge
            ),
            "environmental_constraints_section": self._format_environmental_constraints(
                master_prompt.context.environmental_constraints
            ),
            "user_profile_section": self._format_user_profile(
                master_prompt.context.user_profile
            ),
            "performance_history_section": self._format_performance_history(
                master_prompt.context.performance_history
            ),
            "constraints_section": self._format_constraints(
                master_prompt.instructions.constraints
            ),
            "success_metrics_section": self._format_success_metrics(
                master_prompt.instructions.success_metrics
            ),
            "user_input": user_input,
            "task_specific_instructions": self._generate_task_specific_instructions(
                master_prompt, user_input
            ),
            "additional_context": self._generate_additional_context(master_prompt)
        })
        
        return variables
    
    def _render_rich_template(self, template: str, variables: Dict[str, str]) -> str:
        """Render template with rich variable substitution."""
        rendered = template
        
        for key, value in variables.items():
            placeholder = "{" + key + "}"
            rendered = rendered.replace(placeholder, str(value))
        
        return rendered
    
    def _optimize_prompt_structure(
        self, 
        prompt: str, 
        master_prompt: ToxoMasterPrompt
    ) -> str:
        """Apply advanced optimizations to prompt structure."""
        # Remove excessive whitespace while preserving structure
        optimized = re.sub(r'\n\s*\n\s*\n', '\n\n', prompt)
        
        # Ensure proper section spacing
        optimized = re.sub(r'(##[^#\n]*)\n([^#\n\s])', r'\1\n\n\2', optimized)
        
        # Optimize for readability
        optimized = self._optimize_readability(optimized)
        
        # Apply performance-specific optimizations
        if master_prompt.metadata.optimization_target == "speed":
            optimized = self._optimize_for_speed(optimized)
        elif master_prompt.metadata.optimization_target == "accuracy":
            optimized = self._optimize_for_accuracy(optimized)
        
        return optimized.strip()
    
    def _load_advanced_templates(self):
        """Load advanced template structures."""
        self.templates = {
            "professional": {
                "structure": ["identity", "directive", "capabilities", "guidelines", "context"],
                "formatting": "structured"
            },
            "technical": {
                "structure": ["specifications", "constraints", "protocols", "implementation"],
                "formatting": "detailed"
            },
            "creative": {
                "structure": ["inspiration", "guidelines", "expression", "refinement"],
                "formatting": "fluid"
            }
        }
    
    def _load_domain_expertise(self):
        """Load domain-specific expertise patterns."""
        self.domain_expertise = {
            "finance": {
                "authorities": ["financial analysis", "risk assessment", "regulatory compliance"],
                "capabilities": ["portfolio optimization", "market analysis", "financial modeling"],
                "constraints": ["regulatory compliance", "risk management", "ethical investing"]
            },
            "legal": {
                "authorities": ["legal research", "case analysis", "regulatory interpretation"],
                "capabilities": ["document review", "legal reasoning", "precedent analysis"],
                "constraints": ["confidentiality", "jurisdictional limits", "ethical guidelines"]
            },
            "medical": {
                "authorities": ["clinical knowledge", "evidence-based medicine", "patient safety"],
                "capabilities": ["symptom analysis", "treatment recommendations", "drug interactions"],
                "constraints": ["patient privacy", "medical ethics", "regulatory compliance"]
            },
            "education": {
                "authorities": ["pedagogical methods", "curriculum design", "learning assessment"],
                "capabilities": ["personalized instruction", "knowledge assessment", "skill development"],
                "constraints": ["age-appropriate content", "learning accessibility", "educational standards"]
            }
        }
    
    def _load_performance_patterns(self):
        """Load performance optimization patterns."""
        self.performance_patterns = {
            "accuracy": {
                "reasoning": "systematic and thorough",
                "verification": "multi-step validation",
                "output": "detailed and precise"
            },
            "speed": {
                "reasoning": "efficient and direct",
                "verification": "quick validation",
                "output": "concise and actionable"
            },
            "creativity": {
                "reasoning": "divergent and innovative",
                "verification": "originality check",
                "output": "novel and inspiring"
            }
        }
    
    def _format_domain_authority(self, authorities: List[str]) -> str:
        """Format domain authority section."""
        if not authorities:
            return "General expertise across multiple domains."
        
        formatted = "## Domain Authority\n"
        for authority in authorities:
            formatted += f"- **{authority.title()}**: Deep expertise and proven track record\n"
        
        return formatted
    
    def _format_capabilities(self, capabilities: List[str]) -> str:
        """Format capabilities section."""
        if not capabilities:
            return "Core AI reasoning and response generation capabilities."
        
        formatted = ""
        for i, capability in enumerate(capabilities, 1):
            formatted += f"{i}. **{capability.title()}**: Advanced proficiency\n"
        
        return formatted
    
    def _format_decision_framework(self, framework: List[str]) -> str:
        """Format decision framework section."""
        if not framework:
            return "Apply logical reasoning and evidence-based decision making."
        
        formatted = ""
        for i, step in enumerate(framework, 1):
            formatted += f"{i}. {step}\n"
        
        return formatted
    
    def _format_quality_standards(self, standards: Dict[str, str]) -> str:
        """Format quality standards section."""
        if not standards:
            return "Maintain high standards of accuracy, relevance, and helpfulness."
        
        formatted = ""
        for standard, description in standards.items():
            formatted += f"- **{standard.title()}**: {description}\n"
        
        return formatted
    
    def _format_output_specifications(self, specs: Dict[str, Any]) -> str:
        """Format output specifications section."""
        if not specs:
            return "Provide clear, well-structured, and actionable responses."
        
        formatted = ""
        for spec, value in specs.items():
            formatted += f"- **{spec.title()}**: {value}\n"
        
        return formatted
    
    def _format_interaction_patterns(self, patterns: List[str]) -> str:
        """Format interaction patterns section."""
        if not patterns:
            return "Engage professionally and helpfully with users."
        
        formatted = ""
        for pattern in patterns:
            formatted += f"- {pattern}\n"
        
        return formatted
    
    def _format_error_handling(self, error_handling: Dict[str, str]) -> str:
        """Format error handling section."""
        if not error_handling:
            return "Handle errors gracefully and provide helpful guidance."
        
        formatted = ""
        for error_type, handling in error_handling.items():
            formatted += f"- **{error_type}**: {handling}\n"
        
        return formatted
    
    def _format_domain_knowledge(self, knowledge: Dict[str, List[str]]) -> str:
        """Format domain knowledge section."""
        if not knowledge:
            return "Access to general knowledge base."
        
        formatted = ""
        for domain, items in knowledge.items():
            formatted += f"### {domain.title()}\n"
            for item in items[:3]:  # Limit to top 3 for brevity
                formatted += f"- {item}\n"
            formatted += "\n"
        
        return formatted
    
    def _format_environmental_constraints(self, constraints: Dict[str, Any]) -> str:
        """Format environmental constraints section."""
        if not constraints:
            return "Operating in standard environment with full capabilities."
        
        formatted = ""
        for constraint, value in constraints.items():
            formatted += f"- **{constraint.title()}**: {value}\n"
        
        return formatted
    
    def _format_user_profile(self, profile: Dict[str, Any]) -> str:
        """Format user profile section."""
        if not profile:
            return "General user with standard preferences."
        
        formatted = ""
        for key, value in profile.items():
            formatted += f"- **{key.title()}**: {value}\n"
        
        return formatted
    
    def _format_performance_history(self, history: Dict[str, float]) -> str:
        """Format performance history section."""
        if not history:
            return "No previous performance metrics available."
        
        formatted = ""
        for metric, value in history.items():
            formatted += f"- **{metric.title()}**: {value:.2f}\n"
        
        return formatted
    
    def _format_constraints(self, constraints: List[str]) -> str:
        """Format constraints section."""
        if not constraints:
            return "Standard operational constraints apply."
        
        formatted = ""
        for constraint in constraints:
            formatted += f"- {constraint}\n"
        
        return formatted
    
    def _format_success_metrics(self, metrics: List[str]) -> str:
        """Format success metrics section."""
        if not metrics:
            return "Success measured by user satisfaction and task completion."
        
        formatted = ""
        for metric in metrics:
            formatted += f"- {metric}\n"
        
        return formatted
    
    def _determine_sophisticated_role(self, task_description: str, domain: str) -> str:
        """Determine sophisticated AI role based on task and domain."""
        role_patterns = {
            "finance": "Expert Financial AI Advisor and Quantitative Analyst",
            "legal": "Advanced Legal AI Research Assistant and Case Analyst", 
            "medical": "Specialized Medical AI Assistant and Clinical Decision Support",
            "education": "Advanced Educational AI Tutor and Learning Specialist",
            "technical": "Senior AI Software Engineering Assistant and Architecture Advisor",
            "creative": "Creative AI Collaborator and Innovation Catalyst",
            "business": "Strategic Business AI Consultant and Market Analyst"
        }
        
        return role_patterns.get(domain, "Advanced AI Assistant and Domain Expert")
    
    def _create_domain_specialization(self, domain: str, complexity_level: str) -> str:
        """Create domain specialization description."""
        base_specializations = {
            "finance": "Financial Analysis and Investment Strategy",
            "legal": "Legal Research and Regulatory Compliance",
            "medical": "Clinical Decision Support and Medical Research",
            "education": "Personalized Learning and Curriculum Development",
            "technical": "Software Architecture and Engineering Best Practices",
            "creative": "Creative Development and Innovation Strategy",
            "business": "Strategic Planning and Business Intelligence"
        }
        
        complexity_modifiers = {
            "simple": "with focus on clarity and accessibility",
            "intermediate": "with balanced depth and practical application",
            "advanced": "with comprehensive expertise and nuanced understanding",
            "expert": "with cutting-edge knowledge and strategic insight"
        }
        
        base = base_specializations.get(domain, "General AI Assistance")
        modifier = complexity_modifiers.get(complexity_level, "with professional competency")
        
        return f"{base} {modifier}"
    
    def _assess_expertise_level(self, complexity_level: str, performance_metrics: Dict[str, float]) -> str:
        """Assess appropriate expertise level."""
        base_levels = {
            "simple": "Competent Professional",
            "intermediate": "Senior Specialist", 
            "advanced": "Subject Matter Expert",
            "expert": "Industry Authority"
        }
        
        # Adjust based on performance
        avg_performance = sum(performance_metrics.values()) / len(performance_metrics) if performance_metrics else 0.5
        
        if avg_performance > 0.9:
            return f"Elite {base_levels.get(complexity_level, 'Professional')}"
        elif avg_performance > 0.8:
            return f"Distinguished {base_levels.get(complexity_level, 'Professional')}"
        else:
            return base_levels.get(complexity_level, "Competent Professional")
    
    def _build_domain_authority(self, domain: str, task_description: str) -> List[str]:
        """Build domain authority areas."""
        domain_data = self.domain_expertise.get(domain, {})
        return domain_data.get("authorities", ["general expertise", "analytical thinking", "problem solving"])
    
    def _define_advanced_capabilities(self, task_description: str, domain: str, complexity_level: str) -> List[str]:
        """Define advanced capabilities based on domain and task."""
        domain_data = self.domain_expertise.get(domain, {})
        base_capabilities = domain_data.get("capabilities", [
            "analytical reasoning", "information synthesis", "solution generation"
        ])
        
        # Add complexity-specific capabilities
        complexity_capabilities = {
            "simple": ["clear communication", "step-by-step guidance"],
            "intermediate": ["critical analysis", "practical recommendations"],
            "advanced": ["strategic thinking", "complex problem solving"],
            "expert": ["innovation leadership", "paradigm development"]
        }
        
        all_capabilities = base_capabilities + complexity_capabilities.get(complexity_level, [])
        return all_capabilities[:6]  # Limit to 6 for clarity
    
    def _define_performance_characteristics(self, complexity_level: str, performance_metrics: Dict[str, float]) -> Dict[str, str]:
        """Define performance characteristics."""
        base_characteristics = {
            "response_quality": "high precision and relevance",
            "reasoning_depth": "thorough and systematic",
            "adaptability": "context-aware and flexible",
            "reliability": "consistent and dependable"
        }
        
        # Adjust based on complexity and performance
        if complexity_level in ["advanced", "expert"]:
            base_characteristics["innovation"] = "creative and forward-thinking"
            base_characteristics["expertise_depth"] = "comprehensive and nuanced"
        
        return base_characteristics
    
    def _select_optimal_persona_traits(self, domain: str, task_description: str) -> List[str]:
        """Select optimal persona traits for the domain."""
        domain_traits = {
            "finance": ["analytical", "detail-oriented", "risk-aware", "ethical"],
            "legal": ["precise", "thorough", "ethical", "objective"],
            "medical": ["careful", "evidence-based", "compassionate", "ethical"],
            "education": ["patient", "encouraging", "adaptive", "supportive"],
            "technical": ["logical", "systematic", "innovative", "precise"],
            "creative": ["imaginative", "open-minded", "inspiring", "original"],
            "business": ["strategic", "results-oriented", "practical", "insightful"]
        }
        
        return domain_traits.get(domain, ["helpful", "professional", "reliable", "knowledgeable"])
    
    def _select_communication_style(self, domain: str, complexity_level: str) -> str:
        """Select appropriate communication style."""
        styles = {
            "finance": "Professional and analytical with clear risk assessments",
            "legal": "Precise and formal with careful qualification of statements",
            "medical": "Careful and evidence-based with appropriate disclaimers",
            "education": "Clear and encouraging with progressive complexity",
            "technical": "Systematic and detailed with practical examples",
            "creative": "Inspiring and open-ended with innovative perspectives",
            "business": "Strategic and results-focused with actionable insights"
        }
        
        base_style = styles.get(domain, "Professional and helpful")
        
        if complexity_level == "expert":
            return f"{base_style}, with sophisticated depth and industry insight"
        elif complexity_level == "simple":
            return f"{base_style}, with accessible explanations and clear guidance"
        else:
            return base_style
    
    def _craft_primary_directive(self, task_description: str, domain: str) -> str:
        """Craft the primary directive."""
        return f"Provide expert assistance in {domain} with focus on {task_description}. Deliver accurate, actionable, and contextually appropriate responses that exceed user expectations while maintaining the highest professional standards."
    
    def _infer_task_type(self, description: str) -> str:
        """Infer task type from description."""
        description_lower = description.lower()
        
        if any(word in description_lower for word in ["classify", "categorize", "identify", "recognize"]):
            return "classification"
        elif any(word in description_lower for word in ["generate", "create", "write", "compose"]):
            return "generation"
        elif any(word in description_lower for word in ["analyze", "examine", "evaluate", "assess"]):
            return "analysis"
        elif any(word in description_lower for word in ["question", "answer", "explain", "help"]):
            return "qa"
        elif any(word in description_lower for word in ["summarize", "summary", "brief"]):
            return "summarization"
        elif any(word in description_lower for word in ["recommend", "suggest", "advise"]):
            return "recommendation"
        elif any(word in description_lower for word in ["plan", "strategy", "approach"]):
            return "planning"
        else:
            return "general"
    
    def _get_timestamp(self) -> str:
        """Get current timestamp."""
        return datetime.now().isoformat()
    
    def _clone_master_prompt(self, master_prompt: ToxoMasterPrompt) -> ToxoMasterPrompt:
        """Create a deep copy of master prompt."""
        return ToxoMasterPrompt(
            identity=PromptIdentity(**asdict(master_prompt.identity)),
            instructions=PromptInstructions(**asdict(master_prompt.instructions)),
            context=PromptContext(**asdict(master_prompt.context)),
            metadata=PromptMetadata(**asdict(master_prompt.metadata))
        )
    
    def _generate_task_specific_instructions(self, master_prompt: ToxoMasterPrompt, user_input: str) -> str:
        """Generate task-specific instructions."""
        return f"Apply your expertise to address the user's specific request with attention to detail, accuracy, and practical value. Consider the context and provide comprehensive assistance."
    
    def _generate_additional_context(self, master_prompt: ToxoMasterPrompt) -> str:
        """Generate additional context."""
        if master_prompt.context.retrieved_documents:
            return f"\n\n## Retrieved Knowledge\nRelevant information has been retrieved to enhance response accuracy."
        return ""
    
    def _optimize_readability(self, prompt: str) -> str:
        """Optimize prompt for readability."""
        # Ensure proper spacing after headers
        prompt = re.sub(r'(^#{1,6}[^#\n]*)\n([^#\n\s])', r'\1\n\n\2', prompt, flags=re.MULTILINE)
        
        # Ensure proper list formatting
        prompt = re.sub(r'\n-([^\n])', r'\n- \1', prompt)
        prompt = re.sub(r'\n(\d+\.)([^\n])', r'\n\1 \2', prompt)
        
        return prompt
    
    def _optimize_for_speed(self, prompt: str) -> str:
        """Optimize prompt for speed."""
        # Reduce verbosity while maintaining clarity
        prompt = re.sub(r'\n\n+', '\n\n', prompt)
        return prompt
    
    def _optimize_for_accuracy(self, prompt: str) -> str:
        """Optimize prompt for accuracy."""
        # Ensure all important sections are present
        if "## Quality Standards" not in prompt:
            prompt += "\n\n## Quality Standards\nMaintain highest accuracy and verify all information."
        return prompt
    
    # Additional helper methods would continue here...
    # This represents the core structure of the enhanced prompt engine


# Create alias for backward compatibility
PromptTemplateEngine = AdvancedPromptTemplateEngine 