# Copyright (c) 2025 Patrick Motsch
# All rights reserved.
"""
Chat Playground Feature Interface.
Wrapper around interfaceDbChat with feature instance context.
"""

import logging
from typing import Dict, Any, List, Optional

from modules.datamodels.datamodelUam import User
from modules.interfaces import interfaceDbChat

logger = logging.getLogger(__name__)

# Feature code constant
FEATURE_CODE = "chatplayground"

# Singleton instances cache
_instances: Dict[str, "ChatPlaygroundObjects"] = {}


def getInterface(currentUser: User, mandateId: str = None, featureInstanceId: str = None) -> "ChatPlaygroundObjects":
    """
    Factory function to get or create a ChatPlaygroundObjects instance.
    Uses singleton pattern per user context.
    
    Args:
        currentUser: Current user object
        mandateId: Mandate ID
        featureInstanceId: Feature instance ID
        
    Returns:
        ChatPlaygroundObjects instance
    """
    cacheKey = f"{currentUser.id}_{mandateId}_{featureInstanceId}"
    
    if cacheKey not in _instances:
        _instances[cacheKey] = ChatPlaygroundObjects(currentUser, mandateId, featureInstanceId)
    else:
        # Update context if needed
        _instances[cacheKey].setUserContext(currentUser, mandateId, featureInstanceId)
    
    return _instances[cacheKey]


class ChatPlaygroundObjects:
    """
    Chat Playground feature interface.
    Wraps the shared interfaceDbChat with feature instance context.
    """
    
    FEATURE_CODE = FEATURE_CODE
    
    def __init__(self, currentUser: User, mandateId: str = None, featureInstanceId: str = None):
        """
        Initialize the Chat Playground interface.
        
        Args:
            currentUser: Current user object
            mandateId: Mandate ID
            featureInstanceId: Feature instance ID
        """
        self.currentUser = currentUser
        self.mandateId = mandateId
        self.featureInstanceId = featureInstanceId
        
        # Get the underlying chat interface
        self._chatInterface = interfaceDbChat.getInterface(
            currentUser, 
            mandateId=mandateId,
            featureInstanceId=featureInstanceId
        )
    
    def setUserContext(self, currentUser: User, mandateId: str = None, featureInstanceId: str = None):
        """
        Update the user context.
        
        Args:
            currentUser: Current user object
            mandateId: Mandate ID
            featureInstanceId: Feature instance ID
        """
        self.currentUser = currentUser
        self.mandateId = mandateId
        self.featureInstanceId = featureInstanceId
        
        # Update underlying interface
        self._chatInterface = interfaceDbChat.getInterface(
            currentUser, 
            mandateId=mandateId,
            featureInstanceId=featureInstanceId
        )
    
    # =========================================================================
    # Delegated methods from interfaceDbChat
    # =========================================================================
    
    def getWorkflow(self, workflowId: str) -> Optional[Dict[str, Any]]:
        """Get a workflow by ID."""
        return self._chatInterface.getWorkflow(workflowId)
    
    def getWorkflows(self, pagination=None) -> Dict[str, Any]:
        """Get all workflows with pagination."""
        return self._chatInterface.getWorkflows(pagination=pagination)
    
    def getUnifiedChatData(self, workflowId: str, afterTimestamp: float = None) -> Dict[str, Any]:
        """Get unified chat data for a workflow."""
        return self._chatInterface.getUnifiedChatData(workflowId, afterTimestamp)
    
    def createWorkflow(self, workflow) -> Dict[str, Any]:
        """Create a new workflow."""
        return self._chatInterface.createWorkflow(workflow)
    
    def updateWorkflow(self, workflowId: str, updates: Dict[str, Any]) -> Optional[Dict[str, Any]]:
        """Update a workflow."""
        return self._chatInterface.updateWorkflow(workflowId, updates)
    
    def deleteWorkflow(self, workflowId: str) -> bool:
        """Delete a workflow."""
        return self._chatInterface.deleteWorkflow(workflowId)
    
    def getMessages(self, workflowId: str) -> List[Dict[str, Any]]:
        """Get messages for a workflow."""
        return self._chatInterface.getMessages(workflowId)
    
    def createMessage(self, message) -> Dict[str, Any]:
        """Create a new message."""
        return self._chatInterface.createMessage(message)
    
    def getLogs(self, workflowId: str) -> List[Dict[str, Any]]:
        """Get logs for a workflow."""
        return self._chatInterface.getLogs(workflowId)
    
    def createLog(self, log) -> Dict[str, Any]:
        """Create a new log entry."""
        return self._chatInterface.createLog(log)
    
    def getStats(self, workflowId: str) -> List[Dict[str, Any]]:
        """Get stats for a workflow."""
        return self._chatInterface.getStats(workflowId)
    
    def createStat(self, stat) -> Dict[str, Any]:
        """Create a new stat entry."""
        return self._chatInterface.createStat(stat)
