"""Minimal Flask storefront with the Mira widget.

Run from this folder:

    pip install flask
    MIRA_TENANT_ID=YOUR_TENANT_ID MIRA_API_URL=https://api.mira.app python flask_example.py

Uses only the standard library plus Flask. Replace `current_customer_id()` with
your real session/auth lookup before deploying.
"""

from __future__ import annotations

import os

from flask import Flask, render_template_string
from markupsafe import Markup

from mira_widget import widget_snippet

app = Flask(__name__)

TENANT_ID = os.environ.get("MIRA_TENANT_ID", "YOUR_TENANT_ID")
API_URL = os.environ.get("MIRA_API_URL", "https://api.mira.app")

PRODUCT = {
    "id": "sku-1001",
    "title": "Aurora Wireless Headphones",
    "price": 249.0,
    "image": "https://placehold.co/600x600/png?text=Aurora",
    "url": "/products/sku-1001",
}


def current_customer_id() -> str | None:
    """Return an opaque id for the logged-in shopper, or None for a guest.

    In a real app: `return session.get("user_id")` (Flask login/session) or the
    equivalent from your auth provider. Never return an email or a token.
    """
    return "cus_demo_123"


PAGE = """\
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>{{ product.title }} — Demo Store</title>
  <style>body{font:16px system-ui,sans-serif;max-width:720px;margin:3rem auto;padding:0 1rem}
  img{width:240px;height:auto;border-radius:12px}button{padding:.6rem 1rem;cursor:pointer}</style>
</head>
<body>
  <h1>{{ product.title }}</h1>
  <img src="{{ product.image }}" alt="{{ product.title }}">
  <p><strong>${{ '%.2f'|format(product.price) }}</strong></p>
  <p><a href="{{ product.url }}">Product details</a></p>

  {# widget_snippet() already escapes its values; Markup marks it trusted. #}
  {{ widget }}

  <script>
    // Optional: open the chat programmatically.
    function askMira() { window.dispatchEvent(new Event("mira:open")); }
  </script>
  <button onclick="askMira()">Ask Mira about this product</button>
</body>
</html>
"""


@app.get("/")
def index() -> str:
    widget = widget_snippet(
        TENANT_ID,
        API_URL,
        customer_id=current_customer_id(),
        config={
            "position": "bottom-right",
            "primaryColor": "#7C5CFC",
            "avatar": "🤖",
            "autoMinimize": True,
            "voice": False,
            "storeUrl": "http://localhost:5000",
        },
    )
    return render_template_string(PAGE, product=PRODUCT, widget=Markup(widget))


@app.get("/products/<product_id>")
def product_page(product_id: str) -> str:
    return f"<h1>Product {product_id}</h1><p>Demo product page.</p>"


if __name__ == "__main__":
    app.run(debug=True)
