"""API pública para el bot de IA (n8n + LLM).

Diseñada para que un agente conversacional consulte el catálogo de ChevroCaracas
en tiempo real: buscar productos, ver disponibilidad, precios, especificaciones,
iPhones disponibles, info de la tienda, métodos de pago, etc.

Autenticación: header `X-API-Key` con la clave configurada en
`SystemConfig['bot_api_key']`. Se rota desde el admin → Config → Bot.

Diseñada con dos premisas:
  - JSON descriptivo (claves en español + campos calculados) para que el LLM
    no necesite hacer joins ni transformar datos.
  - Solo datos públicos: nunca expone costos, márgenes, ni datos internos
    de inventario por sede.

Endpoints (prefijo `/api/v1/bot`):
  GET  /products/search?q=...&limit=10     — Buscador semántico-friendly
  GET  /products/<slug-or-id>              — Detalle completo de un producto
  GET  /products/featured                  — Productos destacados de la home
  GET  /iphones                            — iPhones usados disponibles
  GET  /stock-check?sku=...                — Disponibilidad rápida por SKU
  GET  /store-info                         — Info de la tienda (pagos, contacto)
  GET  /payment-methods                    — Métodos de pago activos
  GET  /brands                             — Lista de marcas
  GET  /categories                         — Lista de categorías
  GET  /ping                               — Health check con la clave
"""
from __future__ import annotations

import secrets
from decimal import Decimal
from functools import wraps

from flask import Blueprint, current_app, jsonify, request
from sqlalchemy import or_

from datetime import datetime, timezone

from sqlalchemy import text as _sql

from ..extensions import db
from ..models import (
    AccountReceivable,
    BotConversation,
    BotStage,
    Brand,
    Category,
    Customer,
    ItemStatus,
    LeadStatus,
    PaymentMethod,
    PaymentStatus,
    Product,
    ProductItem,
    ProductKind,
    ReceivableStatus,
    Sale,
    SaleChannel,
    SaleItem,
    SaleStatus,
    SalesLead,
    SystemConfig,
)
import json as _json

bot_bp = Blueprint("bot", __name__)


# ============================================================
# Auth por API key
# ============================================================

BOT_API_KEY_CONFIG = "bot_api_key"


def _get_or_create_api_key() -> str:
    """Devuelve la clave actual; si no existe, genera y guarda una nueva."""
    key = SystemConfig.get(BOT_API_KEY_CONFIG)
    if key:
        return key
    # Primera vez: la creamos y la persistimos.
    new_key = secrets.token_urlsafe(32)
    SystemConfig.set(
        BOT_API_KEY_CONFIG, new_key,
        description="Clave de API para el bot de IA (n8n).",
    )
    db.session.commit()
    return new_key


def require_bot_api_key(fn):
    @wraps(fn)
    def _wrapped(*args, **kwargs):
        provided = request.headers.get("X-API-Key", "").strip()
        if not provided:
            # Permitimos también el query param `?api_key=` para pruebas rápidas.
            provided = request.args.get("api_key", "").strip()
        if not provided:
            return jsonify(error="missing X-API-Key header"), 401
        expected = SystemConfig.get(BOT_API_KEY_CONFIG)
        if not expected or not secrets.compare_digest(provided, expected):
            return jsonify(error="invalid api key"), 401
        return fn(*args, **kwargs)
    return _wrapped


# ============================================================
# Serializadores (JSON descriptivo en español)
# ============================================================


def _product_summary(p: Product) -> dict:
    """Resumen liviano para listados de búsqueda."""
    return {
        "id": p.id,
        "sku": p.sku,
        "slug": p.slug,
        "nombre": p.name,
        "modelo": p.model,
        "marca": p.brand.name if p.brand else None,
        "categoria": p.category.name if p.category else None,
        "precio_usd": float(p.price),
        "stock_disponible": int(p.stock_available),
        "imagen": p.image_url,
        "es_iphone": bool(p.is_iphone),
        "es_combo": p.is_combo,
        "url_publica": f"/product/{p.slug}",
    }


def _product_full(p: Product) -> dict:
    """Detalle completo del producto: incluye descripción + componentes si es combo."""
    out = _product_summary(p)
    out["descripcion"] = p.description or ""
    if p.is_combo:
        out["componentes"] = [
            {
                "producto": c.component_product.name if c.component_product else None,
                "sku": c.component_product.sku if c.component_product else None,
                "cantidad": c.quantity,
            }
            for c in (p.combo_components or [])
        ]
        out["subtotal_componentes_usd"] = float(p.components_subtotal)
    return out


def _iphone_unit(item: ProductItem) -> dict:
    """Cada iPhone es una unidad serializada con color, batería, etc."""
    return {
        "id": item.id,
        "producto": item.product.name if item.product else None,
        "modelo": item.product.model if item.product else None,
        "color": getattr(item, "color", None),
        "bateria_pct": getattr(item, "battery_pct", None),
        "almacenamiento": getattr(item, "storage", None),
        "serial": item.serial,
        "imei": item.imei if hasattr(item, "imei") else None,
        "precio_usd": float(item.effective_price or 0),
        "imagen": item.product.image_url if item.product else None,
        "url_publica": f"/product/{item.product.slug}" if item.product else None,
    }


# ============================================================
# Endpoints
# ============================================================


@bot_bp.get("/ping")
@require_bot_api_key
def ping():
    """Health check con la clave: el bot lo usa para validar conexión."""
    return jsonify(ok=True, service="chevrocaracas-bot-api", version="1.0")


_SPANISH_STOPWORDS = frozenset({
    # Fillers que vienen en las preguntas del bot pero no son del producto
    "a", "al", "algo", "ah", "ahi", "ahí", "ay", "buenas", "bueno", "buenos",
    "cual", "cuáles", "cuales", "cuanto", "cuánto", "cuanta", "cuanta", "cuantas", "cuántos",
    "cuesta", "cuestan", "como", "cómo", "con", "cuando", "cuándo", "de", "del",
    "dame", "decime", "decir", "desde", "donde", "dónde", "el", "la", "los", "las",
    "en", "es", "eso", "este", "esta", "estos", "estas", "esos", "esas",
    "ganas", "gracias", "hay", "hola", "hace", "ha", "ir", "le", "les",
    "lo", "mas", "más", "me", "mi", "mis", "muy", "no", "nos", "o", "ok",
    "para", "pero", "poco", "por", "porque", "porqué", "que", "qué", "quiero",
    "quisiera", "queria", "quería", "quien", "quién", "si", "sí", "sin", "solo", "sólo",
    "su", "sus", "tan", "tanto", "te", "tienen", "tienes", "tiene", "tene", "tenes",
    "tene", "ti", "tu", "tus", "un", "una", "uno", "unos", "unas", "venta", "ver",
    "vez", "y", "ya", "yo", "uds", "ustedes", "usted",
    # Frases comunes pre-acción
    "tengo", "tener", "necesito", "necesitar", "mostrame", "muestrame", "muéstrame",
    "envíame", "enviame", "info", "informacion", "información", "precio", "precios",
    "stock", "disponible", "disponibilidad", "comprar", "compra", "comprando",
    "agregar", "agregame", "agréguelo", "agregue", "carrito", "carritos",
    "buscar", "busco", "buscando", "encontrar", "encontre", "encontré",
    "favor", "amigo", "amiga", "vale", "okay",
})


def _singularize(token: str) -> str:
    """Quita el plural simple en español para que 'iphones' matchee 'iPhone'."""
    if len(token) <= 4:
        return token
    if token.endswith("es"):
        return token[:-2]
    if token.endswith("s"):
        return token[:-1]
    return token


def _tokenize_search(q_text: str) -> list[str]:
    """Convierte la frase del cliente en tokens útiles para buscar.

    - Pasa a minúsculas y saca puntuación.
    - Saca palabras vacías comunes (artículos, preguntas, fillers).
    - Singulariza para que 'iphones' busque 'iphone'.
    - Mantiene números importantes ('13', '256gb').
    """
    import re
    text = re.sub(r"[^\w\sáéíóúñü]", " ", q_text.lower(), flags=re.UNICODE)
    raw = [t.strip() for t in text.split() if t.strip()]
    clean = [_singularize(t) for t in raw if t not in _SPANISH_STOPWORDS and len(t) >= 2]
    return clean or [_singularize(t) for t in raw]


@bot_bp.get("/products/search")
@require_bot_api_key
def search_products():
    """Buscador de productos tolerante a frases naturales del bot.

    - Tokeniza la query y exige que cada palabra clave esté presente en
      algún campo (name / sku / model / description / brand / category).
    - Si el AND no encuentra nada, hace un segundo intento con OR (fuzzy).

    Query params:
        q             : texto libre (frase natural del cliente)
        marca         : filtrar por marca (slug o nombre)
        categoria     : filtrar por categoría
        solo_en_stock : 'true' para excluir sin stock (default true)
        limit         : 1-50 (default 10)
    """
    q_text = (request.args.get("q") or "").strip()
    marca = (request.args.get("marca") or "").strip()
    categoria = (request.args.get("categoria") or "").strip()
    solo_stock = (request.args.get("solo_en_stock") or "true").lower() in ("true", "1", "yes")
    try:
        limit = min(max(int(request.args.get("limit", 10)), 1), 50)
    except ValueError:
        limit = 10

    def _base_query():
        return (
            Product.query.filter(Product.is_active == True)  # noqa: E712
            .outerjoin(Brand, Brand.id == Product.brand_id)
            .outerjoin(Category, Category.id == Product.category_id)
        )

    tokens = _tokenize_search(q_text) if q_text else []
    rows: list[Product] = []

    if tokens:
        # 1) Modo estricto: AND de tokens. Todos deben aparecer en algún campo.
        query = _base_query()
        for tok in tokens:
            like = f"%{tok}%"
            query = query.filter(or_(
                Product.name.ilike(like),
                Product.sku.ilike(like),
                Product.model.ilike(like),
                Product.description.ilike(like),
                Brand.name.ilike(like),
                Category.name.ilike(like),
            ))
        if marca:
            query = query.filter(or_(Brand.slug == marca, Brand.name.ilike(f"%{marca}%")))
        if categoria:
            query = query.filter(or_(Category.slug == categoria, Category.name.ilike(f"%{categoria}%")))
        rows = query.order_by(Product.name).limit(limit * 3).all()

        # 2) Fallback fuzzy: si AND no devuelve nada, OR de tokens.
        if not rows:
            query = _base_query()
            ors = []
            for tok in tokens:
                like = f"%{tok}%"
                ors.extend([
                    Product.name.ilike(like),
                    Product.sku.ilike(like),
                    Product.model.ilike(like),
                    Product.description.ilike(like),
                    Brand.name.ilike(like),
                    Category.name.ilike(like),
                ])
            if ors:
                query = query.filter(or_(*ors))
            if marca:
                query = query.filter(or_(Brand.slug == marca, Brand.name.ilike(f"%{marca}%")))
            if categoria:
                query = query.filter(or_(Category.slug == categoria, Category.name.ilike(f"%{categoria}%")))
            rows = query.order_by(Product.name).limit(limit * 3).all()
    else:
        # Sin texto: devolver los más nuevos (con filtros de marca/categoria si vienen)
        query = _base_query()
        if marca:
            query = query.filter(or_(Brand.slug == marca, Brand.name.ilike(f"%{marca}%")))
        if categoria:
            query = query.filter(or_(Category.slug == categoria, Category.name.ilike(f"%{categoria}%")))
        rows = query.order_by(Product.created_at.desc()).limit(limit * 3).all()
    items = [_product_summary(p) for p in rows]
    if solo_stock:
        items = [it for it in items if it["stock_disponible"] > 0]
    items = items[:limit]
    return jsonify(
        total=len(items),
        consulta={"q": q_text, "marca": marca, "categoria": categoria, "solo_en_stock": solo_stock, "limit": limit},
        productos=items,
    )


@bot_bp.get("/products/<identifier>")
@require_bot_api_key
def get_product(identifier):
    """Detalle por slug, SKU o id numérico."""
    p = None
    if identifier.isdigit():
        p = db.session.get(Product, int(identifier))
    if p is None:
        p = Product.query.filter(or_(Product.slug == identifier, Product.sku == identifier)).first()
    if p is None or not p.is_active:
        return jsonify(error="producto no encontrado"), 404
    return jsonify(_product_full(p))


@bot_bp.get("/products/featured")
@require_bot_api_key
def featured_products():
    """Top de productos: combos + más recientes con stock."""
    rows = (
        Product.query.filter(Product.is_active == True)  # noqa: E712
        .order_by(Product.kind.desc(), Product.created_at.desc())
        .limit(40).all()
    )
    items = [_product_summary(p) for p in rows]
    items = [it for it in items if it["stock_disponible"] > 0][:12]
    return jsonify(total=len(items), productos=items)


@bot_bp.get("/iphones")
@require_bot_api_key
def list_iphones():
    """iPhones disponibles, unidad por unidad (con color, batería, serial)."""
    # Filtramos productos marcados is_iphone y traemos sus unidades AVAILABLE.
    items_q = (
        db.session.query(ProductItem)
        .join(Product, Product.id == ProductItem.product_id)
        .filter(
            Product.is_iphone == True,  # noqa: E712
            Product.is_active == True,  # noqa: E712
            ProductItem.status == ItemStatus.AVAILABLE,
        )
        .order_by(Product.name, ProductItem.id)
    )
    rows = items_q.limit(100).all()
    items = [_iphone_unit(r) for r in rows]
    return jsonify(total=len(items), iphones=items)


@bot_bp.get("/stock-check")
@require_bot_api_key
def stock_check():
    """Consulta rápida de disponibilidad por SKU o slug."""
    code = (request.args.get("sku") or request.args.get("slug") or "").strip()
    if not code:
        return jsonify(error="parámetro sku o slug requerido"), 400
    p = Product.query.filter(or_(Product.sku == code, Product.slug == code)).first()
    if not p or not p.is_active:
        return jsonify(disponible=False, encontrado=False, mensaje="producto no encontrado"), 404
    stock = int(p.stock_available)
    return jsonify(
        encontrado=True,
        disponible=stock > 0,
        stock=stock,
        producto={"id": p.id, "sku": p.sku, "nombre": p.name, "precio_usd": float(p.price)},
    )


@bot_bp.get("/store-info")
@require_bot_api_key
def store_info():
    """Información general de la tienda para que el bot la cite al cliente."""
    return jsonify(
        nombre="ChevroCaracas",
        sitio_web="https://chevrocaracas.com",
        whatsapp="+58 412 275 9423",
        whatsapp_link="https://wa.me/584122759423",
        descripcion=(
            "Tienda de tecnología en Venezuela. Vendemos productos nuevos y "
            "iPhones usados con garantía variable por producto. Despachamos "
            "a todo el país y atendemos desde nuestras sedes físicas."
        ),
        garantia=(
            "El tiempo de garantía es variable según el producto. "
            "Consultá con atención al cliente antes de comprar para conocer "
            "la garantía específica de cada equipo."
        ),
        moneda_principal="USD",
        moneda_secundaria="VES (Bolívares)",
        pagos_disponibles=(
            "USD en efectivo o transferencia, Bs por Pago Móvil o transferencia, "
            "y Cashea (crédito al consumo con inicial 20-50% y cuotas cada 15 días)."
        ),
    )


@bot_bp.get("/payment-methods")
@require_bot_api_key
def payment_methods():
    """Métodos de pago activos. Excluye los is_public=false (POS-only)."""
    rows = PaymentMethod.query.filter(
        PaymentMethod.is_active == True,  # noqa: E712
        PaymentMethod.is_public == True,  # noqa: E712
    ).order_by(PaymentMethod.name).all()
    items = [
        {
            "id": m.id,
            "nombre": m.name,
            "moneda": m.currency.code if m.currency else "USD",
            "ajuste_pct": float(m.adjustment_percent or 0),
            "tipo_ajuste": (
                "recargo" if (m.adjustment_percent or Decimal("0")) > 0
                else ("descuento" if (m.adjustment_percent or Decimal("0")) < 0 else "ninguno")
            ),
        }
        for m in rows
    ]
    return jsonify(total=len(items), metodos=items)


@bot_bp.get("/brands")
@require_bot_api_key
def brands():
    rows = Brand.query.order_by(Brand.name).all()
    return jsonify([{"id": b.id, "slug": b.slug, "nombre": b.name} for b in rows])


@bot_bp.get("/categories")
@require_bot_api_key
def categories():
    rows = Category.query.order_by(Category.name).all()
    return jsonify([{"id": c.id, "slug": c.slug, "nombre": c.name} for c in rows])


# ============================================================
# Leads: registro de interés del cliente cuando el bot detecta
# intención de compra → handoff al vendedor humano.
# ============================================================


@bot_bp.post("/leads")
@require_bot_api_key
def create_lead():
    """Crea un lead nuevo o actualiza el último abierto del mismo teléfono.

    Body (JSON):
        phone            : string requerido, formato internacional sin '+'
        customer_name    : string opcional
        last_message     : string opcional — qué dijo el cliente
        summary          : string opcional — resumen breve para el vendedor
        products_interest: array opcional — [{sku, nombre, qty}]
    """
    body = request.get_json(silent=True) or {}
    phone = (body.get("phone") or "").strip().replace("+", "").replace(" ", "")
    if not phone:
        return jsonify(error="phone es requerido"), 400

    # Si ya hay un lead abierto del mismo número, lo actualizamos en lugar
    # de duplicar. Así una conversación = un lead.
    existing = (
        SalesLead.query.filter(SalesLead.phone == phone)
        .filter(SalesLead.status.in_([LeadStatus.NEW, LeadStatus.CONTACTED]))
        .order_by(SalesLead.created_at.desc())
        .first()
    )

    customer_name = (body.get("customer_name") or "").strip() or None
    last_message = (body.get("last_message") or "").strip() or None
    summary = (body.get("summary") or "").strip() or None
    products = body.get("products_interest") or None

    if existing:
        # Update — preservamos lo viejo si lo nuevo viene vacío.
        if customer_name and not existing.customer_name:
            existing.customer_name = customer_name
        if last_message:
            existing.last_message = last_message
        if summary:
            existing.summary = summary
        if products:
            existing.products_interest = products
        existing.updated_at = datetime.now(timezone.utc)
        lead = existing
        created = False
    else:
        lead = SalesLead(
            phone=phone,
            customer_name=customer_name,
            last_message=last_message,
            summary=summary,
            products_interest=products,
            status=LeadStatus.NEW,
        )
        db.session.add(lead)
        created = True

    db.session.commit()
    return jsonify(
        id=lead.id,
        phone=lead.phone,
        status=lead.status.value if hasattr(lead.status, "value") else lead.status,
        created=created,
        url_admin=f"/admin/leads/{lead.id}",
    ), 201 if created else 200


# ============================================================
# Mensajes del bot (historial). El bot guarda cada mensaje user/assistant
# vía POST y consulta el historial reciente para alimentar al clasificador
# del LLM con contexto. n8n no toca la BD directo — todo pasa por API.
# ============================================================


def _normalize_phone(raw: str) -> str:
    """Limpia un número: saca '+', espacios, guiones, paréntesis."""
    if not raw:
        return ""
    return (
        raw.strip()
        .replace("+", "")
        .replace(" ", "")
        .replace("-", "")
        .replace("(", "")
        .replace(")", "")
    )


@bot_bp.post("/messages")
@require_bot_api_key
def log_bot_message():
    """Guarda un mensaje del chat (user o assistant) en bot_messages.

    Body JSON:
        role             : 'user' o 'assistant'
        user_number      : teléfono internacional sin '+' (requerido)
        user_name        : nombre del cliente (opcional)
        type_message     : 'text' / 'audio' / 'image' (default text)
        message          : texto del mensaje
        audio_transcription : transcripción si fue audio
        img_url          : url si fue imagen
        intent           : intent clasificado (assistant)
        timestamp        : unix timestamp (string)
    """
    body = request.get_json(silent=True) or {}
    role = (body.get("role") or "").strip().lower()
    if role not in ("user", "assistant"):
        return jsonify(error="role debe ser 'user' o 'assistant'"), 400
    user_number = _normalize_phone(body.get("user_number") or "")
    if not user_number:
        return jsonify(error="user_number requerido"), 400

    db.session.execute(_sql(
        "INSERT INTO bot_messages "
        "(role, user_name, user_number, type_message, message, "
        " audio_transcription, img_url, intent, timestamp) "
        "VALUES (:role, :user_name, :user_number, :type_message, :message, "
        " :audio_transcription, :img_url, :intent, :timestamp)"
    ), {
        "role": role,
        "user_name": body.get("user_name") or None,
        "user_number": user_number,
        "type_message": (body.get("type_message") or "text").lower(),
        "message": body.get("message") or "",
        "audio_transcription": body.get("audio_transcription") or None,
        "img_url": body.get("img_url") or None,
        "intent": body.get("intent") or None,
        "timestamp": body.get("timestamp") or None,
    })
    db.session.commit()
    return jsonify(ok=True), 201


@bot_bp.get("/messages/history")
@require_bot_api_key
def get_bot_history():
    """Últimos N mensajes de una conversación, ya formateados para pegar
    al prompt del clasificador.

    Query params:
        wa_id : teléfono internacional sin '+' (requerido)
        limit : 1-50, default 10
    """
    wa_id = _normalize_phone(request.args.get("wa_id") or "")
    if not wa_id:
        return jsonify(error="wa_id requerido"), 400
    try:
        limit = min(max(int(request.args.get("limit", 10)), 1), 50)
    except ValueError:
        limit = 10

    rows = db.session.execute(_sql(
        "SELECT role, user_name, message, created_at "
        "FROM bot_messages "
        "WHERE user_number = :wa_id "
        "ORDER BY id DESC LIMIT :limit"
    ), {"wa_id": wa_id, "limit": limit}).fetchall()

    items = list(reversed([
        {
            "role": r.role,
            "direction": "inbound" if r.role == "user" else "outbound",
            "user_name": r.user_name,
            "message": r.message or "",
            "created_at": r.created_at.isoformat() if r.created_at else None,
        }
        for r in rows
    ]))

    if not items:
        conversation_text = "CONVERSACION NUEVA"
    else:
        conversation_text = "\n".join(
            f"{'Cliente' if it['direction'] == 'inbound' else 'Bot'}: {it['message']}"
            for it in items if it["message"]
        ) or "CONVERSACION NUEVA"

    return jsonify(
        wa_id=wa_id,
        total=len(items),
        is_new=len(items) == 0,
        conversation_history=conversation_text,
        items=items,
    )


# ============================================================
# Conversación activa: carrito + datos del cliente + state machine.
# El bot consulta el state antes de clasificar y actualiza acciones
# (agregar al carrito, capturar nombre/dirección, confirmar pedido).
# ============================================================


def _dump_conversation(conv: BotConversation) -> dict:
    """Serializa la conversación en formato amigable para el bot."""
    cart = conv.cart_items or []
    cd = conv.customer_data or {}
    from decimal import Decimal as _D
    cart_total = sum(
        (_D(str(it.get("line_total", "0"))) for it in cart),
        _D("0"),
    )
    return {
        "phone": conv.phone,
        "customer_name": conv.customer_name,
        "stage": conv.stage.value if hasattr(conv.stage, "value") else conv.stage,
        "cart_items": cart,
        "cart_count": sum(int(it.get("qty", 0)) for it in cart),
        "cart_total": str(cart_total.quantize(_D("0.01"))),
        "customer_data": cd,
        "sale_id": conv.sale_id,
        "is_data_complete": all([
            cd.get("name"),
            cd.get("document"),
            cd.get("address"),
        ]),
        "last_active_at": conv.last_active_at.isoformat() if conv.last_active_at else None,
    }


def _get_or_create_conv(phone: str, customer_name: str | None = None) -> BotConversation:
    """Busca la conversación por teléfono o crea una nueva en BROWSING."""
    phone = _normalize_phone(phone)
    conv = BotConversation.query.filter_by(phone=phone).first()
    if conv is None:
        conv = BotConversation(
            phone=phone,
            customer_name=customer_name or None,
            stage=BotStage.BROWSING,
            cart_items=[],
            customer_data={},
        )
        db.session.add(conv)
        db.session.flush()
    else:
        # Si el cliente ya tiene una conversación COMPLETED y vuelve a
        # escribir, reiniciamos a BROWSING para una nueva compra.
        if conv.stage == BotStage.COMPLETED:
            conv.stage = BotStage.BROWSING
            conv.cart_items = []
            conv.customer_data = {}
            conv.sale_id = None
        if customer_name and not conv.customer_name:
            conv.customer_name = customer_name
    conv.last_active_at = datetime.now(timezone.utc)
    return conv


@bot_bp.get("/conversation/<phone>")
@require_bot_api_key
def get_conversation(phone):
    """Estado actual de la conversación. Si no existe la crea."""
    name = request.args.get("customer_name") or None
    conv = _get_or_create_conv(phone, name)
    db.session.commit()
    return jsonify(_dump_conversation(conv))


@bot_bp.post("/conversation/<phone>/cart")
@require_bot_api_key
def update_cart(phone):
    """Agrega o quita un producto del carrito.

    Body JSON:
        action  : 'add' | 'remove' | 'clear'
        sku     : SKU o slug del producto (para add/remove)
        qty     : cantidad (default 1)
    """
    body = request.get_json(silent=True) or {}
    action = (body.get("action") or "").lower()
    conv = _get_or_create_conv(phone)

    if action == "clear":
        conv.cart_items = []
        if conv.stage == BotStage.CART_OPEN:
            conv.stage = BotStage.BROWSING
        db.session.commit()
        return jsonify(_dump_conversation(conv))

    if action not in ("add", "remove"):
        return jsonify(error="action debe ser add, remove o clear"), 400

    code = (body.get("sku") or "").strip()
    if not code:
        return jsonify(error="sku requerido"), 400
    try:
        qty = max(int(body.get("qty", 1)), 1)
    except (TypeError, ValueError):
        qty = 1

    product = Product.query.filter(
        (Product.sku == code) | (Product.slug == code),
    ).first()
    if not product or not product.is_active:
        return jsonify(error="producto no encontrado"), 404
    if action == "add" and product.stock_available <= 0:
        return jsonify(error="producto sin stock"), 409

    items = list(conv.cart_items or [])
    found_idx = next(
        (i for i, it in enumerate(items) if it.get("sku") == product.sku),
        None,
    )

    if action == "add":
        new_qty_total = qty + (items[found_idx]["qty"] if found_idx is not None else 0)
        if new_qty_total > product.stock_available:
            return jsonify(
                error=f"stock insuficiente (disponible: {product.stock_available})",
            ), 409
        unit_price = float(product.price)
        line = {
            "product_id": product.id,
            "sku": product.sku,
            "name": product.name,
            "qty": qty if found_idx is None else new_qty_total,
            "unit_price": unit_price,
            "line_total": round(unit_price * (qty if found_idx is None else new_qty_total), 2),
        }
        if found_idx is None:
            items.append(line)
        else:
            items[found_idx] = line
        conv.cart_items = items
        if conv.stage == BotStage.BROWSING:
            conv.stage = BotStage.CART_OPEN

    else:  # remove
        if found_idx is None:
            return jsonify(error="el producto no está en el carrito"), 404
        items.pop(found_idx)
        conv.cart_items = items
        if not items and conv.stage == BotStage.CART_OPEN:
            conv.stage = BotStage.BROWSING

    db.session.commit()
    return jsonify(_dump_conversation(conv))


@bot_bp.post("/conversation/<phone>/customer-data")
@require_bot_api_key
def update_customer_data(phone):
    """Guarda un campo de los datos del cliente.

    Body JSON: cualquier subset de:
        name, document, address, payment_method_id, notes
    Devuelve el state — el bot decide a qué stage avanzar.
    """
    body = request.get_json(silent=True) or {}
    conv = _get_or_create_conv(phone)
    cd = dict(conv.customer_data or {})
    for field in ("name", "document", "address", "payment_method_id", "notes"):
        if field in body and body[field] is not None:
            cd[field] = body[field]
    conv.customer_data = cd
    if cd.get("name") and not conv.customer_name:
        conv.customer_name = cd["name"]
    db.session.commit()
    return jsonify(_dump_conversation(conv))


@bot_bp.post("/conversation/<phone>/stage")
@require_bot_api_key
def update_stage(phone):
    """Cambia el stage del flujo.

    Body JSON: { stage: 'browsing'|'cart_open'|'asking_name'|... }
    """
    body = request.get_json(silent=True) or {}
    target = (body.get("stage") or "").lower()
    try:
        new_stage = BotStage(target)
    except ValueError:
        return jsonify(error=f"stage invalido: {target}"), 400
    conv = _get_or_create_conv(phone)
    conv.stage = new_stage
    db.session.commit()
    return jsonify(_dump_conversation(conv))


@bot_bp.post("/conversation/<phone>/cancel")
@require_bot_api_key
def cancel_conversation(phone):
    """Reset completo: vacía carrito y datos, vuelve a BROWSING."""
    conv = _get_or_create_conv(phone)
    conv.cart_items = []
    conv.customer_data = {}
    conv.stage = BotStage.BROWSING
    conv.sale_id = None
    db.session.commit()
    return jsonify(_dump_conversation(conv))


@bot_bp.post("/conversation/<phone>/confirm")
@require_bot_api_key
def confirm_order(phone):
    """Concreta el pedido del bot: crea Sale + AR pendiente en /admin/sales.

    - Find-or-create del Customer por teléfono.
    - Crea Sale con channel=BOT, status=PENDING, payment_status=PENDING.
    - Items snapshotean nombre y precio (sin reservar serial — eso lo
      asigna el vendedor al despachar).
    - Crea AccountReceivable con saldo completo.
    - Actualiza la BotConversation con sale_id y stage=COMPLETED.
    - Actualiza el SalesLead a 'won' si existe.
    """
    conv = _get_or_create_conv(phone)
    cd = conv.customer_data or {}

    # Validaciones de datos requeridos.
    if not conv.cart_items:
        return jsonify(error="el carrito está vacío"), 400
    if not cd.get("name") or not cd.get("document") or not cd.get("address"):
        return jsonify(error="faltan datos del cliente (name/document/address)"), 400

    # Find-or-create del Customer.
    norm_phone = _normalize_phone(conv.phone)
    customer = Customer.query.filter_by(phone=norm_phone).first()
    if customer is None:
        customer = Customer.query.filter_by(document=cd.get("document")).first()
    if customer is None:
        customer = Customer(
            name=cd["name"],
            phone=norm_phone,
            document=cd.get("document") or None,
            address=cd.get("address") or None,
        )
        db.session.add(customer)
        db.session.flush()
    else:
        # Actualiza datos faltantes sin pisar lo existente.
        if not customer.name:
            customer.name = cd["name"]
        if not customer.document and cd.get("document"):
            customer.document = cd["document"]
        if not customer.address and cd.get("address"):
            customer.address = cd["address"]

    from decimal import Decimal as _D

    # Calcular totales desde el carrito.
    subtotal = _D("0.00")
    for it in conv.cart_items:
        subtotal += _D(str(it.get("line_total", "0")))

    pm_id = cd.get("payment_method_id")
    payment_method = None
    if pm_id:
        try:
            payment_method = db.session.get(PaymentMethod, int(pm_id))
        except (TypeError, ValueError):
            payment_method = None

    # Generar número provisional; al flush con id real lo reemplazamos.
    sale = Sale(
        number="BOT-PENDING",
        channel=SaleChannel.BOT,
        status=SaleStatus.PENDING,
        payment_status=PaymentStatus.PENDING,
        customer_id=customer.id,
        payment_method_id=payment_method.id if payment_method else None,
        subtotal=subtotal,
        discount=_D("0.00"),
        surcharge=_D("0.00"),
        total=subtotal,
        currency="USD",
        notes=(cd.get("notes") or "Pedido tomado por bot WhatsApp"),
    )
    db.session.add(sale)
    db.session.flush()
    sale.number = f"BOT-{sale.id:06d}"

    # Items: snapshot. Sin asignar product_item_id — el vendedor humano
    # asigna seriales al despachar (importante para iPhones).
    for it in conv.cart_items:
        db.session.add(SaleItem(
            sale_id=sale.id,
            product_id=int(it.get("product_id")),
            unit_price=_D(str(it.get("unit_price", "0"))),
            quantity=int(it.get("qty", 1)),
            line_total=_D(str(it.get("line_total", "0"))),
        ))

    # AccountReceivable con saldo completo (vendedor confirma pago).
    ar = AccountReceivable(
        customer_id=customer.id,
        sale_id=sale.id,
        total=sale.total,
        paid=_D("0"),
        currency=sale.currency,
        status=ReceivableStatus.PENDING,
    )
    db.session.add(ar)

    # Update de la conversación.
    conv.sale_id = sale.id
    conv.stage = BotStage.COMPLETED

    # Si hay un lead abierto del mismo teléfono, lo cerramos como ganado.
    lead = (
        SalesLead.query.filter(SalesLead.phone == norm_phone)
        .filter(SalesLead.status.in_([LeadStatus.NEW, LeadStatus.CONTACTED]))
        .order_by(SalesLead.created_at.desc())
        .first()
    )
    if lead:
        lead.status = LeadStatus.CLOSED_WON
        lead.sale_id = sale.id
        lead.customer_id = customer.id

    db.session.commit()

    return jsonify(
        ok=True,
        sale_id=sale.id,
        sale_number=sale.number,
        total=str(sale.total),
        currency=sale.currency,
        admin_url=f"/admin/sales/{sale.id}",
        message=(
            f"Pedido {sale.number} creado correctamente. "
            "Está pendiente de pago — un asesor te va a contactar para coordinar."
        ),
    ), 201


