"""
Gerenciador de Conversas Contínuas
Implementa contexto acumulado e refinamento
"""
from typing import List, Dict, Optional
from datetime import datetime
import uuid
from tiramisu.conversation.database import get_db


class ConversationManager:
    """Gerencia conversas contínuas com contexto"""
    
    def __init__(self):
        self.db = get_db()
    
    def create_conversation(self, title: str = None) -> str:
        """Cria nova conversa e retorna ID"""
        conv_id = str(uuid.uuid4())
        self.db.create_conversation(
            conv_id=conv_id,
            title=title or f"Conversa {datetime.now().strftime('%d/%m/%Y %H:%M')}",
            metadata={"created_via": "api"}
        )
        return conv_id
    
    def add_message(
        self, 
        conversation_id: str, 
        role: str, 
        content: str,
        metadata: Dict = None
    ) -> int:
        """Adiciona mensagem à conversa"""
        # Cria conversa se não existir
        if not self.db.conversation_exists(conversation_id):
            self.db.create_conversation(conversation_id)
        
        return self.db.add_message(
            conversation_id=conversation_id,
            role=role,
            content=content,
            metadata=metadata or {}
        )
    
    def get_conversation_history(
        self, 
        conversation_id: str,
        limit: int = None
    ) -> List[Dict]:
        """Retorna histórico completo da conversa"""
        return self.db.get_conversation_history(conversation_id, limit)
    
    def get_context_for_analysis(
        self, 
        conversation_id: str, 
        max_messages: int = 5
    ) -> str:
        """
        Gera contexto otimizado para análise
        Seguindo orientações do consultor
        """
        history = self.db.get_recent_messages(conversation_id, max_messages)
        
        if not history:
            return ""
        
        # Filtrar mensagens recentes (últimas 24h)
        relevant_messages = []
        for msg in history:
            msg_time = datetime.fromisoformat(msg.get('timestamp', ''))
            if (datetime.now() - msg_time).days < 1:
                relevant_messages.append(msg)
        
        # Formatar como diálogo Cliente/Consultor
        context_parts = []
        for msg in relevant_messages:
            role = "Cliente" if msg['role'] == 'user' else "Consultor"
            
            # Limitar tamanho de cada mensagem (300 chars)
            content = msg['content']
            if len(content) > 300:
                content = content[:300] + "..."
            
            context_parts.append(f"{role}: {content}")
        
        return "\n\n".join(context_parts)
    
    def get_summary(self, conversation_id: str) -> Dict:
        """Gera resumo executivo da conversa"""
        history = self.get_conversation_history(conversation_id)
        
        if not history:
            return {
                "conversation_id": conversation_id,
                "message_count": 0,
                "key_points": [],
                "last_interaction": None
            }
        
        # Extrair pontos-chave das respostas do assistente
        key_points = []
        for msg in history:
            if msg['role'] == 'assistant':
                metadata = msg.get('metadata', {})
                if isinstance(metadata, dict):
                    full_response = metadata.get('full_response', {})
                    if isinstance(full_response, dict):
                        recommendations = full_response.get('key_recommendations', [])
                        if recommendations:
                            key_points.extend(recommendations[:2])
        
        return {
            "conversation_id": conversation_id,
            "message_count": len(history),
            "key_points": key_points[:5],
            "last_interaction": history[-1]['timestamp'] if history else None
        }
    
    def estimate_tokens(self, conversation_id: str, max_messages: int = 5) -> int:
        """Estima tokens do contexto (aproximado)"""
        context = self.get_context_for_analysis(conversation_id, max_messages)
        # Estimativa: ~1.3 tokens por palavra
        return int(len(context.split()) * 1.3)
    
    def delete_conversation(self, conversation_id: str) -> bool:
        """Remove conversa completa"""
        return self.db.delete_conversation(conversation_id)


# Singleton
_manager_instance = None

def get_manager() -> ConversationManager:
    """Retorna instância única do manager"""
    global _manager_instance
    if _manager_instance is None:
        _manager_instance = ConversationManager()
    return _manager_instance
