# ---------------------------------------------------------
# run_all.py – یک نقطهٔ ورود برای کل پروژه
# ---------------------------------------------------------
import os, sys, threading, logging, importlib.util, pathlib

# -----------------------------------------------------------------
# ۱️⃣ تنظیم لاگر (از همان تنظیمات ربات استفاده می‌شود)
# -----------------------------------------------------------------
logger = logging.getLogger('AnonBot')
logger.setLevel(logging.INFO)

# -----------------------------------------------------------------
# ۲️⃣ تنظیم توکن ربات (از env یا فایل .bot_token)
# -----------------------------------------------------------------
if not os.getenv('BOT_TOKEN'):
    token_file = pathlib.Path(__file__).resolve().parent / '.bot_token'
    if token_file.is_file():
        token = token_file.read_text().strip()
        if token:
            os.environ['BOT_TOKEN'] = token
            logger.info('BOT_TOKEN loaded from .bot_token')
        else:
            logger.error('.bot_token is empty')
    else:
        logger.error('BOT_TOKEN not set and .bot_token not found')

# -----------------------------------------------------------------
# ۳️⃣ بارگذاری اسکریپت اصلی ربات (newfile.py یا NewFile(S).py)
# -----------------------------------------------------------------
search_dirs = [
    pathlib.Path(__file__).resolve().parent,            # همین پوشه
    pathlib.Path(__file__).resolve().parent.parent,     # پوشهٔ والد
    pathlib.Path(__file__).resolve().parent / 'Un',     # پوشهٔ Un
]

bot_path = None
for d in search_dirs:
    for name in ['newfile.py', 'NewFile(S).py']:
        cand = d / name
        if cand.is_file():
            bot_path = cand
            break
    if bot_path:
        break

if bot_path is None:
    logger.error('Bot script not found. Searched locations:')
    for d in search_dirs:
        logger.error(f'   - {d / "newfile.py"}')
        logger.error(f'   - {d / "NewFile(S).py"}')
    raise FileNotFoundError('Bot script not found')

spec = importlib.util.spec_from_file_location('main_bot', str(bot_path))
main_bot = importlib.util.module_from_spec(spec)
sys.modules['main_bot'] = main_bot
spec.loader.exec_module(main_bot)

bot = getattr(main_bot, 'bot', None)
if bot is None:
    raise RuntimeError('Bot instance not found in the loaded script')

# -----------------------------------------------------------------
# ۴️⃣ تابع برای اجرای Flask (وب‌اپ) در یک ترد جدا
# -----------------------------------------------------------------
def start_flask():
    try:
        import webapp_server
        webapp_server.run()
    except Exception as e:
        logger.exception('Failed to start Flask server: %s', e)

flask_thread = threading.Thread(target=start_flask,
                                name='FlaskThread',
                                daemon=True)
flask_thread.start()
logger.info('✅ Flask thread started.')

# -----------------------------------------------------------------
# ۵️⃣ راه‌اندازی ربات تلگرام (در همان پردازش اصلی)
# -----------------------------------------------------------------
def start_bot():
    try:
        bot.infinity_polling()
    except Exception as e:
        logger.exception('Bot polling crashed: %s', e)

logger.info('🚀 Starting Telegram bot…')
start_bot()
