from pyrogram import Client, filters
from config import Config
from database import add_user, get_api_key, remove_user, get_db_connection
from streamhg_api import StreamHG
from queue_worker import add_to_queue, cancel_signals, user_queues
import os

app = Client(
    "streamhg_bot",
    api_id=Config.API_ID,
    api_hash=Config.API_HASH,
    bot_token=Config.BOT_TOKEN
)

@app.on_message(filters.command("start"))
async def start(client, message):
    await message.reply_text(
        "👋 **Welcome to StreamHG Uploader Bot!**\n\n"
        "1️⃣ Get your API Key from StreamHG settings.\n"
        "2️⃣ Send `/login API_KEY` to authorize.\n"
        "3️⃣ Send any video file to start uploading.\n\n"
        "**Features:**\n"
        "✅ Queue System\n"
        "✅ Speed Meter & Progress Bar\n"
        "✅ Cancel Support"
    )

@app.on_message(filters.command("login"))
async def login(client, message):
    if len(message.command) < 2:
        await message.reply_text("❌ Usage: `/login YOUR_API_KEY`")
        return
    
    api_key = message.command[1]
    
    # Validate API Key
    info = await StreamHG.get_account_info(api_key)
    if info.get("status") == 200:
        if add_user(message.from_user.id, api_key):
            result = info['result']
            await message.reply_text(
                f"✅ **Login Successful!**\n\n"
                f"👤 Login: `{result.get('login')}`\n"
                f"📧 Email: `{result.get('email')}`\n"
                f"💰 Balance: `{result.get('balance')}`"
            )
        else:
            await message.reply_text("❌ Database Error. Try again.")
    else:
        await message.reply_text("❌ Invalid API Key!")

@app.on_message(filters.command("logout"))
async def logout(client, message):
    if remove_user(message.from_user.id):
        await message.reply_text("✅ API Key removed.")
    else:
        await message.reply_text("❌ Error removing data.")

@app.on_message(filters.video | filters.document)
async def handle_video(client, message):
    user_id = message.from_user.id
    
    # Check if user is logged in
    if not get_api_key(user_id):
        await message.reply_text("🔒 You are not logged in. Use `/login API_KEY` first.")
        return

    # Check for file size or other validation if needed
    # Note: Pyrogram handles large files automatically via MTProto
    
    await add_to_queue(client, message, user_id)

@app.on_message(filters.command("cancel"))
async def cancel_command(client, message):
    user_id = message.from_user.id
    cancel_signals[user_id] = True
    await message.reply_text("🛑 Stopping current/pending tasks and clearing queue...")

@app.on_message(filters.command("clear"))
async def clear_queue(client, message):
    user_id = message.from_user.id
    if user_id in user_queues:
        q = user_queues[user_id]["queue"]
        while not q.empty():
            try:
                q.get_nowait()
                q.task_done()
            except:
                break
        await message.reply_text("🧹 Queue cleared.")
    else:
        await message.reply_text("📭 Queue is empty.")

@app.on_message(filters.command("status"))
async def status(client, message):
    user_id = message.from_user.id
    if user_id in user_queues:
        q_size = user_queues[user_id]["queue"].qsize()
        is_running = user_queues[user_id]["is_running"]
        await message.reply_text(f"📊 **Status**\nRunning: `{is_running}`\nFiles in Queue: `{q_size}`")
    else:
        await message.reply_text("💤 No active tasks.")

if __name__ == "__main__":
    if not os.path.exists("downloads"):
        os.makedirs("downloads")
    print("Bot Started...")
    app.run()