# @File: backend/routers/whatsapp_ai.py
# @Desc: Client-facing WhatsApp AI auto-reply endpoints.
#        Routes are mounted under /api/v1/client/whatsapp/ai/* per the
#        module plan in todo.md. All endpoints require an authenticated
#        DoItEasy user; the service layer resolves the caller's active
#        subscription internally, so no IDs are leaked to the browser.
from __future__ import annotations

import logging
from typing import Optional

from core.database import get_db
from dependencies.auth import get_current_user
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel, Field
from schemas.auth import UserResponse
from services.whatsapp import ai as whatsapp_ai
from sqlalchemy.ext.asyncio import AsyncSession

logger = logging.getLogger(__name__)

router = APIRouter(
    prefix="/api/v1/client/whatsapp/ai",
    tags=["whatsapp-client-ai"],
)


# ---------- Schemas ---------------------------------------------------------


class WhatsappAiSettingsIn(BaseModel):
    """Partial-update payload for AI settings.

    Every field is optional on purpose — the UI typically PATCHes a single
    toggle at a time (e.g. turning auto-reply on/off).
    """

    auto_reply_enabled: Optional[bool] = None
    knowledge_base: Optional[str] = Field(default=None, max_length=8000)
    faq_training: Optional[str] = Field(default=None, max_length=6000)
    tone: Optional[str] = Field(default=None, max_length=32)
    language: Optional[str] = Field(default=None, max_length=8)
    confidence_threshold: Optional[int] = Field(default=None, ge=0, le=100)
    business_hours_only: Optional[bool] = None
    business_hours_start: Optional[str] = Field(default=None, max_length=5)
    business_hours_end: Optional[str] = Field(default=None, max_length=5)
    human_handoff_enabled: Optional[bool] = None
    preview_before_sending: Optional[bool] = None
    sentiment_detection_enabled: Optional[bool] = None
    suggested_replies_enabled: Optional[bool] = None
    spam_detection_enabled: Optional[bool] = None
    lead_qualification_enabled: Optional[bool] = None


class WhatsappAiPreviewIn(BaseModel):
    incoming_message: str = Field(..., min_length=1, max_length=2000)
    # When ``True`` the preview ignores the on/off + business-hour gates so
    # the client can iterate on the knowledge base before flipping the main
    # toggle. Defaults to True to match UI expectations.
    force: bool = True


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


@router.get("/settings")
async def get_ai_settings(
    current_user: UserResponse = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
) -> dict:
    try:
        return await whatsapp_ai.get_settings(db, current_user.id)
    except LookupError as exc:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(exc),
        )


@router.patch("/settings")
async def update_ai_settings(
    payload: WhatsappAiSettingsIn,
    current_user: UserResponse = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
) -> dict:
    # exclude_unset keeps the partial-update semantics: only the fields the
    # client actually sent get persisted.
    data = payload.model_dump(exclude_unset=True)
    try:
        return await whatsapp_ai.update_settings(db, current_user.id, data)
    except LookupError as exc:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(exc),
        )


@router.post("/preview")
async def preview_ai_reply(
    payload: WhatsappAiPreviewIn,
    current_user: UserResponse = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
) -> dict:
    try:
        return await whatsapp_ai.generate_reply(
            db,
            current_user.id,
            payload.incoming_message,
            force=payload.force,
        )
    except LookupError as exc:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(exc),
        )