import os
import json
import time
import uuid
from typing import Dict, List, Any, Optional
from utils.conversation_memory import Message, Conversation, ConversationMemoryManager

class PersistentConversationMemoryManager(ConversationMemoryManager):
    """Manages conversations with persistence to disk"""
    
    def __init__(self, storage_dir: str = "conversation_data", max_conversations: int = 1000, max_history: int = 50):
        """
        Initialize the persistent conversation memory manager
        
        Args:
            storage_dir: Directory to store conversation data
            max_conversations: Maximum number of conversations to store
            max_history: Maximum number of messages per conversation
        """
        super().__init__(max_conversations, max_history)
        self.storage_dir = storage_dir
        
        # Create storage directory if it doesn't exist
        os.makedirs(self.storage_dir, exist_ok=True)
        
        # Load existing conversations
        self._load_conversations()
        
    def _get_conversation_path(self, conversation_id: str) -> str:
        """Get the file path for a conversation"""
        return os.path.join(self.storage_dir, f"{conversation_id}.json")
        
    def _load_conversations(self):
        """Load conversations from disk"""
        try:
            # Get all JSON files in the storage directory
            files = [f for f in os.listdir(self.storage_dir) if f.endswith('.json')]
            
            # Load each conversation
            for file in files[:self.max_conversations]:  # Limit to max_conversations
                conversation_id = file.replace('.json', '')
                try:
                    with open(os.path.join(self.storage_dir, file), 'r', encoding='utf-8') as f:
                        data = json.load(f)
                        conversation = Conversation.from_dict(data)
                        self.conversations[conversation_id] = conversation
                except Exception as e:
                    print(f"Error loading conversation {conversation_id}: {str(e)}")
                    
            print(f"Loaded {len(self.conversations)} conversations from disk")
        except Exception as e:
            print(f"Error loading conversations: {str(e)}")
            
    def _save_conversation(self, conversation_id: str):
        """Save a conversation to disk"""
        try:
            conversation = self.get_conversation(conversation_id)
            if not conversation:
                return
                
            # Convert to dictionary
            data = conversation.to_dict()
            
            # Save to file
            with open(self._get_conversation_path(conversation_id), 'w', encoding='utf-8') as f:
                json.dump(data, f, ensure_ascii=False, indent=2)
        except Exception as e:
            print(f"Error saving conversation {conversation_id}: {str(e)}")
            
    def create_conversation(self) -> Conversation:
        """Create a new conversation and save it"""
        conversation = super().create_conversation()
        self._save_conversation(conversation.conversation_id)
        return conversation
        
    def add_message(self, conversation_id: str, content: str, role: str) -> Optional[Message]:
        """Add a message to a conversation and save it"""
        message = super().add_message(conversation_id, content, role)
        if message:
            self._save_conversation(conversation_id)
        return message
        
    def delete_conversation(self, conversation_id: str) -> bool:
        """Delete a conversation"""
        if conversation_id in self.conversations:
            del self.conversations[conversation_id]
            
            # Delete the file if it exists
            file_path = self._get_conversation_path(conversation_id)
            if os.path.exists(file_path):
                os.remove(file_path)
                
            return True
        return False

# Create a singleton instance
persistent_conversation_memory = PersistentConversationMemoryManager()
