"""
Episodic Memory System for Toxo.

Implements episodic memory for storing and retrieving experiences and events.
"""

from typing import Dict, Any, List, Optional
from dataclasses import dataclass
from datetime import datetime

from ..utils.logger import get_logger


@dataclass 
class EpisodicMemory:
    """An episodic memory item representing an experience."""
    id: str
    episode: str
    experience: Dict[str, Any]
    timestamp: datetime
    duration: float = 0.0
    
    def __post_init__(self):
        if isinstance(self.timestamp, str):
            self.timestamp = datetime.fromisoformat(self.timestamp)


class EpisodicMemorySystem:
    """Episodic memory system for experience storage."""
    
    def __init__(self):
        self.logger = get_logger("toxo.memory.episodic")
        self.episodes: Dict[str, EpisodicMemory] = {}
        self.timeline: List[str] = []
        self.logger.info("Episodic memory system initialized")
    
    async def store(self, data: Dict[str, Any]) -> str:
        """Store episodic memory."""
        episode = data.get("episode", "unnamed_episode")
        experience = data.get("experience", {})
        episode_id = f"episode_{len(self.episodes)}_{datetime.now().timestamp()}"
        
        memory = EpisodicMemory(
            id=episode_id,
            episode=episode,
            experience=experience,
            timestamp=datetime.now(),
            duration=data.get("duration", 0.0)
        )
        
        self.episodes[episode_id] = memory
        self.timeline.append(episode_id)
        
        self.logger.debug(f"Stored episodic memory: {episode_id}")
        return episode_id
    
    async def retrieve(self, query: str) -> List[Dict[str, Any]]:
        """Retrieve episodic memories."""
        results = []
        for memory in self.episodes.values():
            if query.lower() in memory.episode.lower():
                results.append({
                    "id": memory.id,
                    "episode": memory.episode,
                    "experience": memory.experience,
                    "timestamp": memory.timestamp.isoformat(),
                    "duration": memory.duration
                })
        return results
    
    async def search(self, query: str) -> List[Dict[str, Any]]:
        """Search episodic memories."""
        return await self.retrieve(query)
    
    async def analyze(self) -> Dict[str, Any]:
        """Analyze episodic memory."""
        return {
            "total_episodes": len(self.episodes),
            "timeline_length": len(self.timeline),
            "recent_episodes": [self.episodes[eid].episode for eid in self.timeline[-5:]]
        }
    
    async def optimize(self) -> Dict[str, Any]:
        """Optimize episodic memory."""
        self.logger.info("Optimizing episodic memory")
        return {"status": "optimized", "episodes_count": len(self.episodes)}
    
    async def consolidate(self) -> Dict[str, Any]:
        """Consolidate episodic memory."""
        self.logger.info("Consolidating episodic memory")
        return {"status": "consolidated", "episodes_count": len(self.episodes)}
    
    def get_stats(self) -> Dict[str, Any]:
        """Get memory statistics."""
        return {
            "type": "episodic",
            "episodes": len(self.episodes),
            "timeline_length": len(self.timeline)
        }