"""
Ollama API endpoints for local AI status and simple tasks.
"""

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from typing import Optional, List
from app.services.ollama_service import ollama_service
from app.config import settings

router = APIRouter(prefix="/api/ollama", tags=["Local AI"])


class OllamaStatus(BaseModel):
    available: bool
    model: str
    embed_model: str
    base_url: str


class GenerateRequest(BaseModel):
    prompt: str
    system: Optional[str] = None
    temperature: float = 0.7
    max_tokens: int = 500


class GenerateResponse(BaseModel):
    response: Optional[str]
    model: str
    success: bool


class SentimentRequest(BaseModel):
    text: str


class SentimentResponse(BaseModel):
    sentiment: Optional[str]
    confidence: Optional[float]
    success: bool


class ClassifyRequest(BaseModel):
    text: str
    categories: List[str]


class ClassifyResponse(BaseModel):
    category: Optional[str]
    success: bool


class SummarizeRequest(BaseModel):
    text: str
    max_sentences: int = 2


class SummarizeResponse(BaseModel):
    summary: Optional[str]
    success: bool


@router.get("/status", response_model=OllamaStatus)
async def get_ollama_status():
    """Check if Ollama is available and configured."""
    available = await ollama_service.is_available()
    return OllamaStatus(
        available=available,
        model=settings.OLLAMA_MODEL,
        embed_model=settings.OLLAMA_MODEL_EMBED,
        base_url=settings.OLLAMA_BASE_URL
    )


@router.post("/generate", response_model=GenerateResponse)
async def generate_text(request: GenerateRequest):
    """Generate text using local Ollama model."""
    result = await ollama_service.generate(
        prompt=request.prompt,
        system=request.system,
        temperature=request.temperature,
        max_tokens=request.max_tokens
    )
    return GenerateResponse(
        response=result,
        model=settings.OLLAMA_MODEL,
        success=result is not None
    )


@router.post("/sentiment", response_model=SentimentResponse)
async def analyze_sentiment(request: SentimentRequest):
    """Quick sentiment analysis using local model."""
    result = await ollama_service.quick_sentiment(request.text)
    if result:
        return SentimentResponse(
            sentiment=result.get("sentiment"),
            confidence=result.get("confidence"),
            success=True
        )
    return SentimentResponse(sentiment=None, confidence=None, success=False)


@router.post("/classify", response_model=ClassifyResponse)
async def classify_text(request: ClassifyRequest):
    """Classify text into one of the provided categories."""
    result = await ollama_service.quick_classify(request.text, request.categories)
    return ClassifyResponse(
        category=result,
        success=result is not None
    )


@router.post("/summarize", response_model=SummarizeResponse)
async def summarize_text(request: SummarizeRequest):
    """Quick text summarization using local model."""
    result = await ollama_service.quick_summarize(
        text=request.text,
        max_sentences=request.max_sentences
    )
    return SummarizeResponse(
        summary=result,
        success=result is not None
    )
