from telegram import (
    Update,
    ReplyKeyboardRemove
)

from telegram.ext import (
    Application,
    CommandHandler,
    MessageHandler,
    ContextTypes,
    ConversationHandler,
    filters
)

from config import (
    TOKEN,
    ADMIN_ID,
    WELCOME_MESSAGE,
    GUIDE_TEXT
)

from questions import QUESTIONS

from keyboards import (
    main_menu,
    options_keyboard
)

from scoring import calculate_group

from database import (
    init_db,
    save_user,
    user_exists
)

from export import export_excel

ASKING = 1


async def start(
    update: Update,
    context: ContextTypes.DEFAULT_TYPE
):

    await update.message.reply_text(
        WELCOME_MESSAGE,
        reply_markup=main_menu()
    )


async def menu_handler(
    update: Update,
    context: ContextTypes.DEFAULT_TYPE
):

    text = update.message.text

    if text == "📖 راهنما":

        await update.message.reply_text(
            GUIDE_TEXT,
            reply_markup=main_menu()
        )

        return ConversationHandler.END

    if text == "🚀 انجام قدم اول":

        telegram_id = update.effective_user.id

        if user_exists(telegram_id):

            await update.message.reply_text(
                "شما قبلاً فرم را تکمیل کرده‌اید."
            )

            return ConversationHandler.END

        context.user_data["answers"] = {}
        context.user_data["step"] = 0

        await send_question(
            update,
            context
        )

        return ASKING

    return ConversationHandler.END


async def send_question(
    update,
    context
):

    step = context.user_data["step"]

    question = QUESTIONS[step]

    if question["type"] == "choice":

        await update.message.reply_text(
            question["question"],
            reply_markup=options_keyboard(
                question["options"]
            )
        )

    else:

        await update.message.reply_text(
            question["question"],
            reply_markup=ReplyKeyboardRemove()
        )


async def receive_answer(
    update: Update,
    context: ContextTypes.DEFAULT_TYPE
):

    step = context.user_data["step"]

    question = QUESTIONS[step]

    answer = update.message.text

    context.user_data["answers"][
        question["key"]
    ] = answer

    step += 1

    context.user_data["step"] = step

    if step >= len(QUESTIONS):

        answers = context.user_data["answers"]

        group_name = calculate_group(
            answers
        )

        user = update.effective_user

        save_user(
            telegram_id=user.id,
            username=user.username,
            first_name=user.first_name,
            group_name=group_name,
            answers=answers
        )

        if group_name == "Explorer":

            result = """
🌱 گروه شما: Explorer

شما در مرحله کشف مسیر زندگی هستید.

تمرکز اصلی شما:
شناخت بهتر خود
"""

        elif group_name == "Builder":

            result = """
🏗 گروه شما: Builder

شما مسیر کلی خود را پیدا کرده‌اید.

تمرکز اصلی شما:
اجرا و استمرار
"""

        else:

            result = """
🔥 گروه شما: Impact Maker

شما به دنبال اثرگذاری عمیق هستید.

تمرکز اصلی شما:
خلق ارزش برای دیگران
"""

        await update.message.reply_text(
            result,
            reply_markup=main_menu()
        )

        return ConversationHandler.END

    await send_question(
        update,
        context
    )

    return ASKING


async def export_command(
    update: Update,
    context: ContextTypes.DEFAULT_TYPE
):

    if update.effective_user.id != ADMIN_ID:

        await update.message.reply_text(
            "دسترسی ندارید."
        )

        return

    file_name = export_excel()

    await update.message.reply_document(
        document=open(
            file_name,
            "rb"
        )
    )


async def cancel(
    update: Update,
    context: ContextTypes.DEFAULT_TYPE
):

    await update.message.reply_text(
        "عملیات لغو شد.",
        reply_markup=main_menu()
    )

    return ConversationHandler.END


def main():

    init_db()

    app = Application.builder()\
        .token(TOKEN)\
        .build()

    app.add_handler(
        CommandHandler(
            "start",
            start
        )
    )

    app.add_handler(
        CommandHandler(
            "export",
            export_command
        )
    )

    conversation = ConversationHandler(

        entry_points=[
            MessageHandler(
                filters.Regex(
                    "^📖 راهنما$|^🚀 انجام قدم اول$"
                ),
                menu_handler
            )
        ],

        states={

            ASKING: [

                MessageHandler(
                    filters.TEXT &
                    ~filters.COMMAND,
                    receive_answer
                )

            ]

        },

        fallbacks=[

            CommandHandler(
                "cancel",
                cancel
            )

        ]

    )

    app.add_handler(
        conversation
    )

    print(
        "Bot Started..."
    )

    app.run_polling()


if __name__ == "__main__":
    main()