import os
import sys
import threading
import asyncio

# Ensure the current directory is in the path
sys.path.insert(0, os.path.dirname(__file__))

# Import the bot's main function
from main import start_bot

bot_started = False

def run_bot():
    """Runs the bot in a new asyncio event loop"""
    try:
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        loop.run_until_complete(start_bot())
    except Exception as e:
        print(f"Bot thread crashed: {e}")

def application(environ, start_response):
    """
    This is the WSGI application that cPanel Passenger looks for.
    It serves a simple HTTP response and starts the bot in the background.
    """
    global bot_started
    
    # Start the bot in a background thread ONLY ONCE
    if not bot_started:
        bot_thread = threading.Thread(target=run_bot)
        bot_thread.daemon = True
        bot_thread.start()
        bot_started = True

    # Respond to HTTP requests (Health Check)
    status = '200 OK'
    response_headers = [('Content-Type', 'text/plain')]
    start_response(status, response_headers)
    
    return [b"MRI Store Bot is Running successfully via cPanel Python App!\n"]
