"""
Sentiment Analysis API Routes
"""
from fastapi import APIRouter, HTTPException
from typing import List, Dict, Any, Optional
from pydantic import BaseModel

from app.services.sentiment_service import sentiment_service

router = APIRouter()


class TextInput(BaseModel):
    text: str


class BatchTextInput(BaseModel):
    texts: List[str]


class Message(BaseModel):
    role: str
    content: str


class ConversationInput(BaseModel):
    messages: List[Message]


class KeywordInput(BaseModel):
    texts: List[str]
    sentiments: List[str]


@router.post("/analyze", summary="Analyze sentiment")
async def analyze_sentiment(input: TextInput):
    """
    Analyze sentiment of a single text
    """
    if not input.text or not input.text.strip():
        raise HTTPException(status_code=400, detail="Text cannot be empty")

    result = sentiment_service.analyze_text(input.text)
    return {
        "text": input.text,
        "analysis": result
    }


@router.post("/batch", summary="Batch sentiment analysis")
async def analyze_batch(input: BatchTextInput):
    """
    Analyze sentiment of multiple texts
    """
    if not input.texts:
        raise HTTPException(status_code=400, detail="Texts list cannot be empty")

    if len(input.texts) > 100:
        raise HTTPException(status_code=400, detail="Maximum 100 texts per batch")

    results = await sentiment_service.analyze_batch(input.texts)
    return {
        "count": len(input.texts),
        "results": [
            {"text": text, "analysis": analysis}
            for text, analysis in zip(input.texts, results)
        ]
    }


@router.post("/conversation", summary="Analyze conversation sentiment")
async def analyze_conversation(input: ConversationInput):
    """
    Analyze sentiment progression in a conversation
    """
    if not input.messages:
        raise HTTPException(status_code=400, detail="Messages cannot be empty")

    messages = [{"role": m.role, "content": m.content} for m in input.messages]
    result = await sentiment_service.analyze_conversation(messages)
    return result


@router.post("/keywords", summary="Extract keywords by sentiment")
async def extract_keywords(input: KeywordInput):
    """
    Extract keywords grouped by sentiment
    """
    if len(input.texts) != len(input.sentiments):
        raise HTTPException(
            status_code=400,
            detail="Texts and sentiments must have the same length"
        )

    result = sentiment_service.get_keywords_by_sentiment(
        input.texts,
        input.sentiments
    )
    return {"keywords_by_sentiment": result}


@router.get("/demo", summary="Demo sentiment analysis")
async def demo_analysis():
    """
    Demo sentiment analysis with sample texts
    """
    sample_texts = [
        "I love this product! It works perfectly.",
        "The service was okay, nothing special.",
        "This is terrible, I want a refund immediately!",
        "Thank you for your quick response.",
        "I'm not sure if this is what I needed."
    ]

    results = await sentiment_service.analyze_batch(sample_texts)

    return {
        "demo": True,
        "samples": [
            {"text": text, "analysis": analysis}
            for text, analysis in zip(sample_texts, results)
        ]
    }
