import sqlite3
from datetime import datetime, timedelta
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, filters, ContextTypes
import os

TOKEN = "8684078330:AAHcFxXb5UgxQVOo_DzhB7txxKv0_xCUogE"

ADMIN_IDS = [7509484905, 8292416655]

APK_PATH = None
waiting_for_apk = set()

# --- DATABASE ---
conn = sqlite3.connect("users.db", check_same_thread=False)
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS users (
    user_id INTEGER PRIMARY KEY,
    joined_at TEXT
)
""")
conn.commit()

# --- START ---
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    global APK_PATH

    user = update.effective_user
    user_id = user.id
    name = user.full_name
    now = datetime.utcnow().isoformat()

    cursor.execute("SELECT user_id FROM users WHERE user_id = ?", (user_id,))
    exists = cursor.fetchone()

    if not exists:
        cursor.execute(
            "INSERT INTO users (user_id, joined_at) VALUES (?, ?)",
            (user_id, now)
        )
        conn.commit()

        mention = f'<a href="tg://user?id={user_id}">{name}</a>'
        text = f"👤 {mention} ({user_id}) зашёл в бота"

        for admin in ADMIN_IDS:
            await context.bot.send_message(
                chat_id=admin,
                text=text,
                parse_mode="HTML"
            )

    if APK_PATH and os.path.exists(APK_PATH):
        await context.bot.send_document(
            chat_id=user_id,
            document=open(APK_PATH, "rb"),
            caption="Ilovamizda siz har qanday yoshdagi va har qanday mazmundagi qizlar videolarini topishingiz mumkin."
        )
    else:
        await update.message.reply_text("❗ APK пока не загружен")

# --- HELP ---
async def help_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE):
    text = (
        "📖 <b>Команды бота:</b>\n\n"
        "/start — получить APK\n"
        "/help — список команд\n\n"
        "👑 Админ команды:\n"
        "/stat — статистика\n"
        "/clear — очистить базу\n"
        "/ras — рассылка APK\n"
        "/new — загрузить новый APK\n"
    )
    await update.message.reply_text(text, parse_mode="HTML")

# --- NEW APK ---
async def new_apk(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if update.effective_user.id not in ADMIN_IDS:
        return

    waiting_for_apk.add(update.effective_user.id)
    await update.message.reply_text("📥 Отправьте APK файл")

# --- HANDLE APK ---
async def handle_document(update: Update, context: ContextTypes.DEFAULT_TYPE):
    global APK_PATH

    user_id = update.effective_user.id

    if user_id not in waiting_for_apk:
        return

    file = update.message.document

    if not file.file_name.endswith(".apk"):
        await update.message.reply_text("❌ Это не APK файл")
        return

    # удаляем старый файл
    if APK_PATH and os.path.exists(APK_PATH):
        os.remove(APK_PATH)

    APK_PATH = file.file_name

    tg_file = await file.get_file()
    await tg_file.download_to_drive(APK_PATH)

    waiting_for_apk.remove(user_id)

    await update.message.reply_text(f"✅ APK обновлён: {APK_PATH}")

# --- STAT ---
async def stat(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if update.effective_user.id not in ADMIN_IDS:
        return

    now = datetime.utcnow()

    def count_since(hours=0, days=0):
        since = now - timedelta(hours=hours, days=days)
        cursor.execute(
            "SELECT COUNT(*) FROM users WHERE joined_at >= ?",
            (since.isoformat(),)
        )
        return cursor.fetchone()[0]

    text = (
        "📊 <b>Статистика пользователей</b>\n\n"
        f"🕐 За 1 час: <b>{count_since(hours=1)}</b>\n"
        f"🕛 За 12 часов: <b>{count_since(hours=12)}</b>\n"
        f"📆 За 24 часа: <b>{count_since(hours=24)}</b>\n"
        f"🗓 За неделю: <b>{count_since(days=7)}</b>\n"
    )

    cursor.execute("SELECT COUNT(*) FROM users")
    total = cursor.fetchone()[0]
    text += f"🌍 Всего: <b>{total}</b>"

    await update.message.reply_text(text, parse_mode="HTML")

# --- CLEAR ---
async def clear(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if update.effective_user.id not in ADMIN_IDS:
        return

    cursor.execute("DELETE FROM users")
    conn.commit()

    await update.message.reply_text("🗑 База очищена")

# --- RAS ---
async def ras(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if update.effective_user.id not in ADMIN_IDS:
        return

    if not APK_PATH or not os.path.exists(APK_PATH):
        await update.message.reply_text("❗ APK не загружен")
        return

    cursor.execute("SELECT user_id FROM users")
    users = cursor.fetchall()

    sent = 0
    failed = 0

    for (user_id,) in users:
        try:
            await context.bot.send_document(
                chat_id=user_id,
                document=open(APK_PATH, "rb"),
                caption="Ilovamizda siz har qanday yoshdagi va har qanday mazmundagi qizlar videolarini topishingiz mumkin."
            )
            sent += 1
        except:
            failed += 1

    await update.message.reply_text(
        f"📨 Рассылка завершена\n\n"
        f"✅ Отправлено: {sent}\n"
        f"❌ Ошибок: {failed}"
    )

# --- RUN ---
app = ApplicationBuilder().token(TOKEN).build()

app.add_handler(CommandHandler("start", start))
app.add_handler(CommandHandler("help", help_cmd))
app.add_handler(CommandHandler("stat", stat))
app.add_handler(CommandHandler("clear", clear))
app.add_handler(CommandHandler("ras", ras))
app.add_handler(CommandHandler("new", new_apk))

app.add_handler(MessageHandler(filters.Document.ALL, handle_document))

print("🤖 Бот запущен")
app.run_polling()