"""
AI router — provides AI-assisted generation features for cemetery staff.

Rate limiting: Use the RATE_LIMIT_AI setting (default 10/minute) via slowapi
on the API gateway or nginx upstream. Placeholder comment below where inline
rate-limiting would be applied if using slowapi decorators.
"""
from typing import Optional
from datetime import date

from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel

from src.core.config import settings
from src.core.constants import UserRole
from src.core.dependencies import require_roles

router = APIRouter(prefix="/ai", tags=["AI"])


# ---------------------------------------------------------------------------
# Request / Response schemas (kept inline — no separate schema file needed)
# ---------------------------------------------------------------------------

class GenerateBiographyRequest(BaseModel):
    first_name: str
    last_name: str
    occupation: Optional[str] = None
    hobbies: Optional[str] = None
    key_events: Optional[str] = None
    tone: Optional[str] = "warm and respectful"
    date_of_birth: Optional[date] = None
    date_of_death: Optional[date] = None


class GenerateBiographyResponse(BaseModel):
    biography_text: str


# ---------------------------------------------------------------------------
# Endpoints
# ---------------------------------------------------------------------------

@router.post(
    "/generate-biography",
    response_model=dict,
    summary="Generate a memorial biography using Claude",
)
async def generate_biography(
    body: GenerateBiographyRequest,
    # RATE LIMIT PLACEHOLDER: apply @limiter.limit(settings.RATE_LIMIT_AI) here
    # when slowapi is wired to the app instance.
    current_user=Depends(
        require_roles(UserRole.ADMINISTRATOR, UserRole.MANAGER, UserRole.STAFF)
    ),
):
    """
    Use the Anthropic Claude API to draft a memorial biography based on
    the provided personal details. Staff can then edit and publish it.
    """
    if not settings.ANTHROPIC_API_KEY:
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail="AI service is not configured. Set ANTHROPIC_API_KEY.",
        )

    # Build a structured prompt
    life_span = ""
    if body.date_of_birth and body.date_of_death:
        life_span = f" ({body.date_of_birth.year}–{body.date_of_death.year})"
    elif body.date_of_birth:
        life_span = f" (born {body.date_of_birth.year})"

    details_parts = []
    if body.occupation:
        details_parts.append(f"Occupation: {body.occupation}")
    if body.hobbies:
        details_parts.append(f"Hobbies and interests: {body.hobbies}")
    if body.key_events:
        details_parts.append(f"Key life events: {body.key_events}")

    details_text = "\n".join(details_parts) if details_parts else "No additional details provided."
    tone = body.tone or "warm and respectful"

    prompt = (
        f"You are a compassionate writer helping a cemetery staff member create a "
        f"memorial biography. Write a biography for {body.first_name} {body.last_name}"
        f"{life_span} in a {tone} tone.\n\n"
        f"Personal details:\n{details_text}\n\n"
        f"Write 2-4 paragraphs. Focus on celebrating their life. "
        f"Do not add unverified facts. Keep it dignified and heartfelt."
    )

    try:
        import anthropic

        client = anthropic.AsyncAnthropic(api_key=settings.ANTHROPIC_API_KEY)
        message = await client.messages.create(
            model="claude-opus-4-5",
            max_tokens=1024,
            messages=[{"role": "user", "content": prompt}],
        )
        biography_text = message.content[0].text.strip()
        return {"success": True, "data": {"biography_text": biography_text}}

    except anthropic.AuthenticationError:
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail="AI service authentication failed. Check ANTHROPIC_API_KEY.",
        )
    except anthropic.RateLimitError:
        raise HTTPException(
            status_code=status.HTTP_429_TOO_MANY_REQUESTS,
            detail="AI service rate limit reached. Please try again shortly.",
        )
    except anthropic.APIStatusError as exc:
        raise HTTPException(
            status_code=status.HTTP_502_BAD_GATEWAY,
            detail=f"AI service error: {exc.message}",
        )
    except Exception as exc:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Unexpected error generating biography: {str(exc)}",
        )


@router.post(
    "/extract-record",
    summary="Extract burial record from a document image (coming soon)",
    status_code=status.HTTP_501_NOT_IMPLEMENTED,
)
async def extract_record(
    current_user=Depends(
        require_roles(UserRole.ADMINISTRATOR, UserRole.MANAGER, UserRole.STAFF)
    ),
):
    """
    Placeholder endpoint — GPT-4o Vision-based document extraction.
    Will accept an uploaded image or S3 key of a scanned burial register
    and return a structured record payload.
    """
    raise HTTPException(
        status_code=status.HTTP_501_NOT_IMPLEMENTED,
        detail="GPT-4o Vision extraction coming soon",
    )
