"""Endpoints admin para visualizar conversaciones activas del bot.

Permite ver:
- Lista de conversaciones por stage (cuántas en cada etapa)
- Detalle: carrito, datos del cliente, historial de mensajes
- Resetear una conversación atascada
"""
from flask import jsonify, request
from sqlalchemy import text as _sql

from ...extensions import db
from ...models import BotConversation, BotStage
from ...permissions import require_permission
from ...utils import get_or_404, paginate
from . import admin_bp


def _dump(conv: BotConversation) -> dict:
    from decimal import Decimal as _D
    cart = conv.cart_items or []
    cart_total = sum(
        (_D(str(it.get("line_total", "0"))) for it in cart),
        _D("0"),
    )
    return {
        "id": conv.id,
        "phone": conv.phone,
        "whatsapp_link": f"https://wa.me/{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": conv.customer_data or {},
        "sale_id": conv.sale_id,
        "sale_number": conv.sale.number if conv.sale else None,
        "last_active_at": conv.last_active_at.isoformat() if conv.last_active_at else None,
        "created_at": conv.created_at.isoformat() if conv.created_at else None,
    }


@admin_bp.get("/bot-conversations")
@require_permission("leads.view")
def list_bot_conversations():
    """Lista conversaciones por stage. Por defecto excluye COMPLETED."""
    q = BotConversation.query.order_by(BotConversation.last_active_at.desc())
    if stage := request.args.get("stage"):
        q = q.filter(BotConversation.stage == stage.lower())
    elif request.args.get("show_completed", "false").lower() not in ("true", "1"):
        q = q.filter(BotConversation.stage != BotStage.COMPLETED)
    page = paginate(q)
    page["items"] = [_dump(x) for x in page["items"]]
    # Conteos por stage para badges en la UI
    counts = {}
    for s in BotStage:
        counts[s.value] = BotConversation.query.filter(
            BotConversation.stage == s,
        ).count()
    page["counts"] = counts
    return jsonify(page)


@admin_bp.get("/bot-conversations/<int:conv_id>")
@require_permission("leads.view")
def get_bot_conversation(conv_id):
    """Detalle de una conversación + últimos mensajes del chat."""
    conv = get_or_404(BotConversation, conv_id)
    out = _dump(conv)
    # Traemos historial de mensajes (texto de WhatsApp).
    rows = db.session.execute(_sql(
        "SELECT role, user_name, type_message, message, intent, created_at "
        "FROM bot_messages WHERE user_number = :phone "
        "ORDER BY id DESC LIMIT 30"
    ), {"phone": conv.phone}).fetchall()
    out["messages"] = [
        {
            "role": r.role,
            "user_name": r.user_name,
            "type": r.type_message,
            "message": r.message or "",
            "intent": r.intent,
            "created_at": r.created_at.isoformat() if r.created_at else None,
        }
        for r in reversed(rows)
    ]
    return jsonify(out)


@admin_bp.post("/bot-conversations/<int:conv_id>/reset")
@require_permission("leads.update")
def reset_bot_conversation(conv_id):
    """Resetea la conversación: vacía carrito y datos, vuelve a BROWSING.
    Útil cuando un cliente quedó atascado en algún ASKING_*."""
    conv = get_or_404(BotConversation, conv_id)
    conv.cart_items = []
    conv.customer_data = {}
    conv.stage = BotStage.BROWSING
    db.session.commit()
    return jsonify(_dump(conv))


@admin_bp.delete("/bot-conversations/<int:conv_id>")
@require_permission("leads.delete")
def delete_bot_conversation(conv_id):
    conv = get_or_404(BotConversation, conv_id)
    db.session.delete(conv)
    db.session.commit()
    return "", 204
