# Debug version with logging
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes
from database import JokeDatabase
import os
import logging

# Enable detailed logging
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.DEBUG  # Changed to DEBUG
)
logger = logging.getLogger(__name__)

BOT_TOKEN = "7864875699:AAEWf6ff1DYNzPvW6Dbn7D2W5aavg9KPhgY"
db = JokeDatabase()

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    logger.info(f"📱 /start from user: {update.effective_user.username}")
    await update.message.reply_text("🤖 Hi! I'm your Joke Bot!\nCommands: /joke, /addjoke")

async def get_random_joke(update: Update, context: ContextTypes.DEFAULT_TYPE):
    logger.info(f"🎲 /joke from user: {update.effective_user.username}")
    joke = db.get_random_joke()
    
    if not joke:
        await update.message.reply_text("No jokes yet! Use /addjoke to add one.")
        return
    
    await update.message.reply_text(joke['joke_text'])

async def add_new_joke(update: Update, context: ContextTypes.DEFAULT_TYPE):
    logger.info(f"➕ /addjoke from user: {update.effective_user.username}")
    logger.info(f"   Args: {context.args}")
    
    if not context.args:
        await update.message.reply_text("Usage: /addjoke [your joke]")
        return
    
    joke_text = " ".join(context.args)
    user = update.effective_user
    
    logger.info(f"   User ID: {user.id}, Username: {user.username}")
    logger.info(f"   Joke text (first 50 chars): {joke_text[:50]}...")
    
    # Add to database
    joke_id = db.add_joke(joke_text, user.id, user.username or user.first_name)
    logger.info(f"   Database returned joke_id: {joke_id}")
    
    await update.message.reply_text("✅ Joke added to database!")

def main():
    print("🔍 DEBUG MODE - Starting bot with detailed logs...")
    print(f"📊 Database: {os.path.abspath('jokes.db')}")
    
    app = ApplicationBuilder()\
        .token(BOT_TOKEN)\
        .read_timeout(30)\
        .write_timeout(30)\
        .connect_timeout(30)\
        .pool_timeout(30)\
        .build()
    
    app.add_handler(CommandHandler("start", start))
    app.add_handler(CommandHandler("joke", get_random_joke))
    app.add_handler(CommandHandler("addjoke", add_new_joke))
    
    print("✅ Debug bot is running! Check logs below...")
    print("📱 Test in Telegram with /addjoke test joke")
    print("🛑 Press Ctrl+C to stop")
    
    app.run_polling()

if __name__ == "__main__":
    main()
