"""Mira widget embed helper for Python — standard library only.

`widget_snippet()` returns a safe HTML string that can be inserted into Jinja
templates with `|safe` (or wrapped in `markupsafe.Markup`). Every value is
escaped for its context: HTML attributes via html.escape(), inline JavaScript
via JSON encoding with `<`, `>`, `&` and Unicode line separators escaped.
"""

from __future__ import annotations

import html
import json
from typing import Any, Mapping, Optional

DEFAULT_API_URL = "https://api.mira.app"

# Prevent </script> break-outs and JS line-terminator issues in inline scripts.
_JS_ESCAPES = {
    "<": r"\u003c",
    ">": r"\u003e",
    "&": r"\u0026",
    "\u2028": r"\u2028",
    "\u2029": r"\u2029",
}


def script_url(api_url: str = DEFAULT_API_URL) -> str:
    """Return the public widget bundle URL for a Mira API base."""
    return api_url.rstrip("/") + "/mira-widget.js"


def _js(value: Any) -> str:
    """JSON-encode a value for placement inside an inline <script> block."""
    text = json.dumps(value, ensure_ascii=False, separators=(",", ":"))
    for char, escaped in _JS_ESCAPES.items():
        text = text.replace(char, escaped)
    return text


def _attr(value: Any) -> str:
    """Escape a value for a double-quoted HTML attribute."""
    if isinstance(value, bool):
        value = "true" if value else "false"
    return html.escape(str(value), quote=True)


def widget_snippet(
    tenant_id: str,
    api_url: str = DEFAULT_API_URL,
    customer_id: Optional[str] = None,
    config: Optional[Mapping[str, Any]] = None,
) -> str:
    """Build the Mira embed snippet (globals + script + <noscript> fallback).

    Args:
        tenant_id: Public tenant id from the Mira dashboard (required).
        api_url: Mira API base URL, with or without a trailing slash.
        customer_id: Opaque logged-in customer id; omit for anonymous shoppers.
        config: Optional appearance/behaviour overrides (position, primaryColor,
            avatar, autoMinimize, voice, name, greeting, currency, ...).

    Returns:
        HTML safe to inject into a page. Returns an HTML comment if tenant_id
        is empty, so a misconfiguration cannot emit a half-initialised widget.
    """
    tenant_id = (tenant_id or "").strip()
    if not tenant_id:
        return "<!-- Mira: a tenant id is required -->"

    api_base = api_url.rstrip("/") or DEFAULT_API_URL
    cfg: dict[str, Any] = {
        "tenantId": tenant_id,
        "apiBase": api_base,
        "storeUrl": "",
        "customerId": customer_id or "",
        "name": "Mira",
        "avatar": "🤖",
        "primaryColor": "#7C5CFC",
        "position": "bottom-right",
        "autoMinimize": True,
        "requireConsent": True,
        "currency": "USD",
        "voice": False,
    }
    if config:
        cfg.update(config)

    bootstrap = (
        "window.MIRA_TENANT_ID={tenant};"
        "window.MIRA_API_URL={api};"
        "window.MIRA_STORE_URL={store};"
        "window.MIRA_CUSTOMER_ID={customer};"
        "window.MIRA_CONFIG={cfg};"
    ).format(
        tenant=_js(str(cfg["tenantId"])),
        api=_js(str(cfg["apiBase"])),
        store=_js(str(cfg.get("storeUrl") or "")),
        customer=_js(str(cfg.get("customerId") or "")),
        cfg=_js(cfg),
    )

    # data-* attributes mirror MIRA_CONFIG so older widget builds also apply
    # the requested branding without waiting for remote config.
    attributes = {
        "data-tenant": str(cfg["tenantId"]),
        "data-api": str(cfg["apiBase"]),
        "data-customer-id": str(cfg.get("customerId") or ""),
        "data-position": str(cfg.get("position") or "bottom-right"),
        "data-color": str(cfg.get("primaryColor") or "#7C5CFC"),
        "data-avatar": str(cfg.get("avatar") or "🤖"),
        "data-auto-minimize": _attr(cfg.get("autoMinimize", True)),
    }
    attrs = "".join(f' {name}="{_attr(value)}"' for name, value in attributes.items())

    from urllib.parse import quote

    fallback = _attr(
        str(cfg["apiBase"]).rstrip("/")
        + "/widget/fallback?tenant_id="
        + quote(str(cfg["tenantId"]), safe="")
    )

    return (
        f"<script>{bootstrap}</script>\n"
        f'<script async src="{_attr(script_url(str(cfg["apiBase"])))}"{attrs}></script>\n'
        f'<noscript><a href="{fallback}" rel="noopener noreferrer">Ask Mira</a></noscript>'
    )


# Friendly alias used by some integrations.
mira_widget_snippet = widget_snippet
