"""
Widget Init API — /widget/init
Minimal public endpoint. No auth required — domain must be active.
"""
import logging
from fastapi import APIRouter, HTTPException, status, Request, Header
from database.firebase_client import get_firestore

logger = logging.getLogger("chatbot.routers.widget")
router = APIRouter(prefix="/widget", tags=["Widget API"])


@router.get("/config")
async def widget_config(request: Request, x_api_key: str = Header(..., alias="X-API-Key")):
    """Returns config JSON for the embeddable chat widget."""
    domain_id = x_api_key
    db = get_firestore()
    try:
        snap = db.collection("domains").document(domain_id).get()
        if not snap.exists:
            raise HTTPException(status_code=404, detail="Widget domain not found.")
        data = snap.to_dict()
        if not data.get("is_active", True):
            raise HTTPException(status_code=403, detail="This chatbot has been disabled.")

        scheme = "wss" if request.url.scheme == "https" else "ws"
        host = request.headers.get("host", request.url.netloc)
        ws_url = f"{scheme}://{host}/ws/chat"

        http_scheme = "https" if request.url.scheme == "https" else "http"
        base_url = f"{http_scheme}://{host}"
        logo_url = data.get("widget_logo_url") or "/static/chatbot-logo.png"
        if logo_url.startswith("/static/"):
            logo_url = f"{base_url}{logo_url}"

        return {
            "domain_id": domain_id,
            "ws_url": ws_url,
            "widget_config": {
                "title": data.get("widget_title", "Support Chat"),
                "placeholder": data.get("widget_placeholder", "Type your question..."),
                "theme_color": data.get("widget_theme_color", "#7C3AED"),
                "domain_name": data.get("name", ""),
                "welcome_message": data.get("widget_welcome_message") or data.get("welcome_message") or "Welcome to Acme Support.",
                "fallback_message": data.get("fallback_message", "Sorry, we could not find an answer. Please contact support."),
                "helpline_number": data.get("helpline_number", ""),
                "logo_url": logo_url,
            },
        }
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Widget init error for {domain_id}: {e}")
        raise HTTPException(status_code=500, detail="Widget configuration unavailable.")


from pydantic import BaseModel
from typing import Optional, Dict
from datetime import datetime
import uuid

class LeadCapture(BaseModel):
    session_id: str
    name: str
    email: str
    phone: str
    utm: Optional[Dict[str, str]] = None

@router.post("/lead")
async def capture_lead(lead: LeadCapture, x_api_key: str = Header(..., alias="X-API-Key")):
    domain_id = x_api_key
    db = get_firestore()
    
    lead_id = str(uuid.uuid4())
    doc = {
        "id": lead_id,
        "domain_id": domain_id,
        "session_id": lead.session_id,
        "name": lead.name,
        "email": lead.email,
        "phone": lead.phone,
        "utm": lead.utm or {},
        "created_at": datetime.utcnow().isoformat()
    }
    
    db.collection("leads").document(lead_id).set(doc)
    return {"status": "success", "lead_id": lead_id}
