"""Entry point: Telegram shop bot with wallet, SePay auto top-up and admin panel."""
import os
import sys
import time
import traceback
from concurrent.futures import ThreadPoolExecutor


def load_env():
    """Read KEY=VALUE pairs from .env next to bot.py (token lives there)."""
    path = os.path.join(os.path.dirname(os.path.abspath(__file__)), ".env")
    if not os.path.exists(path):
        return
    try:
        with open(path, "r", encoding="utf-8") as f:
            for line in f:
                line = line.strip()
                if not line or line.startswith("#") or "=" not in line:
                    continue
                k, v = line.split("=", 1)
                os.environ.setdefault(k.strip(), v.strip().strip('"').strip("'"))
    except Exception as e:
        print("env load error:", e)


load_env()

import admin
import db
import i18n
import sepay
import shop
import tg
from i18n import money, t

POOL = ThreadPoolExecutor(max_workers=8)
OWNER = os.environ.get("ADMIN_ID", "").strip()


def log(*a):
    print(time.strftime("%H:%M:%S"), *a, flush=True)


def lang_of(uid):
    return shop.lang_of(uid)


def bootstrap_user(msg):
    frm = msg["from"]
    uid = frm["id"]
    payload = (msg.get("text") or "").split(" ", 1)[1].strip() if " " in (msg.get("text") or "") else ""
    ref_by = None
    if payload.startswith("ref_"):
        try:
            cand = int(payload[4:])
            if cand != uid:
                ref_by = cand
        except Exception:
            ref_by = None
    u = db.get_user(uid)
    is_new = u is None
    if is_new:
        # first ever user becomes owner if ADMIN_ID not configured
        if not OWNER and not db.q1("SELECT id FROM users WHERE is_admin=1"):
            u = db.ensure_user(uid, frm.get("username", ""), frm.get("first_name", ""), None)
            db.set_admin(uid)
        else:
            if ref_by and not db.get_user(ref_by):
                ref_by = None
            u = db.ensure_user(uid, frm.get("username", ""), frm.get("first_name", ""), ref_by)
            if ref_by:
                inviter = db.get_user(ref_by)
                if inviter:
                    tg.send(ref_by, "🎉 Bạn có người mới tham gia qua link: <b>%s</b>"
                            % tg.esc(frm.get("first_name") or str(uid)))
    else:
        db.ensure_user(uid, frm.get("username", ""), frm.get("first_name", ""), None)
    return db.get_user(uid), is_new, ref_by


def handle_message(msg):
    if "text" not in msg or not msg.get("from"):
        return
    text = msg["text"].strip()
    chat_id = msg["chat"]["id"]
    frm = msg["from"]
    uid = frm["id"]

    if text.startswith("/start"):
        user, is_new, ref_by = bootstrap_user(msg)
        if user["banned"]:
            tg.send(chat_id, t(user["lang"] or "vi", "banned"))
            return
        shop.show_home(uid, chat_id)
        if is_new and ref_by:
            inviter = db.get_user(ref_by)
            if inviter:
                tg.send(uid, t(user["lang"] or "vi", "ref_new_user",
                               name=tg.esc(inviter["first_name"] or inviter["username"] or ref_by)))
        return

    user = db.get_user(uid)
    if not user:
        user = db.ensure_user(uid, frm.get("username", ""), frm.get("first_name", ""), None)
    lang = user["lang"] or "vi"

    if user["banned"]:
        tg.send(chat_id, t(lang, "banned"))
        return

    if text.startswith("/admin"):
        if admin.is_admin(uid):
            db.clear_state(uid)
            admin.panel(chat_id)
        else:
            tg.send(chat_id, "⛔ Bạn không có quyền quản trị.")
        return
    if text.startswith("/help"):
        tg.send(chat_id, t(lang, "welcome", shop=db.get_setting("shop_name")), shop.home_kb(lang))
        return
    if text.startswith("/done") and admin.is_admin(uid):
        state, _ = db.get_state(uid)
        if state in ("a_pstock", "a_pstock_edit"):
            admin.handle_text(uid, chat_id, "/done")
            return
    if text.startswith("/cancel"):
        db.clear_state(uid)
        tg.send(chat_id, "✅ Đã huỷ thao tác.", shop.home_kb(lang))
        return

    # admin text flows first
    if admin.is_admin(uid):
        if admin.handle_text(uid, chat_id, text):
            return

    state, data = db.get_state(uid)
    if state == "search":
        db.clear_state(uid)
        shop.search_results(uid, chat_id, text)
        return
    if state == "topup_amount":
        db.clear_state(uid)
        raw = text.replace(".", "").replace(",", "").replace("đ", "").replace("d", "").strip()
        try:
            amount = int(raw)
        except Exception:
            amount = 0
        minimum = int(db.get_setting("min_topup", "10000") or 10000)
        if amount < minimum:
            db.set_state(uid, "topup_amount")
            tg.send(chat_id, t(lang, "topup_too_small", min=money(minimum)))
            return
        shop.create_topup(uid, chat_id, amount)
        return
    if state == "support_msg":
        db.clear_state(uid)
        db.x("INSERT INTO tickets(user_id,message,status,created_at) VALUES(?,?,'open',?)",
             (uid, text, db.now()))
        tg.send(chat_id, t(lang, "support_sent"), tg.ikb([[(t(lang, "menu_home"), "home")]]))
        for adm in db.q("SELECT id FROM users WHERE is_admin=1"):
            tg.send(adm["id"], "💬 <b>Hỗ trợ mới</b>\nUser <code>%s</code> (@%s):\n\n%s"
                    % (uid, tg.esc(frm.get("username") or "-"), tg.esc(text[:1500])))
        return
    if state == "coupon_input":
        db.clear_state(uid)
        code = text.strip().upper()
        c = db.coupon(code)
        if not c:
            tg.send(chat_id, t(lang, "coupon_bad"), tg.ikb([[(t(lang, "menu_home"), "home")]]))
            return
        db.x("UPDATE users SET coupon=? WHERE id=?", (code, uid))
        tg.send(chat_id, t(lang, "coupon_ok", code=code), tg.ikb([[(t(lang, "menu_home"), "home")]]))
        return

    tg.send(chat_id, t(lang, "unknown"), shop.home_kb(lang))


def handle_cb(cb):
    data = cb.get("data") or ""
    uid = cb["from"]["id"]
    chat_id = cb["message"]["chat"]["id"] if cb.get("message") else uid
    msg_id = cb["message"]["message_id"] if cb.get("message") else None
    tg.answer_cb(cb["id"])

    user = db.get_user(uid)
    if not user:
        user = db.ensure_user(uid, cb["from"].get("username", ""), cb["from"].get("first_name", ""))
    if user["banned"]:
        return
    lang = user["lang"] or "vi"

    try:
        if data == "home":
            db.clear_state(uid)
            shop.show_home(uid, chat_id, msg_id)
        elif data == "cats":
            shop.show_categories(uid, chat_id, msg_id)
        elif data.startswith("cat:"):
            _, cid, page = data.split(":")
            shop.show_products(uid, chat_id, int(cid), int(page), msg_id)
        elif data.startswith("prod:"):
            shop.product_card(uid, chat_id, int(data.split(":")[1]), msg_id)
        elif data.startswith("buy:"):
            shop.confirm_buy(uid, chat_id, int(data.split(":")[1]), msg_id)
        elif data.startswith("buyok:"):
            shop.do_buy(uid, chat_id, int(data.split(":")[1]), msg_id)
        elif data == "noop":
            pass
        elif data == "topup":
            shop.show_topup(uid, chat_id, msg_id)
        elif data.startswith("tup:"):
            val = data.split(":", 1)[1]
            if val == "custom":
                db.set_state(uid, "topup_amount")
                tg.send(chat_id, t(lang, "topup_enter", min=money(db.get_setting("min_topup", "10000"))))
            else:
                shop.create_topup(uid, chat_id, int(val), msg_id)
        elif data.startswith("chk:"):
            code = data.split(":", 1)[1]
            sepay.kick()
            inv = db.invoice_by_code(code)
            if inv and inv["status"] == "paid":
                u2 = db.get_user(uid)
                tg.send(chat_id, t(lang, "topup_paid", amount=money(inv["amount"]),
                                   balance=money(u2["balance"])))
            else:
                tg.send(chat_id, t(lang, "topup_check_sent"))
        elif data == "balance":
            shop.show_balance(uid, chat_id, msg_id)
        elif data == "orders":
            shop.show_orders(uid, chat_id, msg_id)
        elif data == "ref":
            shop.show_ref(uid, chat_id, msg_id)
        elif data == "lang":
            shop.show_lang(uid, chat_id, msg_id)
        elif data.startswith("lang:"):
            db.set_lang(uid, data.split(":")[1])
            shop.show_home(uid, chat_id, msg_id)
        elif data == "search":
            db.set_state(uid, "search")
            tg.send(chat_id, t(lang, "search_prompt"))
        elif data == "support":
            sup = db.get_setting("support")
            kb = tg.ikb([[(t(lang, "menu_home"), "home")]])
            if sup and (sup.startswith("@") or sup.startswith("http")):
                kb = tg.ikb([[(t(lang, "menu_support"), "url:" + (sup if sup.startswith("http") else "https://t.me/" + sup[1:]))],
                             [(t(lang, "menu_home"), "home")]])
            db.set_state(uid, "support_msg")
            tg.send(chat_id, t(lang, "support_prompt"), kb)
        elif data == "coupon":
            c = db.get_user(uid)["coupon"]
            if c:
                tg.send(chat_id, "🎟 Mã đang lưu: <b>%s</b> (sẽ áp dụng khi mua)." % tg.esc(c))
            db.set_state(uid, "coupon_input")
            tg.send(chat_id, t(lang, "coupon_prompt"))
        elif data.startswith("adm:"):
            if not admin.is_admin(uid):
                return
            handle_admin_cb(uid, chat_id, msg_id, data)
    except Exception as e:
        log("cb error", data, e)
        traceback.print_exc()


def handle_admin_cb(uid, chat_id, msg_id, data):
    parts = data.split(":")
    act = parts[1] if len(parts) > 1 else ""

    if act == "prods":
        admin.products_list(chat_id, int(parts[2]) if len(parts) > 2 else 0, msg_id)
    elif act == "p":
        admin.product_panel(chat_id, int(parts[2]), msg_id)
    elif act == "addp":
        db.set_state(uid, "a_pname", {})
        tg.send(chat_id, "➕ <b>Thêm sản phẩm</b>\n\nNhập TÊN sản phẩm:")
    elif act == "pcat":
        state, sdata = db.get_state(uid)
        sdata["cat_id"] = int(parts[2])
        db.set_state(uid, "a_pdesc", sdata)
        tg.send(chat_id, "📝 Nhập mô tả sản phẩm (gõ /skip để bỏ qua):")
    elif act == "newcat":
        state, sdata = db.get_state(uid)
        db.set_state(uid, "a_catnew", sdata)
        tg.send(chat_id, "📂 Nhập tên danh mục mới:")
    elif act == "pprice":
        db.set_state(uid, "a_pprice_edit", {"pid": int(parts[2])})
        tg.send(chat_id, "💰 Nhập giá mới (VNĐ):")
    elif act == "pname":
        db.set_state(uid, "a_pname_edit", {"pid": int(parts[2])})
        tg.send(chat_id, "✏️ Nhập tên mới:")
    elif act == "pdesc":
        db.set_state(uid, "a_pdesc_edit", {"pid": int(parts[2])})
        tg.send(chat_id, "📝 Nhập mô tả mới:")
    elif act == "pstock":
        db.set_state(uid, "a_pstock_edit", {"pid": int(parts[2])})
        tg.send(chat_id, "📦 Gửi kho (mỗi dòng 1 mục), xong bấm /done:")
    elif act == "ptoggle":
        pid = int(parts[2])
        p = db.product(pid)
        db.x("UPDATE products SET active=? WHERE id=?", (0 if p["active"] else 1, pid))
        admin.product_panel(chat_id, pid, msg_id)
    elif act in ("pdel",):
        pid = int(parts[2])
        db.x("UPDATE products SET active=0 WHERE id=?", (pid,))
        admin.products_list(chat_id, 0, msg_id)
    elif act == "settings":
        admin.settings_panel(chat_id, msg_id)
    elif act == "set":
        key = parts[2]
        db.set_state(uid, "a_set", {"key": key})
        hints = {
            "bank_name": "VD: MB Bank, Vietcombank, Techcombank...",
            "bank_account": "Số tài khoản nhận tiền",
            "bank_holder": "Tên chủ tài khoản (in hoa không dấu)",
            "sepay_token": "Dán API token SePay (my.sepay.vn → Cấu hình → API)",
            "sepay_account": "Số TK dùng để đối soát (để trống = mọi TK)",
            "ref_percent": "Phần trăm hoa hồng, VD 5",
            "topup_amounts": "Các mệnh giá, cách nhau dấu phẩy: 20000,50000,100000",
            "shop_name": "Tên shop hiển thị",
            "support": "@username_admin hoặc link",
            "bank_note": "Ghi chú hiển thị khi chuyển khoản",
        }
        tg.send(chat_id, "⚙️ Nhập giá trị mới cho <b>%s</b>\n\n%s" % (key, hints.get(key, "")))
    elif act == "sepaycheck":
        n = sepay.process_once()
        tg.send(chat_id, "🔄 Đã kiểm tra SePay. Giao dịch mới khớp: <b>%d</b>" % n)
    elif act == "invs":
        admin.invoices_panel(chat_id, msg_id)
    elif act == "invok":
        code = parts[2]
        inv = db.mark_invoice_paid(code, "manual")
        if inv:
            u = db.get_user(inv["user_id"])
            tg.send(inv["user_id"], t(u["lang"] or "vi", "topup_paid",
                                       amount=money(inv["amount"]), balance=money(u["balance"])))
            tg.send(chat_id, "✅ Đã duyệt %s" % code)
        else:
            tg.send(chat_id, "⚠️ Không tìm thấy hoặc đã duyệt rồi.")
        admin.invoices_panel(chat_id, msg_id)
    elif act == "orders":
        admin.orders_panel(chat_id, msg_id)
    elif act == "users":
        db.set_state(uid, "a_finduser", {})
        tg.send(chat_id, "👥 Nhập ID người dùng cần xem:")
    elif act == "user":
        admin.user_panel(chat_id, int(parts[2]), msg_id)
    elif act == "bal":
        target, sign = int(parts[2]), int(parts[3])
        db.set_state(uid, "a_balance", {"uid": target, "sign": sign})
        tg.send(chat_id, "💰 Nhập số tiền cần %s:" % ("cộng" if sign > 0 else "trừ"))
    elif act == "ban":
        target = int(parts[2])
        u = db.get_user(target)
        db.x("UPDATE users SET banned=? WHERE id=?", (0 if u["banned"] else 1, target))
        admin.user_panel(chat_id, target, msg_id)
    elif act == "mkgadm":
        target = int(parts[2])
        db.set_admin(target, 1)
        tg.send(chat_id, "✅ Đã cấp quyền admin cho %s" % target)
    elif act == "coupons":
        admin.coupons_panel(chat_id, msg_id)
    elif act == "newcoupon":
        db.set_state(uid, "a_newcoupon", {})
        tg.send(chat_id, "🎟 Nhập mã theo dạng:\n<code>GIAM10 10</code> (giảm 10%)\n"
                         "<code>GIAM20K -20000</code> (giảm 20.000đ)\n"
                         "<code>GIAM10 10 50</code> (giới hạn 50 lượt)")
    elif act == "bc":
        db.set_state(uid, "a_bc", {})
        tg.send(chat_id, "📢 Nhập nội dung broadcast (gửi tới tất cả người dùng):")
    elif act == "tickets":
        admin.tickets_panel(chat_id, msg_id)
    elif act == "reply":
        db.set_state(uid, "a_reply", {"uid": int(parts[2])})
        tg.send(chat_id, "↩️ Nhập nội dung trả lời:")
    elif act == "":
        admin.panel(chat_id, msg_id)


def handle_update(update):
    try:
        if "message" in update:
            handle_message(update["message"])
        elif "callback_query" in update:
            handle_cb(update["callback_query"])
    except Exception as e:
        log("update error", e)
        traceback.print_exc()


def main():
    if not tg.TOKEN:
        print("BOT_TOKEN missing", flush=True)
        sys.exit(1)
    db.init()
    if OWNER:
        try:
            oid = int(OWNER)
            db.ensure_user(oid, "", "Owner")
            db.set_admin(oid)
        except Exception:
            pass
    me = tg.call("getMe")
    if me.get("ok"):
        tg.BOT_USERNAME = me["result"].get("username", "")
        log("bot @%s ready" % tg.BOT_USERNAME)
    else:
        log("getMe failed:", me)
        desc = str(me.get("description", ""))
        if "Unauthorized" in desc or "Not Found" in desc:
            log("invalid bot token, exiting")
            sys.exit(2)
        time.sleep(5)
    try:
        tg.call("setMyCommands", commands=[
            {"command": "start", "description": "Mở menu shop"},
            {"command": "admin", "description": "Quản trị shop"},
        ])
    except Exception:
        pass
    sepay.start()
    log("shop bot started")
    offset = 0
    while True:
        try:
            updates = tg.get_updates(offset)
            for u in updates:
                offset = max(offset, u["update_id"] + 1)
                POOL.submit(handle_update, u)
            if not updates:
                time.sleep(0.3)
        except Exception as e:
            log("poll error", e)
            time.sleep(3)


if __name__ == "__main__":
    main()
