"""
Endpoints de conversas contínuas
Implementação seguindo orientações do consultor
"""
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from typing import Optional
from datetime import datetime

from tiramisu.conversation.manager import get_manager
from tiramisu.engine.analyzer import TiramisuAnalyzer
from tiramisu.models.schemas import AnalysisType, ConversationAnalysisResponse 


router = APIRouter()
manager = get_manager()


class AnalyzeRequest(BaseModel):
    """Request para análise com conversa"""
    type: str
    content: str
    context: Optional[str] = None


@router.post("/api/conversations/{conv_id}/analyze", response_model=ConversationAnalysisResponse)
async def analyze_with_conversation(
    conv_id: str,
    request: AnalyzeRequest
):
    """
    Análise com contexto de conversa
    Implementação aprimorada do consultor
    """
    
    # 1. Recuperar histórico estruturado
    history = manager.get_conversation_history(conv_id)
    
    # 2. Formatar contexto de forma otimizada
    context_messages = []
    total_tokens = 0
    max_tokens = 2000
    
    for msg in reversed(history[-5:]):
        msg_text = f"{msg['role'].upper()}: {msg['content'][:500]}"
        msg_tokens = len(msg_text.split()) * 1.3
        
        if total_tokens + msg_tokens < max_tokens:
            context_messages.insert(0, msg_text)
            total_tokens += msg_tokens
        else:
            break
    
    # 3. Estruturar contexto para o GPT
    conversation_context = "\n".join(context_messages) if context_messages else ""
    
    structured_context = f"""
CONTEXTO DA CONVERSA:
{conversation_context}

CONTEXTO ADICIONAL:
{request.context or "Nenhum"}

INSTRUÇÃO: Considere o histórico acima ao analisar o conteúdo atual.
"""
    
    # 4. Salvar mensagem do usuário
    manager.add_message(
        conversation_id=conv_id,
        role="user",
        content=request.content,
        metadata={
            "type": request.type,
            "timestamp": datetime.now().isoformat()
        }
    )
    
    # 5. Converter string para Enum
    try:
        analysis_enum = AnalysisType(request.type.lower())
    except ValueError:
        analysis_enum = AnalysisType.CAMPAIGN
    
    # 6. Análise com contexto enriquecido
    analyzer = TiramisuAnalyzer()
    result = analyzer.analyze(
        analysis_type=analysis_enum,  # ← ENUM AQUI!
        content=request.content,
        context=structured_context
    )
    
    # 7. Salvar resposta COMPLETA
    response_data = result.model_dump() if hasattr(result, 'model_dump') else str(result)
    
    manager.add_message(
        conversation_id=conv_id,
        role="assistant",
        content=result.summary if hasattr(result, 'summary') else str(result)[:500],
        metadata={
            "full_response": response_data,
            "type": "analysis_response",
            "timestamp": datetime.now().isoformat()
        }
    )
    
    return ConversationAnalysisResponse(
        conversation_id=conv_id,
        message_count=len(history) + 2,
        analysis=result,
        timestamp=datetime.now().isoformat()
    )


@router.get("/api/conversations/{conv_id}/context")
async def get_conversation_context(
    conv_id: str,
    max_messages: int = 5
):
    """Retorna contexto formatado para debug"""
    context = manager.get_context_for_analysis(conv_id, max_messages)
    return {
        "conversation_id": conv_id,
        "context": context,
        "token_estimate": len(context.split()) * 1.3
    }


@router.get("/api/conversations/{conv_id}/summary")
async def get_conversation_summary(conv_id: str):
    """Gera resumo executivo da conversa"""
    return manager.get_summary(conv_id)


@router.post("/api/conversations/create")
async def create_conversation(title: Optional[str] = None):
    """Cria nova conversa"""
    conv_id = manager.create_conversation(title)
    return {
        "conversation_id": conv_id,
        "created_at": datetime.now().isoformat()
    }


@router.delete("/api/conversations/{conv_id}")
async def delete_conversation(conv_id: str):
    """Remove conversa"""
    success = manager.delete_conversation(conv_id)
    if not success:
        raise HTTPException(status_code=404, detail="Conversa não encontrada")
    return {"message": "Conversa removida com sucesso"}