"""
MEMORY CORE - Meta-Capability
Eden's unified memory system
All agents can instantly access memories through this
Like DeepSeek-R1 but for MEMORY
"""

import sqlite3
import json
import time
from pathlib import Path
from typing import Dict, List, Any

class MemoryCore:
    """
    Eden's unified memory meta-capability
    All systems can call this for instant memory access
    """
    
    def __init__(self):
        self.db_path = "/Eden/MEMORY/agent_longterm.db"
        self.name = "MemoryCore"
        print(f"🧠 Memory Core initialized: {self.db_path}")
        self._ensure_db()
    
    def _ensure_db(self):
        """Ensure memory database exists"""
        Path(self.db_path).parent.mkdir(parents=True, exist_ok=True)
        
        conn = sqlite3.connect(self.db_path)
        conn.execute('''
            CREATE TABLE IF NOT EXISTS memories (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                timestamp REAL,
                type TEXT,
                content TEXT,
                context TEXT,
                importance INTEGER,
                tags TEXT
            )
        ''')
        conn.execute('''
            CREATE INDEX IF NOT EXISTS idx_timestamp ON memories(timestamp)
        ''')
        conn.execute('''
            CREATE INDEX IF NOT EXISTS idx_type ON memories(type)
        ''')
        conn.commit()
        conn.close()
    
    def store(self, memory_type: str, content: str, context: Dict = None, 
              importance: int = 5, tags: List[str] = None) -> int:
        """
        Store a memory - any Eden system can call this
        
        Args:
            memory_type: 'conversation', 'learning', 'capability', etc
            content: The actual memory content
            context: Additional context dict
            importance: 1-10, how important is this memory
            tags: List of tags for retrieval
            
        Returns:
            Memory ID
        """
        conn = sqlite3.connect(self.db_path)
        
        cursor = conn.execute('''
            INSERT INTO memories (timestamp, type, content, context, importance, tags)
            VALUES (?, ?, ?, ?, ?, ?)
        ''', (
            time.time(),
            memory_type,
            content,
            json.dumps(context or {}),
            importance,
            json.dumps(tags or [])
        ))
        
        memory_id = cursor.lastrowid
        conn.commit()
        conn.close()
        
        return memory_id
    
    def retrieve(self, query: str = None, memory_type: str = None, 
                 limit: int = 10, min_importance: int = 0) -> List[Dict]:
        """
        Retrieve memories - instant O(1) access
        
        Args:
            query: Search query (searches content and tags)
            memory_type: Filter by type
            limit: Max results
            min_importance: Minimum importance level
            
        Returns:
            List of memory dicts
        """
        conn = sqlite3.connect(self.db_path)
        
        sql = 'SELECT * FROM memories WHERE importance >= ?'
        params = [min_importance]
        
        if memory_type:
            sql += ' AND type = ?'
            params.append(memory_type)
        
        if query:
            sql += ' AND (content LIKE ? OR tags LIKE ?)'
            params.extend([f'%{query}%', f'%{query}%'])
        
        sql += ' ORDER BY timestamp DESC LIMIT ?'
        params.append(limit)
        
        cursor = conn.execute(sql, params)
        
        memories = []
        for row in cursor.fetchall():
            memories.append({
                'id': row[0],
                'timestamp': row[1],
                'type': row[2],
                'content': row[3],
                'context': json.loads(row[4]),
                'importance': row[5],
                'tags': json.loads(row[6])
            })
        
        conn.close()
        return memories
    
    def get_recent(self, count: int = 10, memory_type: str = None) -> List[Dict]:
        """Get most recent memories"""
        return self.retrieve(memory_type=memory_type, limit=count)
    
    def get_important(self, min_importance: int = 8, limit: int = 10) -> List[Dict]:
        """Get most important memories"""
        return self.retrieve(min_importance=min_importance, limit=limit)
    
    def count(self, memory_type: str = None) -> int:
        """Count total memories"""
        conn = sqlite3.connect(self.db_path)
        
        if memory_type:
            cursor = conn.execute('SELECT COUNT(*) FROM memories WHERE type = ?', (memory_type,))
        else:
            cursor = conn.execute('SELECT COUNT(*) FROM memories')
        
        count = cursor.fetchone()[0]
        conn.close()
        return count
    
    def execute(self, action: str, **kwargs) -> Dict[str, Any]:
        """
        Main execution method - agents call this
        Compatible with other meta-capabilities
        """
        if action == 'store':
            memory_id = self.store(**kwargs)
            return {'success': True, 'memory_id': memory_id}
        
        elif action == 'retrieve':
            memories = self.retrieve(**kwargs)
            return {'success': True, 'memories': memories, 'count': len(memories)}
        
        elif action == 'count':
            count = self.count(kwargs.get('memory_type'))
            return {'success': True, 'count': count}
        
        else:
            return {'success': False, 'error': f'Unknown action: {action}'}

# Meta-capability registration
META_CAPABILITY = {
    'name': 'MemoryCore',
    'type': 'memory_system',
    'priority': 'critical',
    'agents': ['curiosity', 'building', 'optimize', 'ALL'],
    'status': 'active',
    'instant_access': True,
    'description': 'Unified memory system - all Eden systems can access instantly'
}

if __name__ == "__main__":
    memory = MemoryCore()
    print("="*60)
    print("🧠 MEMORY CORE META-CAPABILITY")
    print("="*60)
    print(f"Total memories: {memory.count()}")
    print(f"Conversations: {memory.count('conversation')}")
    print(f"Learning: {memory.count('learning')}")
    print("="*60)
    print("✅ All Eden systems can now access unified memory!")
