"""
bot/bot_server.py — Telegram Bot v2 (Inline Buttons + Payment Flow)
Run:  python bot/bot_server.py
"""

import os
import sys
from pathlib import Path
from dotenv import load_dotenv

sys.path.insert(0, str(Path(__file__).parent.parent))

from bot.keygen import generate_key, decode_key
from bot import db

load_dotenv(Path(__file__).parent.parent / ".env")

BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN", "")
ADMIN_ID = int(os.getenv("TELEGRAM_ADMIN_ID", "0"))
ADMIN_USERNAME = os.getenv("ADMIN_USERNAME", "your_username")

# Bank
BANK_NAME = os.getenv("BANK_NAME", "ABA Bank")
BANK_ACCOUNT = os.getenv("BANK_ACCOUNT", "000 000 000")
BANK_HOLDER = os.getenv("BANK_HOLDER", "Your Name")
PAYMENT_NOTE = os.getenv("PAYMENT_NOTE", "YT Analyzer License")

if not BOT_TOKEN or not ADMIN_ID:
    print("X Set TELEGRAM_BOT_TOKEN and TELEGRAM_ADMIN_ID in .env")
    sys.exit(1)

try:
    from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
    from telegram.ext import (
        Application, CommandHandler, MessageHandler,
        CallbackQueryHandler, ContextTypes, filters,
    )
except ImportError:
    print("X Install: pip install python-telegram-bot")
    sys.exit(1)


# =====================================================
# PLANS
# =====================================================
PLANS = {
    "demo":  {"name": "DEMO",  "days": 7,     "price": "Free",  "emoji": "🆓", "label": "Free Trial (7 days)"},
    "trial": {"name": "TRIAL", "days": 30,    "price": "$3.50", "emoji": "📅", "label": "30 Days"},
    "pro":   {"name": "PRO",   "days": 365,   "price": "$25",   "emoji": "💎", "label": "1 Year"},
    "vip":   {"name": "VIP",   "days": 36500, "price": "$120",  "emoji": "👑", "label": "Lifetime"},
}


def _plan_keyboard() -> InlineKeyboardMarkup:
    buttons = [
        [InlineKeyboardButton(f"🆓 DEMO — Free Trial (7 days)", callback_data="plan_demo")],
        [InlineKeyboardButton(f"📅 TRIAL — 30 Days — $3.50", callback_data="plan_trial")],
        [InlineKeyboardButton(f"💎 PRO — 1 Year — $25", callback_data="plan_pro")],
        [InlineKeyboardButton(f"👑 VIP — Lifetime — $120", callback_data="plan_vip")],
    ]
    return InlineKeyboardMarkup(buttons)


# =====================================================
# USER COMMANDS
# =====================================================
async def cmd_start(update: Update, ctx: ContextTypes.DEFAULT_TYPE):
    user = update.effective_user
    db.upsert_user(user.id, user.full_name)

    lines = [
        "🎬 Welcome to ytkeys License Bot",
        "",
        f"Hi {user.full_name}! 👋",
        f"Your Telegram ID: {user.id}",
        "",
        "====================",
        "💰 CHOOSE YOUR PLAN",
        "====================",
        "",
        "Click a plan button below to continue:",
    ]

    await update.message.reply_text(
        "\n".join(lines),
        reply_markup=_plan_keyboard(),
    )


async def on_plan_selected(update: Update, ctx: ContextTypes.DEFAULT_TYPE):
    """Handle plan button click"""
    query = update.callback_query
    await query.answer()

    user = query.from_user
    data = query.data  # e.g. "plan_pro"

    plan_key = data.replace("plan_", "")
    if plan_key not in PLANS:
        await query.edit_message_text("❌ Invalid plan")
        return

    plan = PLANS[plan_key]

    # ===== Notify admin =====
    if ADMIN_ID and user.id != ADMIN_ID:
        try:
            await ctx.bot.send_message(
                ADMIN_ID,
                f"🔔 NEW PLAN REQUEST\n\n"
                f"👤 Name: {user.full_name}\n"
                f"🆔 ID: {user.id}\n"
                f"📱 Username: @{user.username or 'none'}\n\n"
                f"💎 Plan: {plan['name']} ({plan['label']})\n"
                f"💰 Price: {plan['price']}\n"
                f"📅 Days: {plan['days']}\n\n"
                f"✅ Approve:\n"
                f"/approve {user.id} {plan['name']} {plan['days']}",
            )
        except Exception as e:
            print(f"Admin notify failed: {e}")

    # ===== Show payment info to user =====
    if plan["price"] == "Free":
        # Free plan — direct to admin
        text = (
            f"🆓 DEMO — Free Trial\n\n"
            f"Plan: {plan['name']} ({plan['days']} days)\n"
            f"Price: FREE\n\n"
            f"━━━━━━━━━━━━━━━━━━━━━━\n"
            f"Your request has been sent to admin.\n"
            f"You'll receive your License Key shortly.\n\n"
            f"📞 Contact: @{ADMIN_USERNAME}"
        )
    else:
        text = (
            f"{plan['emoji']} {plan['name']} — {plan['label']}\n\n"
            f"Plan: {plan['name']}\n"
            f"Duration: {plan['days']} days\n"
            f"Price: {plan['price']}\n\n"
            f"━━━━━━━━━━━━━━━━━━━━━━\n"
            f"💳 PAYMENT DETAILS\n"
            f"━━━━━━━━━━━━━━━━━━━━━━\n\n"
            f"🏦 Bank: {BANK_NAME}\n"
            f"💳 Account: {BANK_ACCOUNT}\n"
            f"👤 Holder: {BANK_HOLDER}\n"
            f"📝 Note: {PAYMENT_NOTE}\n\n"
            f"━━━━━━━━━━━━━━━━━━━━━━\n"
            f"✅ After payment:\n"
            f"Send screenshot to @{ADMIN_USERNAME}\n\n"
            f"Your License Key will be sent to you here."
        )

    # Send as new message (keep buttons visible in old message)
    await ctx.bot.send_message(
        chat_id=user.id,
        text=text,
    )


async def cmd_myinfo(update: Update, ctx: ContextTypes.DEFAULT_TYPE):
    user = update.effective_user
    u = db.get_user(user.id)
    if not u or not u.get("license_key"):
        await update.message.reply_text(
            "❌ No active license.\nSend /start to choose a plan."
        )
        return

    lines = [
        "📋 Your Account",
        "",
        f"👤 Name: {u['telegram_name']}",
        f"🔑 Plan: {u.get('plan', '-')}",
        f"📅 Expires: {(u.get('expires_at') or '-')[:10]}",
        f"✅ Status: {'Active' if u['is_active'] else 'Banned'}",
        f"🖥 HWID: {u.get('hwid') or 'Not bound'}",
        "",
        "🔑 License Key:",
        f"  {u['license_key']}",
    ]
    await update.message.reply_text("\n".join(lines))


async def cmd_plans(update: Update, ctx: ContextTypes.DEFAULT_TYPE):
    """Show plans again"""
    await update.message.reply_text(
        "💰 Choose your plan:",
        reply_markup=_plan_keyboard(),
    )


async def cmd_help(update: Update, ctx: ContextTypes.DEFAULT_TYPE):
    if _is_admin(update.effective_user.id):
        msg = (
            "🔧 ADMIN COMMANDS\n\n"
            "/start — Welcome + plans\n"
            "/plans — Show plan buttons\n"
            "/myinfo — Your account\n"
            "/approve <tg_id> <PLAN> <days>\n"
            "/ban <tg_id> — Ban user\n"
            "/unban <tg_id> — Unban\n"
            "/list — Latest 30 users\n"
            "/stats — Statistics"
        )
    else:
        msg = (
            "📖 USER COMMANDS\n\n"
            "/start — Welcome + choose plan\n"
            "/plans — Show plans\n"
            "/myinfo — Your license info\n"
            "/help — This help"
        )
    await update.message.reply_text(msg)


# =====================================================
# ADMIN COMMANDS
# =====================================================
def _is_admin(uid: int) -> bool:
    return uid == ADMIN_ID


async def cmd_approve(update: Update, ctx: ContextTypes.DEFAULT_TYPE):
    if not _is_admin(update.effective_user.id):
        return

    args = ctx.args
    if len(args) < 3:
        await update.message.reply_text(
            "Usage: /approve <tg_id> <PLAN> <days>\n\n"
            "Example:\n"
            "/approve 7551405503 PRO 365"
        )
        return

    try:
        tg_id = int(args[0])
        plan = args[1].upper()
        days = int(args[2])
    except Exception:
        await update.message.reply_text("❌ Invalid arguments")
        return

    user = db.get_user(tg_id)
    if not user:
        try:
            db.upsert_user(tg_id, f"User_{tg_id}")
            user = db.get_user(tg_id)
        except Exception:
            pass

    if not user:
        await update.message.reply_text(f"❌ User {tg_id} not found")
        return

    key = generate_key(plan, days)
    info = decode_key(key)
    db.set_license(tg_id, key, plan, info["expiry"])

    await update.message.reply_text(
        f"✅ APPROVED\n\n"
        f"👤 User: {user.get('telegram_name', '-')}\n"
        f"🔑 Key: {key}\n"
        f"📅 Expires: {info['expiry'][:10]}\n"
        f"💎 Plan: {plan}"
    )

    try:
        await ctx.bot.send_message(
            tg_id,
            f"🎉 LICENSE ACTIVATED!\n\n"
            f"🔑 Your License Key:\n"
            f"  {key}\n\n"
            f"📅 Expires: {info['expiry'][:10]}\n"
            f"💎 Plan: {plan}\n\n"
            f"📋 Copy the key → paste in YT Analyzer Pro app."
        )
    except Exception as e:
        await update.message.reply_text(f"⚠️ Could not notify user: {e}")


async def cmd_list(update: Update, ctx: ContextTypes.DEFAULT_TYPE):
    if not _is_admin(update.effective_user.id):
        return

    users = db.list_users(30)
    if not users:
        await update.message.reply_text("No users yet")
        return

    lines = ["📋 Recent Users (30)", ""]
    for u in users:
        status = "✅" if u["is_active"] else "❌"
        plan = u.get("plan") or "—"
        lines.append(f"{status} {u['telegram_id']} — {u['telegram_name'][:20]} — {plan}")

    stats = db.count_users()
    lines.append("")
    lines.append(f"📊 Total: {stats['total']} | Active: {stats['active']}")

    await update.message.reply_text("\n".join(lines))


async def cmd_ban(update: Update, ctx: ContextTypes.DEFAULT_TYPE):
    if not _is_admin(update.effective_user.id):
        return
    if not ctx.args:
        await update.message.reply_text("Usage: /ban <tg_id>")
        return
    try:
        tg_id = int(ctx.args[0])
    except Exception:
        await update.message.reply_text("Invalid ID")
        return
    db.ban_user(tg_id)
    await update.message.reply_text(f"✅ Banned: {tg_id}")


async def cmd_unban(update: Update, ctx: ContextTypes.DEFAULT_TYPE):
    if not _is_admin(update.effective_user.id):
        return
    if not ctx.args:
        await update.message.reply_text("Usage: /unban <tg_id>")
        return
    try:
        tg_id = int(ctx.args[0])
    except Exception:
        await update.message.reply_text("Invalid ID")
        return
    db.unban_user(tg_id)
    await update.message.reply_text(f"✅ Unbanned: {tg_id}")


async def cmd_stats(update: Update, ctx: ContextTypes.DEFAULT_TYPE):
    if not _is_admin(update.effective_user.id):
        return
    s = db.count_users()
    await update.message.reply_text(
        f"📊 STATISTICS\n\n"
        f"👥 Total Users: {s['total']}\n"
        f"✅ Active: {s['active']}\n"
        f"❌ Banned: {s['total'] - s['active']}"
    )


async def cmd_unknown(update: Update, ctx: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text("❓ Unknown command. Send /help")


# =====================================================
# MAIN
# =====================================================
def main():
    print("=" * 60)
    print("  YTKEYS LICENSE BOT v2")
    print("=" * 60)
    print(f"  Admin ID: {ADMIN_ID}")
    print(f"  Admin User: @{ADMIN_USERNAME}")
    print(f"  Bank: {BANK_NAME} — {BANK_ACCOUNT}")
    print(f"  DB: {db.DB_PATH}")
    print("  Starting bot... (Ctrl+C to stop)")
    print("=" * 60)

    app = Application.builder().token(BOT_TOKEN).build()

    # Commands
    app.add_handler(CommandHandler("start", cmd_start))
    app.add_handler(CommandHandler("plans", cmd_plans))
    app.add_handler(CommandHandler("help", cmd_help))
    app.add_handler(CommandHandler("myinfo", cmd_myinfo))
    app.add_handler(CommandHandler("approve", cmd_approve))
    app.add_handler(CommandHandler("ban", cmd_ban))
    app.add_handler(CommandHandler("unban", cmd_unban))
    app.add_handler(CommandHandler("list", cmd_list))
    app.add_handler(CommandHandler("stats", cmd_stats))

    # Inline button callbacks
    app.add_handler(CallbackQueryHandler(on_plan_selected, pattern="^plan_"))

    # Fallback
    app.add_handler(MessageHandler(filters.COMMAND, cmd_unknown))

    app.run_polling(allowed_updates=Update.ALL_TYPES)


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n👋 Bot stopped")