import os
import sys
import time
import uuid
import math
import threading
import requests
from flask import Flask, request, jsonify

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
if BASE_DIR not in sys.path:
    sys.path.insert(0, BASE_DIR)

from storage import load_config, save_config, load_db, update_db, ensure_user, get_vip_tier, egypt_now
from aitool_client import CATEGORIES, fetch_catalog, get_product_by_id, place_supplier_order, get_supplier_balance, extract_delivery_text
import tg_api

app = Flask(__name__)

ITEMS_PER_PAGE = 8


def _mask_name(user_obj):
    raw = (user_obj.get("username") or user_obj.get("first_name") or "Buyer").lstrip("@")
    if len(raw) <= 2:
        return raw[0] + "***"
    return raw[0] + "***" + raw[-1]


def _bot_link(param=""):
    cfg = load_config()
    uname = (cfg.get("bot_username") or "").lstrip("@").strip()
    if not uname:
        me = tg_api.get_me()
        if me.get("ok"):
            uname = me["result"].get("username", "")
            if uname:
                cfg["bot_username"] = uname
                save_config(cfg)
    if not uname:
        return ""
    return f"https://t.me/{uname}?start={param}" if param else f"https://t.me/{uname}"


def _is_admin(tg_id):
    cfg = load_config()
    admins = {str(x) for x in cfg.get("admin_ids", [])}
    return str(tg_id) in admins


def _main_reply_keyboard(tg_id=None):
    rows = [
        [{"text": "🛍️ Browse Store"}, {"text": "🔍 Search"}],
        [{"text": "👛 My Wallet"}, {"text": "📦 Order History"}],
        [{"text": "👤 VIP Profile"}, {"text": "🎫 Support"}]
    ]
    if tg_id and _is_admin(tg_id):
        rows.append([{"text": "👑 Admin Panel"}])
    return {"keyboard": rows, "resize_keyboard": True, "is_persistent": True}


def _push_ticket_to_sales_bridge(ticket_obj, new_msg):
    cfg = load_config()
    base = (cfg.get("sales_bridge_url") or "").rstrip("/")
    secret = cfg.get("bridge_secret") or ""
    if not base:
        return
    try:
        requests.post(
            f"{base}/api/tg-tickets/incoming",
            json={"ticket": ticket_obj, "message": new_msg, "bot_token": cfg.get("bot_token", "")},
            headers={"X-Bridge-Secret": secret, "Content-Type": "application/json"},
            timeout=6
        )
    except Exception as e:
        print(f"[Bridge Push Error] {e}")


def broadcast_purchase_to_channel(user_obj, product, qty, total_price):
    """Posts an instant luxury Purchase Successful card to the Telegram channel/group."""
    cfg = load_config()
    channel_id = str(cfg.get("channel_id") or "").strip()
    if not channel_id:
        return

    store_name = cfg.get("store_name") or "Nova Digital"
    bot_uname = (cfg.get("bot_username") or "").lstrip("@")
    buyer_masked = _mask_name(user_obj)
    now_cairo = egypt_now().strftime("%d %b %Y, %I:%M %p (Cairo)")

    text = (
        f"<blockquote>🛒 <b>Purchase Successful</b>\n\n"
        f"👤 <b>Buyer:</b> {tg_api.esc(buyer_masked)}\n"
        f"📦 <b>Product:</b> {tg_api.esc(product['name'])}\n"
        f"🔢 <b>Quantity:</b> {qty}\n"
        f"💵 <b>Total:</b> <b>${total_price:.2f}</b>\n"
        f"🏪 <b>Store:</b> {tg_api.esc(store_name)} · ⭐ 4.9\n"
        f"🕒 {now_cairo}</blockquote>\n\n"
        f"🛡 <i>{tg_api.esc(store_name)} · Instant automated delivery, 24/7 verified</i>\n"
        + (f"🤖 <b>Official Bot:</b> @{bot_uname}" if bot_uname else "")
    )
    deep_link = _bot_link(f"prod_{product['id']}")
    kb = {"inline_keyboard": [[{"text": "🛒 Buy this product", "url": deep_link}]]} if deep_link else None
    tg_api.send_message(channel_id, text, reply_markup=kb)


def broadcast_product_alert_to_channel(product, alert_type="new"):
    cfg = load_config()
    channel_id = str(cfg.get("channel_id") or "").strip()
    if not channel_id:
        return
    store_name = cfg.get("store_name") or "Nova Digital"
    bot_uname = (cfg.get("bot_username") or "").lstrip("@")
    badge = "🆕 <b>New Product</b>" if alert_type == "new" else "🔥 <b>Back in Stock!</b>"
    sub = "✨ <i>Just added. Be the first to buy!</i>" if alert_type == "new" else "⚡ <i>Fresh stock loaded &amp; ready for instant delivery!</i>"
    stock_lbl = "Unlimited" if product.get("is_unlimited") else str(product.get("stock", 0))

    text = (
        f"<blockquote>{badge}\n\n"
        f"📦 <b>{tg_api.esc(product['name'])}</b>\n"
        f"💵 <b>Price:</b> <b>${product['price']:.2f}</b>\n"
        f"📊 <b>Stock:</b> {stock_lbl} · ⚡ Instant delivery\n"
        f"🏪 <b>Store:</b> {tg_api.esc(store_name)} · ⭐ 4.9</blockquote>\n\n"
        f"{sub}\n"
        f"🛡 <i>{tg_api.esc(store_name)} · Protected automated delivery</i>\n"
        + (f"🤖 <b>Official Bot:</b> @{bot_uname}" if bot_uname else "")
    )
    deep_link = _bot_link(f"prod_{product['id']}")
    kb = {"inline_keyboard": [[{"text": "🛒 Buy now", "url": deep_link}]]} if deep_link else None
    tg_api.send_message(channel_id, text, reply_markup=kb)


def sync_and_broadcast_catalog_updates(max_posts=5):
    """Detects newly added or restocked AiToolShop items and posts to channel."""
    prods = fetch_catalog(force=True)
    cfg = load_config()
    if not cfg.get("channel_id"):
        return {"posted": 0, "reason": "No channel_id configured"}

    to_post = []

    def _mutate(db):
        announced = db.setdefault("announced_products", {})
        first_run = (len(announced) == 0)
        for p in prods:
            pid = str(p["id"])
            in_stock = bool(p.get("in_stock"))
            prev = announced.get(pid)
            if first_run:
                announced[pid] = {"in_stock": in_stock, "price": p["price"]}
                continue
            if prev is None and in_stock:
                to_post.append((p, "new"))
            elif prev is not None and (not prev.get("in_stock")) and in_stock:
                to_post.append((p, "restock"))
            announced[pid] = {"in_stock": in_stock, "price": p["price"]}
        return first_run

    first_run = update_db(_mutate)
    if first_run:
        return {"posted": 0, "seeded": len(prods)}

    posted = 0
    for p, kind in to_post[:max_posts]:
        broadcast_product_alert_to_channel(p, kind)
        posted += 1
        time.sleep(0.4)
    return {"posted": posted, "queued": len(to_post)}


# ==============================================================================
# UI Screens
# ==============================================================================

def send_welcome_screen(chat_id, tg_user):
    def _m(db):
        return ensure_user(db, tg_user)
    u = update_db(_m)
    cfg = load_config()
    store_name = cfg.get("store_name") or "Nova Digital"
    tier = get_vip_tier(u.get("total_spent", 0))

    text = (
        f"✨ <b>Welcome to {tg_api.esc(store_name)} VIP Store</b> ✨\n\n"
        f"<blockquote>👋 Hello <b>{tg_api.esc(u['first_name'])}</b>!\n"
        f"🏅 <b>Tier:</b> {tier}\n"
        f"👛 <b>Wallet Balance:</b> <code>${u.get('balance', 0.0):.2f}</code>\n"
        f"📦 <b>Total Orders:</b> {u.get('total_orders', 0)}</blockquote>\n\n"
        f"⚡ <b>Instant Automated Delivery 24/7</b>\n"
        f"💎 Browse 400+ AI, VPN, Streaming &amp; Software plans at unbeatable prices.\n\n"
        f"👇 <i>Choose an option below to get started:</i>"
    )
    inline = {
        "inline_keyboard": [
            [{"text": "🛍️ Browse Store", "callback_data": "cats:0"}, {"text": "🔍 Search Products", "callback_data": "search"}],
            [{"text": "👛 My Wallet", "callback_data": "wallet"}, {"text": "📦 My Orders", "callback_data": "orders:0"}],
            [{"text": "👤 VIP Profile", "callback_data": "profile"}, {"text": "🎫 Support Ticket", "callback_data": "support"}]
        ]
    }
    tg_api.send_message(chat_id, text, reply_markup=_main_reply_keyboard(chat_id))
    tg_api.send_message(chat_id, "🚀 <b>Quick Dashboard</b> — Pick an action:", reply_markup=inline)


def show_categories(chat_id, message_id=None):
    prods = fetch_catalog()
    counts = {}
    for p in prods:
        if p["in_stock"]:
            counts[p["category"]] = counts.get(p["category"], 0) + 1

    buttons = []
    row = []
    for key, label in CATEGORIES:
        cnt = counts.get(key, 0)
        if cnt == 0:
            continue
        row.append({"text": f"{label} ({cnt})", "callback_data": f"cat:{key}:0"})
        if len(row) == 2:
            buttons.append(row)
            row = []
    if row:
        buttons.append(row)
    buttons.append([{"text": "🔍 Search by Name", "callback_data": "search"}])
    buttons.append([{"text": "🏠 Main Menu", "callback_data": "home"}])

    total_avail = sum(counts.values())
    text = (
        f"🛍️ <b>Nova Digital Catalog</b>\n\n"
        f"<blockquote>⚡ <b>{total_avail}</b> products in stock &amp; ready for instant delivery!\n"
        f"Select a category below to browse plans &amp; live prices:</blockquote>"
    )
    kb = {"inline_keyboard": buttons}
    if message_id:
        tg_api.edit_message(chat_id, message_id, text, reply_markup=kb)
    else:
        tg_api.send_message(chat_id, text, reply_markup=kb)


def show_category_products(chat_id, cat_key, page=0, message_id=None):
    prods = [p for p in fetch_catalog() if p["category"] == cat_key and p["in_stock"]]
    prods.sort(key=lambda x: (x["price"], x["name"]))
    cat_label = dict(CATEGORIES).get(cat_key, "Products")

    total_pages = max(1, math.ceil(len(prods) / ITEMS_PER_PAGE))
    page = max(0, min(page, total_pages - 1))
    slice_items = prods[page * ITEMS_PER_PAGE:(page + 1) * ITEMS_PER_PAGE]

    buttons = []
    for p in slice_items:
        stock_txt = "∞" if p["is_unlimited"] else p["stock"]
        short_name = p["name"][:34] + ("…" if len(p["name"]) > 34 else "")
        buttons.append([{
            "text": f"💎 {short_name} · ${p['price']:.2f} ({stock_txt})",
            "callback_data": f"prod:{p['id']}:{cat_key}:{page}"
        }])

    nav = []
    if page > 0:
        nav.append({"text": "⬅️ Prev", "callback_data": f"cat:{cat_key}:{page - 1}"})
    nav.append({"text": f"📄 {page + 1}/{total_pages}", "callback_data": "noop"})
    if page < total_pages - 1:
        nav.append({"text": "Next ➡️", "callback_data": f"cat:{cat_key}:{page + 1}"})
    if nav:
        buttons.append(nav)
    buttons.append([{"text": "⬅️ Categories", "callback_data": "cats:0"}, {"text": "🏠 Home", "callback_data": "home"}])

    text = (
        f"{cat_label}\n\n"
        f"<blockquote>📦 Showing <b>{len(slice_items)}</b> of <b>{len(prods)}</b> available items.\n"
        f"Tap any product to inspect details &amp; buy instantly:</blockquote>"
    )
    kb = {"inline_keyboard": buttons}
    if message_id:
        tg_api.edit_message(chat_id, message_id, text, reply_markup=kb)
    else:
        tg_api.send_message(chat_id, text, reply_markup=kb)


def show_product_detail(chat_id, pid, back_cat="ai", back_page=0, message_id=None):
    p = get_product_by_id(pid, force=False)
    if not p:
        p = get_product_by_id(pid, force=True)
    if not p:
        tg_api.send_message(chat_id, "❌ Product not found or currently unavailable.")
        return

    db = load_db()
    u = db.get("users", {}).get(str(chat_id), {})
    bal = float(u.get("balance", 0.0))
    stock_txt = "Unlimited ♾️" if p["is_unlimited"] else f"{p['stock']} left"
    desc = p["description"][:450] + ("…" if len(p["description"]) > 450 else "")
    desc_block = f"\n📝 <b>Description:</b>\n<i>{tg_api.esc(desc)}</i>\n" if desc else ""

    text = (
        f"💎 <b>{tg_api.esc(p['name'])}</b>\n\n"
        f"<blockquote>💵 <b>Price:</b> <b>${p['price']:.2f}</b>\n"
        f"📦 <b>Stock:</b> {stock_txt}\n"
        f"⚡ <b>Delivery:</b> Instant Automated Delivery\n"
        f"👛 <b>Your Balance:</b> <code>${bal:.2f}</code></blockquote>\n"
        f"{desc_block}\n"
        f"👇 <i>Ready to unlock instant access?</i>"
    )

    buttons = []
    if p["in_stock"]:
        if bal >= p["price"]:
            buttons.append([{"text": f"⚡ Buy Now (${p['price']:.2f})", "callback_data": f"buy_confirm:{p['id']}:1"}])
            if (p["is_unlimited"] or p["stock"] >= 3) and bal >= p["price"] * 2:
                buttons.append([
                    {"text": f"Buy x2 (${p['price']*2:.2f})", "callback_data": f"buy_confirm:{p['id']}:2"},
                    {"text": f"Buy x3 (${p['price']*3:.2f})", "callback_data": f"buy_confirm:{p['id']}:3"}
                ])
        else:
            needed = max(0.01, round(p["price"] - bal, 2))
            buttons.append([{"text": f"💳 Top Up Wallet (Need +${needed:.2f})", "callback_data": "topup"}])
    else:
        buttons.append([{"text": "⚠️ Out of Stock", "callback_data": "noop"}])

    buttons.append([
        {"text": "⬅️ Back", "callback_data": f"cat:{back_cat}:{back_page}"},
        {"text": "🏠 Home", "callback_data": "home"}
    ])
    kb = {"inline_keyboard": buttons}
    if message_id:
        tg_api.edit_message(chat_id, message_id, text, reply_markup=kb)
    else:
        tg_api.send_message(chat_id, text, reply_markup=kb)


def execute_purchase(chat_id, tg_user, pid, qty=1, message_id=None):
    p = get_product_by_id(pid, force=True)
    if not p or not p["in_stock"]:
        tg_api.send_message(chat_id, "❌ Sorry, this product just went out of stock!")
        return
    if not p["is_unlimited"] and qty > p["stock"]:
        tg_api.send_message(chat_id, f"⚠️ Only <b>{p['stock']}</b> units available right now.")
        return

    total_cost = round(p["price"] * qty, 2)

    # Atomic wallet deduction before hitting supplier
    def _reserve(db):
        u = ensure_user(db, tg_user)
        if float(u.get("balance", 0.0)) < total_cost:
            return {"ok": False, "bal": float(u.get("balance", 0.0))}
        u["balance"] = round(float(u["balance"]) - total_cost, 2)
        return {"ok": True, "user": dict(u)}

    resv = update_db(_reserve)
    if not resv["ok"]:
        needed = round(total_cost - resv["bal"], 2)
        tg_api.send_message(
            chat_id,
            f"⚠️ <b>Insufficient Wallet Balance</b>\n\nNeeded: <code>${total_cost:.2f}</code>\nYour Balance: <code>${resv['bal']:.2f}</code>\nShortfall: <code>${needed:.2f}</code>",
            reply_markup={"inline_keyboard": [[{"text": "💳 Top Up Wallet Now", "callback_data": "topup"}]]}
        )
        return

    if message_id:
        tg_api.edit_message(chat_id, message_id, "⏳ <b>Processing your instant order...</b>\n<i>Fetching your verified credentials from vault...</i>")

    email_hint = f"{(tg_user.get('username') or f'user{chat_id}')}@nova-digital.site"
    try:
        sup_res = place_supplier_order(pid, quantity=qty, customer_email=email_hint)
    except Exception as e:
        sup_res = {"success": False, "error": str(e)}

    if not isinstance(sup_res, dict) or not sup_res.get("success"):
        # Refund atomically if supplier failed
        def _refund(db):
            u = ensure_user(db, tg_user)
            u["balance"] = round(float(u["balance"]) + total_cost, 2)
        update_db(_refund)
        err = sup_res.get("error") if isinstance(sup_res, dict) else "Supplier error"
        tg_api.send_message(
            chat_id,
            f"❌ <b>Order Failed — Wallet Refunded!</b>\n\nReason: <code>{tg_api.esc(err)}</code>\n💵 <code>${total_cost:.2f}</code> has been returned to your wallet."
        )
        return

    delivery_text = extract_delivery_text(sup_res)
    order_ref = sup_res.get("order_ref") or sup_res.get("reference") or f"NV-{int(time.time())}"
    now_str = egypt_now().strftime("%Y-%m-%d %I:%M %p")

    def _record_order(db):
        u = ensure_user(db, tg_user)
        u["total_spent"] = round(float(u.get("total_spent", 0.0)) + total_cost, 2)
        u["total_orders"] = int(u.get("total_orders", 0)) + 1
        order_obj = {
            "order_ref": str(order_ref),
            "tg_id": str(chat_id),
            "username": u.get("username", ""),
            "product_id": p["id"],
            "product_name": p["name"],
            "qty": qty,
            "unit_price": p["price"],
            "total_price": total_cost,
            "delivery_html": delivery_text,
            "status": "completed",
            "created_at": now_str
        }
        db.setdefault("orders", []).insert(0, order_obj)
        return dict(u), order_obj

    updated_user, _ = update_db(_record_order)

    receipt = (
        f"🎉 <b>Order Delivered Successfully!</b>\n\n"
        f"<blockquote>📦 <b>Product:</b> {tg_api.esc(p['name'])}\n"
        f"🔢 <b>Quantity:</b> {qty}\n"
        f"💵 <b>Paid:</b> <code>${total_cost:.2f}</code>\n"
        f"👛 <b>Remaining Balance:</b> <code>${updated_user['balance']:.2f}</code>\n"
        f"🕒 <b>Time:</b> {now_str} (Cairo)</blockquote>\n\n"
        f"🔐 <b>Your Delivery Details:</b>\n"
        f"<blockquote>{delivery_text}</blockquote>\n\n"
        f"✨ <i>Thank you for choosing Nova Digital! Need help? Open a Support Ticket anytime.</i>"
    )
    kb = {
        "inline_keyboard": [
            [{"text": "📦 View Order History", "callback_data": "orders:0"}, {"text": "🛍️ Buy More", "callback_data": "cats:0"}],
            [{"text": "🎫 Support Ticket", "callback_data": f"newticket:{order_ref}"}]
        ]
    }
    tg_api.send_message(chat_id, receipt, reply_markup=kb)

    # Instant Live Broadcast to Channel/Group right on purchase (synchronous so LiteSpeed/WSGI won't clip it)
    try:
        broadcast_purchase_to_channel(updated_user, p, qty, total_cost)
    except Exception as e:
        print(f"[Channel Broadcast Error] {e}")


def show_wallet(chat_id, tg_user, message_id=None):
    db = load_db()
    u = db.get("users", {}).get(str(chat_id)) or {}
    bal = float(u.get("balance", 0.0))
    deps = [d for d in db.get("deposits", []) if str(d.get("tg_id")) == str(chat_id)][:5]

    dep_lines = []
    for d in deps:
        st_icon = "✅" if d["status"] == "approved" else ("❌" if d["status"] == "rejected" else "⏳")
        dep_lines.append(f"{st_icon} <code>${d['amount']:.2f}</code> · {tg_api.esc(d['method'])} · {d['created_at']}")
    dep_block = "\n".join(dep_lines) if dep_lines else "<i>No recent top-ups yet.</i>"

    text = (
        f"👛 <b>My VIP Wallet</b>\n\n"
        f"<blockquote>💵 <b>Available Balance:</b> <b><code>${bal:.2f}</code> USD</b>\n"
        f"💳 <b>Total Spent:</b> <code>${float(u.get('total_spent', 0.0)):.2f}</code>\n"
        f"🏅 <b>VIP Tier:</b> {get_vip_tier(u.get('total_spent', 0))}</blockquote>\n\n"
        f"🧾 <b>Recent Top-Ups:</b>\n{dep_block}"
    )
    kb = {
        "inline_keyboard": [
            [{"text": "➕ Top Up Wallet", "callback_data": "topup"}],
            [{"text": "🛍️ Browse Store", "callback_data": "cats:0"}, {"text": "🏠 Home", "callback_data": "home"}]
        ]
    }
    if message_id:
        tg_api.edit_message(chat_id, message_id, text, reply_markup=kb)
    else:
        tg_api.send_message(chat_id, text, reply_markup=kb)


def show_topup_methods(chat_id, message_id=None):
    cfg = load_config()
    methods = cfg.get("payment_methods", [])
    btns = [[{"text": f"💳 {m['name']}", "callback_data": f"topup_m:{m['id']}"}] for m in methods]
    btns.append([{"text": "⬅️ Back to Wallet", "callback_data": "wallet"}])

    text = (
        f"💳 <b>Top Up Your Wallet</b>\n\n"
        f"<blockquote>⚡ Instant balance credit once verified by our team.\n"
        f"Choose your preferred payment method below:</blockquote>"
    )
    kb = {"inline_keyboard": btns}
    if message_id:
        tg_api.edit_message(chat_id, message_id, text, reply_markup=kb)
    else:
        tg_api.send_message(chat_id, text, reply_markup=kb)


def show_orders_history(chat_id, page=0, message_id=None):
    db = load_db()
    my_orders = [o for o in db.get("orders", []) if str(o.get("tg_id")) == str(chat_id)]
    if not my_orders:
        text = "📦 <b>Order History</b>\n\n<blockquote>You haven't placed any orders yet.\nExplore our catalog to get started!</blockquote>"
        kb = {"inline_keyboard": [[{"text": "🛍️ Browse Store", "callback_data": "cats:0"}, {"text": "🏠 Home", "callback_data": "home"}]]}
        if message_id:
            tg_api.edit_message(chat_id, message_id, text, reply_markup=kb)
        else:
            tg_api.send_message(chat_id, text, reply_markup=kb)
        return

    per_page = 6
    total_pages = max(1, math.ceil(len(my_orders) / per_page))
    page = max(0, min(page, total_pages - 1))
    items = my_orders[page * per_page:(page + 1) * per_page]

    buttons = []
    for o in items:
        short_n = o["product_name"][:28] + ("…" if len(o["product_name"]) > 28 else "")
        buttons.append([{
            "text": f"🧾 #{o['order_ref'][:12]} · {short_n} (${o['total_price']:.2f})",
            "callback_data": f"ord_view:{o['order_ref']}"
        }])

    nav = []
    if page > 0:
        nav.append({"text": "⬅️ Prev", "callback_data": f"orders:{page - 1}"})
    if total_pages > 1:
        nav.append({"text": f"{page + 1}/{total_pages}", "callback_data": "noop"})
    if page < total_pages - 1:
        nav.append({"text": "Next ➡️", "callback_data": f"orders:{page + 1}"})
    if nav:
        buttons.append(nav)
    buttons.append([{"text": "🏠 Home", "callback_data": "home"}])

    text = f"📦 <b>Your Order History ({len(my_orders)} total)</b>\n\n<i>Tap any order to view credentials or open a ticket:</i>"
    kb = {"inline_keyboard": buttons}
    if message_id:
        tg_api.edit_message(chat_id, message_id, text, reply_markup=kb)
    else:
        tg_api.send_message(chat_id, text, reply_markup=kb)


def show_profile(chat_id, tg_user, message_id=None):
    def _m(db):
        return ensure_user(db, tg_user)
    u = update_db(_m)
    tier = get_vip_tier(u.get("total_spent", 0))
    uname = f"@{u['username']}" if u.get("username") else "Not set"
    text = (
        f"👤 <b>VIP Customer Profile</b>\n\n"
        f"<blockquote>🆔 <b>User ID:</b> <code>{u['id']}</code>\n"
        f"👤 <b>Name:</b> {tg_api.esc(u['first_name'])}\n"
        f"📱 <b>Username:</b> {tg_api.esc(uname)}\n"
        f"🏅 <b>VIP Tier:</b> {tier}\n"
        f"👛 <b>Wallet Balance:</b> <code>${float(u.get('balance', 0.0)):.2f}</code>\n"
        f"📦 <b>Total Orders:</b> {u.get('total_orders', 0)}\n"
        f"💰 <b>Lifetime Spent:</b> <code>${float(u.get('total_spent', 0.0)):.2f}</code>\n"
        f"📅 <b>Member Since:</b> {u.get('joined_at', '')}</blockquote>"
    )
    kb = {
        "inline_keyboard": [
            [{"text": "👛 My Wallet", "callback_data": "wallet"}, {"text": "📦 Order History", "callback_data": "orders:0"}],
            [{"text": "🏠 Main Menu", "callback_data": "home"}]
        ]
    }
    if message_id:
        tg_api.edit_message(chat_id, message_id, text, reply_markup=kb)
    else:
        tg_api.send_message(chat_id, text, reply_markup=kb)


def show_support_menu(chat_id, message_id=None):
    db = load_db()
    my_tickets = [t for t in db.get("tickets", {}).values() if str(t.get("tg_id")) == str(chat_id)]
    my_tickets.sort(key=lambda x: x.get("updated_at", ""), reverse=True)

    buttons = [[{"text": "➕ Open New Support Ticket", "callback_data": "newticket:general"}]]
    for t in my_tickets[:5]:
        icon = "🟢" if t.get("status") == "open" else "🔒"
        buttons.append([{
            "text": f"{icon} #{t['id']} · {t.get('subject', 'Support')[:28]}",
            "callback_data": f"tkt_view:{t['id']}"
        }])
    buttons.append([{"text": "🏠 Home", "callback_data": "home"}])

    text = (
        f"🎫 <b>Nova Digital Live Support</b>\n\n"
        f"<blockquote>💬 Open a support ticket and chat directly with our team inside Telegram.\n"
        f"All replies from our support desk arrive here in real time!</blockquote>"
    )
    kb = {"inline_keyboard": buttons}
    if message_id:
        tg_api.edit_message(chat_id, message_id, text, reply_markup=kb)
    else:
        tg_api.send_message(chat_id, text, reply_markup=kb)


def show_admin_panel(chat_id, message_id=None):
    if not _is_admin(chat_id):
        return
    db = load_db()
    sup_bal = get_supplier_balance()
    bal_val = sup_bal.get("balance") or sup_bal.get("data", {}).get("balance") or "N/A"
    pending_deps = [d for d in db.get("deposits", []) if d.get("status") == "pending"]
    open_tkts = [t for t in db.get("tickets", {}).values() if t.get("status") == "open"]
    total_rev = sum(float(o.get("total_price", 0)) for o in db.get("orders", []))

    text = (
        f"👑 <b>Nova Digital Admin Panel</b>\n\n"
        f"<blockquote>👥 <b>Total Bot Users:</b> {len(db.get('users', {}))}\n"
        f"📦 <b>Total Bot Orders:</b> {len(db.get('orders', []))} (<code>${total_rev:.2f}</code>)\n"
        f"🏦 <b>AiToolShop Balance:</b> <code>${bal_val}</code>\n"
        f"⏳ <b>Pending Top-Ups:</b> {len(pending_deps)}\n"
        f"🎫 <b>Open Tickets:</b> {len(open_tkts)}</blockquote>\n\n"
        f"💡 <b>Quick Commands:</b>\n"
        f"• <code>/addbal USER_ID AMOUNT</code> — Credit wallet\n"
        f"• <code>/broadcast MESSAGE</code> — Message all users"
    )
    kb = {
        "inline_keyboard": [
            [{"text": f"⏳ Pending Deposits ({len(pending_deps)})", "callback_data": "adm_deps"}],
            [{"text": "📢 Broadcast New Stock to Channel", "callback_data": "adm_chan_sync"}],
            [{"text": "🏠 Home", "callback_data": "home"}]
        ]
    }
    if message_id:
        tg_api.edit_message(chat_id, message_id, text, reply_markup=kb)
    else:
        tg_api.send_message(chat_id, text, reply_markup=kb)


# ==============================================================================
# Update Processor
# ==============================================================================

def handle_update(upd):
    if "callback_query" in upd:
        cq = upd["callback_query"]
        cq_id = cq["id"]
        from_u = cq["from"]
        chat_id = str(cq["message"]["chat"]["id"])
        msg_id = cq["message"]["message_id"]
        data = cq.get("data", "")
        tg_api.answer_callback(cq_id)

        if data == "noop":
            return
        if data == "home":
            send_welcome_screen(chat_id, from_u)
        elif data.startswith("cats:"):
            show_categories(chat_id, message_id=msg_id)
        elif data.startswith("cat:"):
            _, ckey, pstr = data.split(":")
            show_category_products(chat_id, ckey, int(pstr), message_id=msg_id)
        elif data.startswith("prod:"):
            parts = data.split(":")
            pid = parts[1]
            bcat = parts[2] if len(parts) > 2 else "ai"
            bpg = int(parts[3]) if len(parts) > 3 else 0
            show_product_detail(chat_id, pid, bcat, bpg, message_id=msg_id)
        elif data.startswith("buy_confirm:"):
            _, pid, qstr = data.split(":")
            execute_purchase(chat_id, from_u, pid, int(qstr), message_id=msg_id)
        elif data == "search":
            def _s(db):
                u = ensure_user(db, from_u)
                u["state"] = "awaiting_search"
            update_db(_s)
            tg_api.send_message(chat_id, "🔍 <b>Search Catalog</b>\n\nSend the product name or keyword (e.g. <code>ChatGPT</code>, <code>Canva</code>, <code>Nord</code>):")
        elif data == "wallet":
            show_wallet(chat_id, from_u, message_id=msg_id)
        elif data == "topup":
            show_topup_methods(chat_id, message_id=msg_id)
        elif data.startswith("topup_m:"):
            mid = data.split(":", 1)[1]
            cfg = load_config()
            mobj = next((m for m in cfg.get("payment_methods", []) if m["id"] == mid), None)
            if not mobj:
                return
            def _st(db):
                u = ensure_user(db, from_u)
                u["state"] = "awaiting_topup_amount"
                u["state_data"] = {"method": mobj["name"]}
            update_db(_st)
            tg_api.edit_message(
                chat_id, msg_id,
                f"💳 <b>{tg_api.esc(mobj['name'])}</b>\n\n"
                f"<blockquote>{tg_api.esc(mobj['details'])}</blockquote>\n\n"
                f"1️⃣ Send your payment first.\n"
                f"2️⃣ Reply here with the <b>USD amount</b> you sent (e.g. <code>20</code>):",
                reply_markup={"inline_keyboard": [[{"text": "❌ Cancel", "callback_data": "wallet"}]]}
            )
        elif data.startswith("orders:"):
            pg = int(data.split(":")[1])
            show_orders_history(chat_id, pg, message_id=msg_id)
        elif data.startswith("ord_view:"):
            ref = data.split(":", 1)[1]
            db = load_db()
            o = next((x for x in db.get("orders", []) if x["order_ref"] == ref and str(x["tg_id"]) == chat_id), None)
            if o:
                tg_api.edit_message(
                    chat_id, msg_id,
                    f"🧾 <b>Order #{tg_api.esc(o['order_ref'])}</b>\n\n"
                    f"<blockquote>📦 <b>Product:</b> {tg_api.esc(o['product_name'])}\n"
                    f"🔢 <b>Qty:</b> {o['qty']} · 💵 <b>Total:</b> <code>${o['total_price']:.2f}</code>\n"
                    f"🕒 <b>Date:</b> {o['created_at']}</blockquote>\n\n"
                    f"🔐 <b>Credentials:</b>\n<blockquote>{o['delivery_html']}</blockquote>",
                    reply_markup={"inline_keyboard": [
                        [{"text": "🎫 Issue? Open Ticket", "callback_data": f"newticket:{o['order_ref']}"}],
                        [{"text": "⬅️ Back to Orders", "callback_data": "orders:0"}]
                    ]}
                )
        elif data == "profile":
            show_profile(chat_id, from_u, message_id=msg_id)
        elif data == "support":
            show_support_menu(chat_id, message_id=msg_id)
        elif data.startswith("newticket:"):
            ref = data.split(":", 1)[1]
            def _nt(db):
                u = ensure_user(db, from_u)
                u["state"] = "awaiting_ticket_msg"
                u["state_data"] = {"order_ref": "" if ref == "general" else ref}
            update_db(_nt)
            ref_txt = f" regarding Order <code>#{tg_api.esc(ref)}</code>" if ref != "general" else ""
            tg_api.send_message(chat_id, f"🎫 <b>New Support Ticket{ref_txt}</b>\n\nDescribe your issue or send a screenshot below — our admin will reply right here!")
        elif data.startswith("tkt_view:"):
            tid = data.split(":", 1)[1]
            db = load_db()
            t = db.get("tickets", {}).get(tid)
            if not t or str(t.get("tg_id")) != chat_id:
                return
            msgs = t.get("messages", [])[-8:]
            hist = "\n".join(
                f"{'🛡 <b>Support</b>' if m.get('is_admin') else '👤 <b>You</b>'} ({m.get('timestamp','')}):\n{tg_api.esc(m.get('text') or '[Photo]')}"
                for m in msgs
            )
            def _rt(db2):
                u = ensure_user(db2, from_u)
                if t.get("status") == "open":
                    u["state"] = "replying_ticket"
                    u["state_data"] = {"ticket_id": tid}
            update_db(_rt)
            tg_api.edit_message(
                chat_id, msg_id,
                f"🎫 <b>Ticket #{tid}</b> ({t.get('status','open').upper()})\n\n<blockquote>{hist}</blockquote>\n\n"
                + ("✍️ <i>Send your next message or screenshot below to reply:</i>" if t.get("status") == "open" else "🔒 <i>This ticket is closed.</i>"),
                reply_markup={"inline_keyboard": [[{"text": "⬅️ Back to Tickets", "callback_data": "support"}]]}
            )
        elif data == "adm_deps" and _is_admin(chat_id):
            db = load_db()
            pends = [d for d in db.get("deposits", []) if d.get("status") == "pending"]
            if not pends:
                tg_api.send_message(chat_id, "✅ No pending deposit requests.")
                return
            for d in pends[:10]:
                tg_api.send_message(
                    chat_id,
                    f"⏳ <b>Deposit Request #{d['id']}</b>\n"
                    f"👤 User: @{tg_api.esc(d.get('username') or d['tg_id'])} (<code>{d['tg_id']}</code>)\n"
                    f"💵 Amount: <b>${d['amount']:.2f}</b>\n"
                    f"💳 Method: {tg_api.esc(d['method'])}\n"
                    f"🧾 Proof: <code>{tg_api.esc(d.get('proof',''))}</code>",
                    reply_markup={"inline_keyboard": [[
                        {"text": "✅ Approve & Credit", "callback_data": f"dep_ok:{d['id']}"},
                        {"text": "❌ Reject", "callback_data": f"dep_no:{d['id']}"}
                    ]]}
                )
        elif data.startswith("dep_ok:") and _is_admin(chat_id):
            did = data.split(":", 1)[1]
            def _approve(db):
                for d in db.get("deposits", []):
                    if d["id"] == did and d["status"] == "pending":
                        d["status"] = "approved"
                        u = db.get("users", {}).get(str(d["tg_id"]))
                        if u:
                            u["balance"] = round(float(u.get("balance", 0.0)) + float(d["amount"]), 2)
                            return d, u["balance"]
                return None, None
            dep, new_bal = update_db(_approve)
            if dep:
                tg_api.edit_message(chat_id, msg_id, f"✅ Approved Deposit #{did} (<b>+${dep['amount']:.2f}</b> credited to <code>{dep['tg_id']}</code>)")
                tg_api.send_message(dep["tg_id"], f"🎉 <b>Wallet Top-Up Approved!</b>\n\n💵 <code>+${dep['amount']:.2f}</code> has been credited.\n👛 <b>New Balance:</b> <code>${new_bal:.2f}</code>")
        elif data.startswith("dep_no:") and _is_admin(chat_id):
            did = data.split(":", 1)[1]
            def _rej(db):
                for d in db.get("deposits", []):
                    if d["id"] == did and d["status"] == "pending":
                        d["status"] = "rejected"
                        return d
                return None
            dep = update_db(_rej)
            if dep:
                tg_api.edit_message(chat_id, msg_id, f"❌ Rejected Deposit #{did}.")
                tg_api.send_message(dep["tg_id"], f"❌ Your deposit request (#{did}) for <code>${dep['amount']:.2f}</code> was declined. Contact Support if you have questions.")
        elif data == "adm_chan_sync" and _is_admin(chat_id):
            res = sync_and_broadcast_catalog_updates(max_posts=5)
            tg_api.send_message(chat_id, f"📢 Channel Sync Result: <code>{res}</code>")
        return

    if "message" not in upd:
        return

    msg = upd["message"]
    chat = msg.get("chat", {})
    if chat.get("type") != "private":
        return

    from_u = msg["from"]
    chat_id = str(chat["id"])
    text = (msg.get("text") or msg.get("caption") or "").strip()
    photo_url = ""
    if msg.get("photo"):
        photo_url = tg_api.get_file_url(msg["photo"][-1]["file_id"])

    # Handle /start commands including deep links (/start prod_123)
    if text.startswith("/start"):
        def _clr(db):
            u = ensure_user(db, from_u)
            u["state"] = None
            u["state_data"] = {}
        update_db(_clr)
        parts = text.split(maxsplit=1)
        if len(parts) == 2 and parts[1].startswith("prod_"):
            pid = parts[1].replace("prod_", "", 1)
            tg_api.send_message(chat_id, "✨ Loading product...", reply_markup=_main_reply_keyboard(chat_id))
            show_product_detail(chat_id, pid)
            return
        send_welcome_screen(chat_id, from_u)
        return

    # Admin CLI commands
    if _is_admin(chat_id) and text.startswith("/addbal "):
        parts = text.split()
        if len(parts) == 3:
            target_uid, amt_str = parts[1], parts[2]
            try:
                amt = round(float(amt_str), 2)
                def _addb(db):
                    u = db.get("users", {}).get(str(target_uid))
                    if not u:
                        return None
                    u["balance"] = round(float(u.get("balance", 0.0)) + amt, 2)
                    return u["balance"]
                nb = update_db(_addb)
                if nb is not None:
                    tg_api.send_message(chat_id, f"✅ Credited <code>${amt:.2f}</code> to <code>{target_uid}</code>. New balance: <code>${nb:.2f}</code>")
                    tg_api.send_message(target_uid, f"🎉 <b>Balance Credited!</b>\n💵 <code>+${amt:.2f}</code> added to your wallet.\n👛 Balance: <code>${nb:.2f}</code>")
                else:
                    tg_api.send_message(chat_id, "❌ User ID not found in bot database.")
            except Exception as e:
                tg_api.send_message(chat_id, f"❌ Error: {e}")
        return

    if _is_admin(chat_id) and text.startswith("/broadcast "):
        bc_msg = text[len("/broadcast "):].strip()
        db = load_db()
        sent = 0
        for uid in db.get("users", {}).keys():
            r = tg_api.send_message(uid, f"📢 <b>Announcement</b>\n\n{tg_api.esc(bc_msg)}")
            if r.get("ok"):
                sent += 1
            time.sleep(0.05)
        tg_api.send_message(chat_id, f"✅ Broadcast sent to <b>{sent}</b> users.")
        return

    # Main ReplyKeyboard navigation buttons
    if text == "🛍️ Browse Store":
        show_categories(chat_id)
        return
    if text == "🔍 Search":
        def _s(db):
            u = ensure_user(db, from_u)
            u["state"] = "awaiting_search"
        update_db(_s)
        tg_api.send_message(chat_id, "🔍 Send the product name to search (e.g. <code>ChatGPT</code>, <code>Canva</code>, <code>Claude</code>):")
        return
    if text == "👛 My Wallet":
        show_wallet(chat_id, from_u)
        return
    if text == "📦 Order History":
        show_orders_history(chat_id, 0)
        return
    if text == "👤 VIP Profile":
        show_profile(chat_id, from_u)
        return
    if text == "🎫 Support":
        show_support_menu(chat_id)
        return
    if text == "👑 Admin Panel" and _is_admin(chat_id):
        show_admin_panel(chat_id)
        return

    # Stateful conversation handlers
    db = load_db()
    u = db.get("users", {}).get(chat_id) or {}
    state = u.get("state")
    sdata = u.get("state_data") or {}

    if state == "awaiting_search" and text:
        def _clr_s(db2):
            ensure_user(db2, from_u)["state"] = None
        update_db(_clr_s)
        q = text.lower()
        matches = [p for p in fetch_catalog() if p["in_stock"] and q in p["name"].lower()][:10]
        if not matches:
            tg_api.send_message(chat_id, f"❌ No in-stock products matched <code>{tg_api.esc(text)}</code>. Try another keyword!")
            return
        btns = [[{
            "text": f"💎 {p['name'][:34]} · ${p['price']:.2f}",
            "callback_data": f"prod:{p['id']}:{p['category']}:0"
        }] for p in matches]
        tg_api.send_message(chat_id, f"🔍 <b>Search Results for '{tg_api.esc(text)}'</b>:", reply_markup={"inline_keyboard": btns})
        return

    if state == "awaiting_topup_amount":
        try:
            amt = round(float(text.replace("$", "").strip()), 2)
            if amt < 1.0:
                raise ValueError("Minimum top-up is $1.00")
            def _nxt(db2):
                usr = ensure_user(db2, from_u)
                usr["state"] = "awaiting_topup_proof"
                usr["state_data"] = {"method": sdata.get("method", "Crypto"), "amount": amt}
            update_db(_nxt)
            tg_api.send_message(chat_id, f"✅ Amount: <code>${amt:.2f}</code>\n\n📸 Now send your <b>Payment Screenshot</b> or <b>Transaction ID (TXID)</b>:")
        except Exception:
            tg_api.send_message(chat_id, "⚠️ Please enter a valid USD number (minimum <code>1</code>, e.g. <code>15</code>).")
        return

    if state == "awaiting_topup_proof":
        proof = text or ("Screenshot attached" if photo_url else "")
        if not proof and not photo_url:
            tg_api.send_message(chat_id, "⚠️ Please send a Transaction ID or payment screenshot.")
            return
        dep_id = f"DEP{uuid.uuid4().hex[:6].upper()}"
        amt = float(sdata.get("amount", 0))
        method = sdata.get("method", "Crypto")
        now_str = egypt_now().strftime("%Y-%m-%d %I:%M %p")

        def _save_dep(db2):
            usr = ensure_user(db2, from_u)
            usr["state"] = None
            usr["state_data"] = {}
            dep = {
                "id": dep_id,
                "tg_id": chat_id,
                "username": usr.get("username", ""),
                "amount": amt,
                "method": method,
                "proof": f"{proof} {photo_url}".strip(),
                "status": "pending",
                "created_at": now_str
            }
            db2.setdefault("deposits", []).insert(0, dep)
            return dep

        dep = update_db(_save_dep)
        tg_api.send_message(
            chat_id,
            f"⏳ <b>Top-Up Request Submitted!</b>\n\n"
            f"<blockquote>🆔 <b>Ref:</b> <code>{dep_id}</code>\n"
            f"💵 <b>Amount:</b> <code>${amt:.2f}</code>\n"
            f"💳 <b>Method:</b> {tg_api.esc(method)}</blockquote>\n\n"
            f"🔔 Our team has been notified and will credit your balance shortly!"
        )
        # Notify all admins with instant Approve/Reject buttons
        cfg = load_config()
        for aid in cfg.get("admin_ids", []):
            adm_caption = (
                f"💰 <b>New Wallet Top-Up Request #{dep_id}</b>\n\n"
                f"👤 User: @{tg_api.esc(dep['username'] or chat_id)} (<code>{chat_id}</code>)\n"
                f"💵 Amount: <b>${amt:.2f}</b>\n"
                f"💳 Method: {tg_api.esc(method)}\n"
                f"🧾 Proof: <code>{tg_api.esc(proof)}</code>"
            )
            adm_kb = {"inline_keyboard": [[
                {"text": "✅ Approve & Credit", "callback_data": f"dep_ok:{dep_id}"},
                {"text": "❌ Reject", "callback_data": f"dep_no:{dep_id}"}
            ]]}
            if photo_url:
                tg_api.send_photo(aid, photo_url, caption=adm_caption, reply_markup=adm_kb)
            else:
                tg_api.send_message(aid, adm_caption, reply_markup=adm_kb)
        return

    if state in ("awaiting_ticket_msg", "replying_ticket") and (text or photo_url):
        now_str = egypt_now().strftime("%I:%M %p")
        now_iso = egypt_now().replace(tzinfo=None).isoformat()
        order_ref = sdata.get("order_ref", "")
        existing_tid = sdata.get("ticket_id") if state == "replying_ticket" else None

        def _save_tkt(db2):
            usr = ensure_user(db2, from_u)
            tickets = db2.setdefault("tickets", {})
            tid = existing_tid if (existing_tid and existing_tid in tickets) else f"TKT{uuid.uuid4().hex[:6].upper()}"
            msg_obj = {
                "id": f"tgm_{int(time.time() * 1000)}",
                "sender": "customer",
                "sender_name": f"@{usr['username']}" if usr.get("username") else usr.get("first_name", "Customer"),
                "text": text,
                "image": photo_url or None,
                "timestamp": now_str,
                "is_admin": False
            }
            if tid not in tickets:
                tickets[tid] = {
                    "id": tid,
                    "tg_id": chat_id,
                    "username": f"@{usr['username']}" if usr.get("username") else "",
                    "customer_name": usr.get("first_name", "Telegram User"),
                    "subject": (f"Order #{order_ref}" if order_ref else (text[:45] or "Support Inquiry")),
                    "order_ref": order_ref,
                    "status": "open",
                    "created_at": now_iso,
                    "updated_at": now_iso,
                    "unread_admin": 1,
                    "messages": [msg_obj]
                }
            else:
                t = tickets[tid]
                t["status"] = "open"
                t["updated_at"] = now_iso
                t["unread_admin"] = int(t.get("unread_admin", 0)) + 1
                t.setdefault("messages", []).append(msg_obj)

            usr["state"] = "replying_ticket"
            usr["state_data"] = {"ticket_id": tid}
            return tickets[tid], msg_obj

        tkt_obj, new_msg = update_db(_save_tkt)
        _push_ticket_to_sales_bridge(tkt_obj, new_msg)
        tg_api.send_message(
            chat_id,
            f"✅ <b>Message delivered to Support (Ticket #{tkt_obj['id']})!</b>\n<i>Our agent will reply to you right here shortly.</i>"
        )
        return

    # Default fallback
    send_welcome_screen(chat_id, from_u)


# ==============================================================================
# Flask Webhook & Cron Routes
# ==============================================================================

@app.route("/", methods=["GET"])
def bot_health():
    return jsonify({"status": "ok", "service": "Nova Digital Telegram Store Bot"})


@app.route("/webhook", methods=["POST"])
def telegram_webhook():
    cfg = load_config()
    sec = cfg.get("webhook_secret", "")
    if sec:
        hdr = request.headers.get("X-Telegram-Bot-Api-Secret-Token", "")
        if hdr and hdr != sec:
            return jsonify({"ok": False}), 403
    upd = request.get_json(silent=True) or {}
    try:
        handle_update(upd)
    except Exception as e:
        print(f"[Webhook Error] {e}")
    return jsonify({"ok": True})


@app.route("/cron/broadcast", methods=["GET", "POST"])
def cron_broadcast():
    return jsonify(sync_and_broadcast_catalog_updates())


if __name__ == "__main__":
    if "--broadcast" in sys.argv:
        print("Broadcast:", sync_and_broadcast_catalog_updates())
    elif "--polling" in sys.argv:
        print("🚀 Starting Nova Digital Telegram Bot in Polling Mode...")
        offset = None
        while True:
            try:
                res = tg_api.get_updates(offset=offset, timeout=25)
                if res.get("ok"):
                    for u in res.get("result", []):
                        offset = u["update_id"] + 1
                        handle_update(u)
                else:
                    time.sleep(3)
            except KeyboardInterrupt:
                break
            except Exception as e:
                print(f"[Polling Error] {e}")
                time.sleep(3)
    else:
        app.run(host="0.0.0.0", port=5050, debug=False)
