# -*- coding: utf-8 -*-
"""
Bot de Telegram para negocios — Demo 2 (Arsenal Freelance)
===========================================================
Esqueleto funcional de un bot que:
  1) Responde PREGUNTAS FRECUENTES (FAQ) con botones.
  2) Toma PEDIDOS simples desde un catálogo (diccionario).
  3) Notifica al DUEÑO cada vez que entra un pedido.

Usa la librería `python-telegram-bot` (v20+, asíncrona).

IMPORTANTE: no se ejecuta sin un token real de BotFather. Pega tu token
en la variable TOKEN (o mejor, en la variable de entorno TELEGRAM_TOKEN)
y pon tu ID de Telegram en OWNER_CHAT_ID para recibir los avisos.
"""

import os
import logging

from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, ReplyKeyboardMarkup
from telegram.ext import (
    Application, CommandHandler, CallbackQueryHandler,
    MessageHandler, ContextTypes, filters,
)

# ---------------------------------------------------------------------------
# CONFIGURACIÓN  (edita esto)
# ---------------------------------------------------------------------------
TOKEN = os.environ.get("TELEGRAM_TOKEN", "PEGA_AQUI_TU_TOKEN_DE_BOTFATHER")
OWNER_CHAT_ID = os.environ.get("OWNER_CHAT_ID", "PEGA_AQUI_TU_CHAT_ID")

NOMBRE_NEGOCIO = "Pizzería Don Antonio"

# Catálogo de productos (nombre -> precio). Cámbialo por el tuyo.
CATALOGO = {
    "Pizza Margarita": 8500,
    "Pizza Pepperoni": 9500,
    "Empanada de queso": 1500,
    "Bebida 1.5L": 2500,
}

# Preguntas frecuentes (pregunta corta -> respuesta)
FAQ = {
    "Horario": "Abrimos todos los días de 12:00 a 23:00.",
    "Ubicación": "Estamos en Av. Siempre Viva 123. ¡Te esperamos!",
    "Delivery": "Sí, hacemos delivery en toda la ciudad. Costo: $2.000.",
    "Métodos de pago": "Aceptamos efectivo, tarjeta y transferencia.",
}

logging.basicConfig(
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    level=logging.INFO,
)

# ---------------------------------------------------------------------------
# COMANDOS
# ---------------------------------------------------------------------------
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    teclado = ReplyKeyboardMarkup(
        [["📋 Ver menú", "❓ Preguntas frecuentes"], ["🛒 Hacer pedido"]],
        resize_keyboard=True,
    )
    await update.message.reply_text(
        "¡Hola! 👋 Bienvenido a *%s*.\n"
        "Soy el asistente automático. ¿En qué te ayudo?" % NOMBRE_NEGOCIO,
        reply_markup=teclado,
        parse_mode="Markdown",
    )


async def mostrar_menu(update: Update, context: ContextTypes.DEFAULT_TYPE):
    lineas = ["🍕 *Nuestro menú:*", ""]
    for producto, precio in CATALOGO.items():
        lineas.append("• %s — $%s" % (producto, format(precio, ",d")))
    lineas.append("\nEscribe *Hacer pedido* para ordenar.")
    await update.message.reply_text("\n".join(lineas), parse_mode="Markdown")


async def mostrar_faq(update: Update, context: ContextTypes.DEFAULT_TYPE):
    botones = [[InlineKeyboardButton(p, callback_data="faq:%s" % p)] for p in FAQ]
    await update.message.reply_text(
        "❓ Elige tu pregunta:",
        reply_markup=InlineKeyboardMarkup(botones),
    )


async def responder_faq(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()
    clave = query.data.split(":", 1)[1]
    await query.edit_message_text("💬 %s\n\n%s" % (clave, FAQ.get(clave, "No encontré esa pregunta.")))


# ---------------------------------------------------------------------------
# PEDIDOS  (flujo simple: elegir producto -> confirmar -> avisar al dueño)
# ---------------------------------------------------------------------------
async def iniciar_pedido(update: Update, context: ContextTypes.DEFAULT_TYPE):
    botones = [[InlineKeyboardButton("%s ($%s)" % (p, format(pr, ",d")),
                callback_data="pedir:%s" % p)] for p, pr in CATALOGO.items()]
    await update.message.reply_text(
        "🛒 ¿Qué quieres pedir? Toca un producto:",
        reply_markup=InlineKeyboardMarkup(botones),
    )


async def registrar_pedido(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()
    producto = query.data.split(":", 1)[1]
    precio = CATALOGO.get(producto, 0)
    cliente = query.from_user

    # Confirmación al cliente
    await query.edit_message_text(
        "✅ ¡Pedido recibido!\n\n"
        "• Producto: %s\n• Precio: $%s\n\n"
        "En breve te contactamos para la entrega. ¡Gracias! 🙌"
        % (producto, format(precio, ",d"))
    )

    # Notificación al DUEÑO
    aviso = (
        "🔔 *NUEVO PEDIDO*\n\n"
        "Producto: %s\nPrecio: $%s\n"
        "Cliente: %s (@%s)\nID: %s"
        % (producto, format(precio, ",d"),
           cliente.full_name, cliente.username or "sin_usuario", cliente.id)
    )
    try:
        await context.bot.send_message(chat_id=OWNER_CHAT_ID, text=aviso, parse_mode="Markdown")
    except Exception as e:
        logging.warning("No se pudo avisar al dueño (revisa OWNER_CHAT_ID): %s", e)


# ---------------------------------------------------------------------------
# ENRUTADOR DE TEXTO (los botones del teclado envían texto)
# ---------------------------------------------------------------------------
async def enrutar_texto(update: Update, context: ContextTypes.DEFAULT_TYPE):
    texto = (update.message.text or "").lower()
    if "menú" in texto or "menu" in texto:
        await mostrar_menu(update, context)
    elif "frecuentes" in texto or "faq" in texto:
        await mostrar_faq(update, context)
    elif "pedido" in texto or "ordenar" in texto:
        await iniciar_pedido(update, context)
    else:
        await update.message.reply_text(
            "No entendí 🤔. Usa los botones o escribe /start para ver el menú."
        )


# ---------------------------------------------------------------------------
# ARRANQUE
# ---------------------------------------------------------------------------
def main():
    if "PEGA_AQUI" in TOKEN:
        print("⚠️  Falta configurar el TOKEN. Crea tu bot con @BotFather y pégalo.")
        print("    (variable TOKEN o entorno TELEGRAM_TOKEN). Ver README.md")
        return

    app = Application.builder().token(TOKEN).build()
    app.add_handler(CommandHandler("start", start))
    app.add_handler(CommandHandler("menu", mostrar_menu))
    app.add_handler(CallbackQueryHandler(responder_faq, pattern=r"^faq:"))
    app.add_handler(CallbackQueryHandler(registrar_pedido, pattern=r"^pedir:"))
    app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, enrutar_texto))

    print("🤖 Bot en marcha. Abre Telegram y escríbele /start. (Ctrl+C para parar)")
    app.run_polling(allowed_updates=Update.ALL_TYPES)


if __name__ == "__main__":
    main()
