#!/usr/bin/env python3
"""
مدیر ربات جنگ کشورها - اجرای مداوم با خودکارسازی
"""

import subprocess
import time
import os
import sys

BOT_SCRIPT = "bot.py"
LOG_FILE = "runner.log"

def log(message):
    timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
    with open(LOG_FILE, "a") as f:
        f.write(f"[{timestamp}] {message}\n")

def is_bot_running():
    """بررسی در حال اجرا بودن ربات"""
    try:
        result = subprocess.run(['pgrep', '-f', f'python3 {BOT_SCRIPT}'], 
                              capture_output=True, text=True)
        return bool(result.stdout.strip())
    except:
        return False

def start_bot():
    """شروع ربات"""
    log("شروع ربات...")
    subprocess.Popen([sys.executable, BOT_SCRIPT], 
                     stdout=subprocess.DEVNULL,
                     stderr=subprocess.DEVNULL,
                     start_new_session=True)
    time.sleep(5)
    if is_bot_running():
        log("✅ ربات با موفقیت شروع شد")
    else:
        log("❌ خطا در شروع ربات")

def main():
    """حلقه اصلی مدیریت ربات"""
    log("🚀 مدیر ربات شروع به کار کرد")
    
    while True:
        if not is_bot_running():
            log("ربات در حال اجرا نیست، راه‌اندازی...")
            start_bot()
        time.sleep(60)  # چک کردن هر 1 دقیقه

if __name__ == "__main__":
    main()