from fastapi import APIRouter, Depends, HTTPException, status
from src.application.dtos.conversation import (
    CreateConversationRequestDTO,
    SendMessageRequestDTO,
    ConversationResponseDTO,
    ConversationDetailResponseDTO,
    MessageResponseDTO
)
from src.application.services.conversation_service import ConversationService
from src.dependencies import get_current_user, get_conversation_service
from typing import List
import logging

logger = logging.getLogger(__name__)
router = APIRouter(tags=["conversations"])

@router.post("/", response_model=ConversationResponseDTO, status_code=status.HTTP_201_CREATED)
async def create_conversation(
    request: CreateConversationRequestDTO,
    current_user: dict = Depends(get_current_user),
    chat_service: ConversationService = Depends(get_conversation_service)
):
    """Create a new conversation for a chart"""
    try:
        return await chat_service.create_conversation(current_user["id"], request)
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"Error creating conversation: {str(e)}")
        raise HTTPException(status_code=500, detail="Failed to create conversation")

@router.get("/", response_model=List[ConversationResponseDTO])
async def list_conversations(
    current_user: dict = Depends(get_current_user),
    limit: int = 20,
    chat_service: ConversationService = Depends(get_conversation_service)
):
    """List user's conversations"""
    try:
        return await chat_service.get_user_conversations(current_user["id"], limit)
    except Exception as e:
        logger.error(f"Error listing conversations: {str(e)}")
        raise HTTPException(status_code=500, detail="Failed to list conversations")

@router.get("/{conversation_id}", response_model=ConversationDetailResponseDTO)
async def get_conversation(
    conversation_id: str,
    current_user: dict = Depends(get_current_user),
    chat_service: ConversationService = Depends(get_conversation_service)
):
    """Get conversation details with messages"""
    try:
        return await chat_service.get_conversation_details(conversation_id, current_user["id"])
    except ValueError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except Exception as e:
        logger.error(f"Error getting conversation: {str(e)}")
        raise HTTPException(status_code=500, detail="Failed to get conversation")

@router.post("/{conversation_id}/messages", response_model=MessageResponseDTO)
async def send_message(
    conversation_id: str,
    request: SendMessageRequestDTO,
    current_user: dict = Depends(get_current_user),
    chat_service: ConversationService = Depends(get_conversation_service)
):
    """Send a message in a conversation"""
    try:
        return await chat_service.send_message(conversation_id, current_user["id"], request)
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"Error sending message: {str(e)}")
        raise HTTPException(status_code=500, detail="Failed to send message")

@router.delete("/{conversation_id}")
async def delete_conversation(
    conversation_id: str,
    current_user: dict = Depends(get_current_user),
    chat_service: ConversationService = Depends(get_conversation_service)
):
    """Delete a conversation (soft delete)"""
    try:
        success = await chat_service.delete_conversation(conversation_id, current_user["id"])
        if success:
            return {"message": "Conversation deleted successfully"}
        else:
            raise HTTPException(status_code=404, detail="Conversation not found")
    except ValueError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except Exception as e:
        logger.error(f"Error deleting conversation: {str(e)}")
        raise HTTPException(status_code=500, detail="Failed to delete conversation")

@router.get("/statistics/summary")
async def get_conversation_statistics(
    current_user: dict = Depends(get_current_user),
    chat_service: ConversationService = Depends(get_conversation_service)

):
    """Get conversation statistics for the current user"""
    try:
        stats = await chat_service.get_conversation_statistics(current_user["id"])
        return stats
    except Exception as e:
        logger.error(f"Error getting conversation statistics: {str(e)}")
        raise HTTPException(status_code=500, detail="Failed to get conversation statistics") 