#!/usr/bin/env python
"""
Enhanced Scheduler Bot with CSV support
"""

try:
    import pandas as pd
except ImportError:
    print("❌ Error: pandas library not found!")
    print("Please install required packages using:")
    print("pip install -r requirements.txt")
    exit(1)

import datetime
from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes

# 🔑 REPLACE THIS with your bot token from @BotFather
BOT_TOKEN = "8248686383:AAGN5UJ73H9i7LQzIBR3TjuJgUGNTFyRHk8"


def load_schedule():
    """
    Load schedule from CSV file using pandas
    Returns a dictionary with day-wise schedule
    """
    try:
        # Read CSV file - Updated to use the provided file name
        df = pd.read_csv('schedule_template RS.csv')
        schedule = {}

        # Process each row (each day)
        for _, row in df.iterrows():
            day = row['Day']
            schedule[day] = []

            # Process each period column - Updated to match the actual CSV structure
            # The CSV has columns labeled '1 (9:00-9:40)', '2 (10:00-10:40)', etc.
            period_columns = [
                '1 (9:00-9:40)', '2 (10:00-10:40)', '3 (11:00-11:40)', '4 (11:50-12:30)',
                '5 (12:40-13:20)', '6 (13:30-14:10)', '7 (14:20-15:00)', '8 (15:20-16:00)',
                '9 (16:15-16:55)', '10 (17:05-17:45)', '11 (17:55-18:35)', '12 (18:45-19:20)', '13 (19:20-20:00)'
            ]

            for i, col_name in enumerate(period_columns):
                period_num = str(i + 1)  # '1', '2', '3', etc.
                
                # Check if the column exists and if class exists for this time slot
                if col_name in row and pd.notna(row[col_name]) and str(row[col_name]).strip() != '':
                    class_info = str(row[col_name])
                    schedule[day].append((period_num, class_info))  # Store both period number and class info

        return schedule

    except FileNotFoundError:
        print("❌ Error: schedule_template RS.csv file not found!")
        print("Please make sure schedule_template RS.csv is in the same folder")
        return {}
    except Exception as e:
        print(f"❌ Error loading schedule: {e}")
        return {}


# Load schedule at startup
SCHEDULE = load_schedule()

# Map period numbers to times - Updated as requested
period_times = {
    '1': ('09:00', '09:40'),
    '2': ('10:00', '10:40'),
    '3': ('11:00', '11:40'),
    '4': ('11:50', '12:30'),
    '5': ('12:40', '13:20'),
    '6': ('13:30', '14:10'),
    '7': ('14:20', '15:00'),
    '8': ('15:20', '16:00'),
    '9': ('16:15', '16:55'),
    '10': ('17:05', '17:45'),
    '11': ('17:55', '18:35'),
    '12': ('18:45', '19:20'),
    '13': ('19:20', '20:00')
}

# Time mapping for periods - Updated to use the new mapping
PERIOD_TIMES = period_times


async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Send welcome message when command /start is issued."""
    await update.message.reply_text(
        "🤖 Hello! I'm your enhanced class scheduler bot!\n"
        "Use /whereami to find your current class\n"
        "Use /schedule to see today's full schedule\n"
        "Use /tomorrow to see tomorrow's schedule\n"
        "Use /help for all commands"
    )


async def where_am_i(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Tell user where they should be right now."""
    if not SCHEDULE:
        await update.message.reply_text("❌ Schedule not loaded. Check schedule_template RS.csv file.")
        return

    now = datetime.datetime.now()
    current_time = now.strftime("%H:%M")
    current_day = now.strftime("%A")

    await update.message.reply_text(f"📅 Today is {current_day}")
    await update.message.reply_text(f"⏰ Current time: {current_time}")

    # Check if we have schedule for today
    if current_day not in SCHEDULE:
        await update.message.reply_text("😊 No classes scheduled for today!")
        return

    # Find current class
    found_class = False
    for period_num, class_info in SCHEDULE[current_day]:
        start_time, end_time = PERIOD_TIMES[period_num]
        
        if start_time <= current_time <= end_time:
            await update.message.reply_text(f"🎯 You should be in: {class_info}")
            found_class = True
            break

    if not found_class:
        await update.message.reply_text("😊 No class right now! Free period.")


async def schedule(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Show the complete weekly schedule."""
    if not SCHEDULE:
        await update.message.reply_text("❌ Schedule not loaded. Check schedule_template RS.csv file.")
        return

    schedule_text = "📚 Weekly Schedule:\n\n"
    
    # Define the standard order of days in a week
    days_of_week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
    
    for day in days_of_week:
        if day in SCHEDULE and SCHEDULE[day]:  # Check if the day exists in the schedule and has classes
            schedule_text += f"*{day}'s Schedule:*\n"
            for period_num, class_info in SCHEDULE[day]:
                start, end = PERIOD_TIMES[period_num]
                schedule_text += f"  ⏰ {start}-{end}: {class_info}\n"
            schedule_text += "\n"
        else:
            schedule_text += f"{day}: No classes scheduled\n\n"

    await update.message.reply_text(schedule_text)


async def tomorrow(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Show tomorrow's schedule."""
    if not SCHEDULE:
        await update.message.reply_text("❌ Schedule not loaded. Check schedule_template RS.csv file.")
        return

    tomorrow_date = datetime.datetime.now() + datetime.timedelta(days=1)
    tomorrow_day = tomorrow_date.strftime("%A")

    if tomorrow_day not in SCHEDULE or not SCHEDULE[tomorrow_day]:
        await update.message.reply_text(f"😊 No classes scheduled for {tomorrow_day}!")
        return

    schedule_text = f"📚 {tomorrow_day}'s Schedule:\n\n"
    for period_num, class_info in SCHEDULE[tomorrow_day]:
        start, end = PERIOD_TIMES[period_num]
        schedule_text += f"⏰ {start}-{end}: {class_info}\n"

    await update.message.reply_text(schedule_text)


async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Send help message with all commands."""
    await update.message.reply_text(
        "Available commands:\n"
        "/start - Start the bot\n"
        "/whereami - Find your current class\n"
        "/schedule - Show today's full schedule\n"
        "/tomorrow - Show tomorrow's schedule\n"
        "/help - Show this help message"
    )


def main():
    """Start the bot."""
    if not SCHEDULE:
        print("❌ Failed to load schedule. Please check schedule_template RS.csv file.")
        print("Make sure schedule_template RS.csv exists in the same folder")
        return

    # Create the Application
    application = Application.builder().token(BOT_TOKEN).build()

    # Add command handlers
    application.add_handler(CommandHandler("start", start))
    application.add_handler(CommandHandler("whereami", where_am_i))
    application.add_handler(CommandHandler("schedule", schedule))
    application.add_handler(CommandHandler("tomorrow", tomorrow))
    application.add_handler(CommandHandler("help", help_command))

    # Start the Bot
    print("🤖 Enhanced scheduler bot is running...")
    print("📊 Schedule loaded successfully!")
    print("📅 Available days:", list(SCHEDULE.keys()))
    print("Press Ctrl+C to stop the bot")

    application.run_polling()


if __name__ == "__main__":
    main()