"""
Chat API Routes
"""
from fastapi import APIRouter, HTTPException, Depends
from pydantic import BaseModel
from typing import List, Optional, Dict
from datetime import datetime
import uuid
import logging

from app.services.ai_service import ai_service

logger = logging.getLogger(__name__)
router = APIRouter()


# Request/Response Models
class MessageRequest(BaseModel):
    """Incoming chat message"""
    message: str
    session_id: Optional[str] = None
    client_id: str
    channel: str = "web"  # web, whatsapp, voice
    user_id: Optional[str] = None
    metadata: Optional[Dict] = None


class MessageResponse(BaseModel):
    """Chat response"""
    response: str
    session_id: str
    message_id: str
    timestamp: str
    tokens_used: int = 0


class ConversationHistory(BaseModel):
    """Conversation history item"""
    role: str
    content: str
    timestamp: str


# In-memory conversation store (replace with Redis/DB in production)
conversations: Dict[str, List[Dict]] = {}
client_configs: Dict[str, Dict] = {
    # Example client configuration
    "demo_client": {
        "company_name": "Demo Company",
        "system_prompt": "You are a helpful assistant for Demo Company, an e-commerce platform.",
        "custom_instructions": "Always mention our 24/7 support if the customer seems frustrated.",
        "model": "gpt-4o-mini"
    }
}


@router.post("/message", response_model=MessageResponse)
async def send_message(request: MessageRequest):
    """
    Send a message and get AI response

    - **message**: The user's message
    - **session_id**: Optional session ID for conversation continuity
    - **client_id**: Client identifier for configuration
    - **channel**: Channel type (web, whatsapp, voice)
    """
    try:
        # Generate session ID if not provided
        session_id = request.session_id or str(uuid.uuid4())

        # Get or create conversation history
        if session_id not in conversations:
            conversations[session_id] = []

        # Add user message to history
        conversations[session_id].append({
            "role": "user",
            "content": request.message,
            "timestamp": datetime.utcnow().isoformat()
        })

        # Get client configuration
        client_config = client_configs.get(request.client_id, {})
        system_prompt = client_config.get("system_prompt")
        model = client_config.get("model")

        # Prepare messages for AI
        messages = [
            {"role": msg["role"], "content": msg["content"]}
            for msg in conversations[session_id]
        ]

        # Get AI response
        ai_response = await ai_service.get_chat_response(
            messages=messages,
            system_prompt=system_prompt,
            client_config=client_config,
            model=model
        )

        # Add assistant response to history
        conversations[session_id].append({
            "role": "assistant",
            "content": ai_response["content"],
            "timestamp": datetime.utcnow().isoformat()
        })

        # Generate message ID
        message_id = str(uuid.uuid4())

        logger.info(f"Message processed: session={session_id}, client={request.client_id}")

        return MessageResponse(
            response=ai_response["content"],
            session_id=session_id,
            message_id=message_id,
            timestamp=datetime.utcnow().isoformat(),
            tokens_used=ai_response.get("tokens_used", 0)
        )

    except Exception as e:
        logger.error(f"Error processing message: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/conversation/{session_id}")
async def get_conversation(session_id: str):
    """Get conversation history by session ID"""
    if session_id not in conversations:
        raise HTTPException(status_code=404, detail="Conversation not found")

    return {
        "session_id": session_id,
        "messages": conversations[session_id],
        "message_count": len(conversations[session_id])
    }


@router.delete("/conversation/{session_id}")
async def clear_conversation(session_id: str):
    """Clear conversation history"""
    if session_id in conversations:
        del conversations[session_id]
        return {"message": "Conversation cleared", "session_id": session_id}
    raise HTTPException(status_code=404, detail="Conversation not found")


@router.post("/client/configure")
async def configure_client(client_id: str, config: Dict):
    """
    Configure client-specific settings

    - **company_name**: Company name for personalization
    - **system_prompt**: Custom system prompt
    - **custom_instructions**: Additional AI instructions
    - **model**: Preferred AI model
    """
    client_configs[client_id] = config
    return {"message": "Client configured", "client_id": client_id}


@router.get("/client/{client_id}/config")
async def get_client_config(client_id: str):
    """Get client configuration"""
    if client_id not in client_configs:
        raise HTTPException(status_code=404, detail="Client not found")
    return client_configs[client_id]


@router.get("/stats")
async def get_stats():
    """Get service statistics"""
    total_conversations = len(conversations)
    total_messages = sum(len(msgs) for msgs in conversations.values())

    return {
        "active_conversations": total_conversations,
        "total_messages": total_messages,
        "configured_clients": len(client_configs)
    }
