"""
Procedural Memory System for Toxo.

Implements procedural memory for storing and managing skills and procedures.
"""

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

from ..utils.logger import get_logger


@dataclass
class ProceduralSkill:
    """A procedural skill or procedure."""
    id: str
    name: str
    steps: List[str]
    proficiency: float = 0.5
    usage_count: int = 0
    last_used: Optional[datetime] = None
    
    def __post_init__(self):
        if isinstance(self.last_used, str):
            self.last_used = datetime.fromisoformat(self.last_used)


class ProceduralMemorySystem:
    """Procedural memory system for skill management."""
    
    def __init__(self):
        self.logger = get_logger("toxo.memory.procedural")
        self.skills: Dict[str, ProceduralSkill] = {}
        self.skill_categories: Dict[str, List[str]] = {}
        self.logger.info("Procedural memory system initialized")
    
    async def store(self, data: Dict[str, Any]) -> str:
        """Store procedural skill."""
        name = data.get("name", "unnamed_skill")
        steps = data.get("steps", [])
        skill_id = f"skill_{len(self.skills)}_{datetime.now().timestamp()}"
        
        skill = ProceduralSkill(
            id=skill_id,
            name=name,
            steps=steps,
            proficiency=data.get("proficiency", 0.5)
        )
        
        self.skills[skill_id] = skill
        
        # Categorize skill
        category = data.get("category", "general")
        if category not in self.skill_categories:
            self.skill_categories[category] = []
        self.skill_categories[category].append(skill_id)
        
        self.logger.debug(f"Stored procedural skill: {skill_id}")
        return skill_id
    
    async def retrieve(self, query: str) -> List[Dict[str, Any]]:
        """Retrieve procedural skills."""
        results = []
        for skill in self.skills.values():
            if query.lower() in skill.name.lower():
                results.append({
                    "id": skill.id,
                    "name": skill.name,
                    "steps": skill.steps,
                    "proficiency": skill.proficiency,
                    "usage_count": skill.usage_count,
                    "last_used": skill.last_used.isoformat() if skill.last_used else None
                })
        return results
    
    async def search(self, query: str) -> List[Dict[str, Any]]:
        """Search procedural skills."""
        return await self.retrieve(query)
    
    async def analyze(self) -> Dict[str, Any]:
        """Analyze procedural memory."""
        return {
            "total_skills": len(self.skills),
            "categories": list(self.skill_categories.keys()),
            "avg_proficiency": sum(s.proficiency for s in self.skills.values()) / max(1, len(self.skills))
        }
    
    async def optimize(self) -> Dict[str, Any]:
        """Optimize procedural memory."""
        self.logger.info("Optimizing procedural memory")
        return {"status": "optimized", "skills_count": len(self.skills)}
    
    async def consolidate(self) -> Dict[str, Any]:
        """Consolidate procedural memory."""
        self.logger.info("Consolidating procedural memory")
        return {"status": "consolidated", "skills_count": len(self.skills)}
    
    def get_stats(self) -> Dict[str, Any]:
        """Get memory statistics."""
        return {
            "type": "procedural",
            "skills": len(self.skills),
            "categories": len(self.skill_categories)
        }