# @File: backend/routers/chat_branding_api.py
# @Desc: Public + admin endpoints for chat widget branding.
#        - GET  /api/v1/chat/branding         -> public read (widget)
#        - PUT  /api/v1/chat/admin/branding   -> admin upsert
#        - POST /api/v1/chat/admin/branding/reset -> reset to defaults
import logging
from typing import Any, Dict, Optional

from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from sqlalchemy.ext.asyncio import AsyncSession

from core.database import get_db
from services.chat_branding_public import (
    DEFAULT_BRANDING,
    get_active_branding,
    reset_branding,
    upsert_branding,
)

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/api/v1/chat", tags=["chat-branding"])


class BrandingPayload(BaseModel):
    widget_name: Optional[str] = None
    avatar_url: Optional[str] = None
    avatar_fallback_initials: Optional[str] = None
    agent_avatar_url: Optional[str] = None
    primary_color: Optional[str] = None
    accent_color: Optional[str] = None
    bubble_bg_color: Optional[str] = None
    bubble_text_color: Optional[str] = None
    header_bg_color: Optional[str] = None
    header_text_color: Optional[str] = None
    launcher_style: Optional[str] = None
    launcher_icon: Optional[str] = None
    launcher_icon_url: Optional[str] = None
    launcher_position: Optional[str] = None
    welcome_message: Optional[str] = None
    offline_message: Optional[str] = None
    ai_intro_message: Optional[str] = None
    human_handover_message: Optional[str] = None
    input_placeholder: Optional[str] = None
    show_branding_footer: Optional[bool] = None
    footer_text: Optional[str] = None
    enable_sound: Optional[bool] = None
    notification_sound: Optional[str] = None
    theme_mode: Optional[str] = None
    rounded: Optional[str] = None
    font_family: Optional[str] = None


@router.get("/branding")
async def get_branding_public(db: AsyncSession = Depends(get_db)) -> Dict[str, Any]:
    """Public read for the widget. No auth required — all fields are visual only."""
    try:
        data = await get_active_branding(db)
        return {"branding": data, "defaults": DEFAULT_BRANDING}
    except Exception as e:
        logger.error("branding read failed: %s", e, exc_info=True)
        # Never break the widget if the DB call fails — return defaults.
        return {"branding": DEFAULT_BRANDING, "defaults": DEFAULT_BRANDING}


@router.put("/admin/branding")
async def update_branding(
    payload: BrandingPayload,
    db: AsyncSession = Depends(get_db),
) -> Dict[str, Any]:
    try:
        data = await upsert_branding(db, payload.model_dump(exclude_unset=True))
        return {"branding": data}
    except Exception as e:
        logger.error("branding upsert failed: %s", e, exc_info=True)
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/admin/branding/reset")
async def reset_branding_endpoint(db: AsyncSession = Depends(get_db)) -> Dict[str, Any]:
    try:
        data = await reset_branding(db)
        return {"branding": data}
    except Exception as e:
        logger.error("branding reset failed: %s", e, exc_info=True)
        raise HTTPException(status_code=500, detail=str(e))