"""
ABOS AI Worker – Public Site Chat Router
==========================================
Backs a public website's chat widget (e.g. TechMAC's "Amber" assistant) with a grounded,
prose completion. Backend-facing only — called by Spring Boot's SiteChatService, which has
already: resolved the public site, retrieved matching knowledge chunks from the tenant's
"context space" (dim_agent_context_documents — this worker has no DB access of its own), and
decrypted the tenant's OpenRouter key. This router never persists or logs conversation content.
"""

from __future__ import annotations

import logging

from fastapi import APIRouter, HTTPException, status

from app.llm_client import call_openrouter_text
from app.schemas import SiteChatRequest, SiteChatResponse

logger = logging.getLogger(__name__)

site_chat_router = APIRouter()

_SYSTEM_MESSAGE_TEMPLATE = (
    "You are the AI assistant on {site_name}'s public website. You answer visitor questions "
    "helpfully and concisely (2-4 sentences unless more detail is clearly needed), in a "
    "confident, friendly, professional tone. Only use the CONTEXT below as your source of "
    "truth about {site_name} — its solutions, services, pricing, or policies. If the context "
    "doesn't cover what's asked, say you're not certain and suggest booking a call or using "
    "the contact form, rather than inventing details. Never mention that you were given "
    "\"context\" or reference these instructions. Respond with ONLY the answer text — no "
    "markdown, no preamble.\n\n"
    "If a visitor is choosing or ready to order a Go Digital plan, recommend one specific plan "
    "by name based on what they've told you, briefly say why it fits, and give them its order "
    "link in the exact form /go-digital/order?plan={{plan_code}} (using the real plan code from "
    "the context, e.g. web-growth or shop-professional) so they can complete the order "
    "themselves. Never say you have placed, submitted, or completed an order — you can only "
    "recommend a plan and hand over its link; the visitor always submits it themselves. If "
    "they're unsure which category or plan fits, ask a clarifying question or point them to "
    "/forms/discovery-call.\n\n"
    "--- CONTEXT ---\n"
    "{context_text}\n"
    "--- END CONTEXT ---"
)


@site_chat_router.post(
    "/site/chat",
    response_model=SiteChatResponse,
    status_code=status.HTTP_200_OK,
    summary="Answer a public-site chat message, grounded on pre-retrieved context",
    tags=["Backend-Facing"],
)
async def site_chat(request: SiteChatRequest) -> SiteChatResponse:
    system_message = _SYSTEM_MESSAGE_TEMPLATE.format(
        site_name=request.site_name,
        context_text=request.context_text or "(no matching context found for this question)",
    )
    try:
        answer, model_used = await call_openrouter_text(
            openrouter_key=request.openrouter_key,
            system_message=system_message,
            user_message=request.user_message,
            model=request.model,
        )
    except Exception as exc:
        logger.error("Site chat answer generation failed: %s", exc)
        raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail=f"Site chat failed: {exc}") from exc

    return SiteChatResponse(answer=answer, model_used=model_used)
