"""
Core persona loading functionality
"""

import json
import os
from pathlib import Path
from typing import Dict, List, Optional


class PersonaLoader:
    """Main class for loading and managing personas"""
    
    def __init__(self, custom_persona_dir: Optional[str] = None):
        """
        Initialize the PersonaLoader
        
        Args:
            custom_persona_dir: Optional custom directory for personas.
                              If None, uses the built-in personas.
        """
        if custom_persona_dir:
            self.personas_dir = Path(custom_persona_dir)
        else:
            # Use the built-in personas directory
            self.personas_dir = Path(__file__).parent / "personas"
        
        if not self.personas_dir.exists():
            raise FileNotFoundError(f"Personas directory not found: {self.personas_dir}")
    
    def load(self, persona_name: str) -> Dict:
        """
        Load a persona by name
        
        Args:
            persona_name: Name of the persona (without .json extension)
            
        Returns:
            Dictionary containing persona data
            
        Raises:
            FileNotFoundError: If persona file doesn't exist
            json.JSONDecodeError: If JSON is invalid
        """
        persona_file = self.personas_dir / f"{persona_name}.json"
        
        if not persona_file.exists():
            raise FileNotFoundError(
                f"Persona '{persona_name}' not found. "
                f"Available personas: {', '.join(self.get_available())}"
            )
        
        with open(persona_file, 'r', encoding='utf-8') as f:
            persona_data = json.load(f)
        
        return persona_data
    
    def get_available(self) -> List[str]:
        """
        Get list of available persona names
        
        Returns:
            List of persona names (without .json extension)
        """
        persona_files = self.personas_dir.glob("*.json")
        return sorted([p.stem for p in persona_files])
    
    def get_all(self) -> Dict[str, Dict]:
        """
        Load all available personas
        
        Returns:
            Dictionary mapping persona names to their data
        """
        personas = {}
        for persona_name in self.get_available():
            try:
                personas[persona_name] = self.load(persona_name)
            except Exception as e:
                print(f"Warning: Failed to load {persona_name}: {e}")
        return personas
    
    def get_persona_info(self, persona_name: str) -> Dict[str, str]:
        """
        Get basic info about a persona without loading full data
        
        Args:
            persona_name: Name of the persona
            
        Returns:
            Dictionary with name, description, emoji, tone
        """
        persona = self.load(persona_name)
        return {
            "name": persona.get("persona_name", persona_name),
            "description": persona.get("description", ""),
            "emoji": persona.get("emoji", "🤖"),
            "tone": persona.get("tone", ""),
            "greeting": persona.get("greeting", "")
        }


# Convenience functions for simple use cases
_default_loader = None

def get_loader() -> PersonaLoader:
    """Get or create the default PersonaLoader instance"""
    global _default_loader
    if _default_loader is None:
        _default_loader = PersonaLoader()
    return _default_loader


def load_persona(persona_name: str) -> Dict:
    """
    Load a persona using the default loader
    
    Args:
        persona_name: Name of the persona
        
    Returns:
        Dictionary containing persona data
    """
    return get_loader().load(persona_name)


def get_available_personas() -> List[str]:
    """
    Get list of available personas
    
    Returns:
        List of persona names
    """
    return get_loader().get_available()


def get_persona_info(persona_name: str) -> Dict[str, str]:
    """
    Get basic info about a persona
    
    Args:
        persona_name: Name of the persona
        
    Returns:
        Dictionary with basic persona information
    """
    return get_loader().get_persona_info(persona_name)
