# @File: backend/services/chat_branding_public.py
# @Desc: Helpers for reading/saving the single-row chat branding settings.
#        The chat_branding table is treated as a singleton (id=1 is the
#        active row). This service exposes safe public read and admin
#        upsert helpers so the widget and admin UI can share logic.
import logging
from typing import Any, Dict, Optional

from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from models.chat_branding import Chat_branding

logger = logging.getLogger(__name__)

DEFAULT_BRANDING: Dict[str, Any] = {
    "widget_name": "DoitEasy Support",
    "avatar_url": "/logo.svg",
    "avatar_fallback_initials": "DE",
    "agent_avatar_url": "",
    "primary_color": "#059669",
    "accent_color": "#10b981",
    "bubble_bg_color": "#ffffff",
    "bubble_text_color": "#0f172a",
    "header_bg_color": "#059669",
    "header_text_color": "#ffffff",
    "launcher_style": "circle",
    "launcher_icon": "chat",
    "launcher_icon_url": "",
    "launcher_position": "bottom-right",
    "welcome_message": "Hi {client_name}! {time_of_day} 👋 How can we help you today?",
    "offline_message": "We're currently offline. Leave a message and we'll reply by email.",
    "ai_intro_message": "Hi there! I'm the DoitEasy AI assistant. Ask me anything about hosting, domains, billing, or support — I'll answer instantly, and hand you to a human when needed.",
    "human_handover_message": "Connecting you to a human agent now…",
    "input_placeholder": "Type a message…",
    "show_branding_footer": True,
    "footer_text": "Powered by DoitEasy ✦ AI + Human support",
    "enable_sound": True,
    "notification_sound": "soft_chime",
    "theme_mode": "light",
    "rounded": "lg",
    "font_family": "Inter",
}

PUBLIC_FIELDS = list(DEFAULT_BRANDING.keys())


async def get_active_branding(db: AsyncSession) -> Dict[str, Any]:
    """Return current branding merged with defaults."""
    stmt = select(Chat_branding).order_by(Chat_branding.id.asc()).limit(1)
    result = await db.execute(stmt)
    row: Optional[Chat_branding] = result.scalar_one_or_none()

    data: Dict[str, Any] = dict(DEFAULT_BRANDING)
    if row:
        for field in PUBLIC_FIELDS:
            val = getattr(row, field, None)
            if val is not None and val != "":
                data[field] = val
        data["id"] = row.id
    return data


async def upsert_branding(db: AsyncSession, payload: Dict[str, Any]) -> Dict[str, Any]:
    """Create-or-update the singleton branding row."""
    stmt = select(Chat_branding).order_by(Chat_branding.id.asc()).limit(1)
    result = await db.execute(stmt)
    row: Optional[Chat_branding] = result.scalar_one_or_none()

    cleaned: Dict[str, Any] = {}
    for field in PUBLIC_FIELDS:
        if field in payload and payload[field] is not None:
            cleaned[field] = payload[field]

    if row is None:
        row = Chat_branding(**cleaned)
        db.add(row)
    else:
        for k, v in cleaned.items():
            setattr(row, k, v)
    await db.commit()
    await db.refresh(row)

    return await get_active_branding(db)


async def reset_branding(db: AsyncSession) -> Dict[str, Any]:
    """Reset branding back to defaults."""
    stmt = select(Chat_branding).order_by(Chat_branding.id.asc()).limit(1)
    result = await db.execute(stmt)
    row: Optional[Chat_branding] = result.scalar_one_or_none()

    if row is None:
        row = Chat_branding(**DEFAULT_BRANDING)
        db.add(row)
    else:
        for k, v in DEFAULT_BRANDING.items():
            setattr(row, k, v)
    await db.commit()
    await db.refresh(row)

    return await get_active_branding(db)