import subprocess
import sys
import time
import os
import signal
import platform

# Detect environment
IS_WINDOWS = platform.system() == "Windows"

if IS_WINDOWS:
    # Development Environment (Windows)
    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    PYTHON_EXEC = sys.executable
    
    SCRIPTS = [
        ("ahoora.py", os.path.join(BASE_DIR, "instamanager")),
        ("pakdel.py", os.path.join(BASE_DIR, "pakdelgold")),
    ]
else:
    # Production Environment (Linux)
    # Using specific paths provided by user
    
    # Configuration for Bot 1 (InstaManager)
    BOT1_PYTHON = "/home/pakdelgo/virtualenv/public_html/instamanager/3.13/bin/python"
    BOT1_DIR = "/home/pakdelgo/public_html/instamanager"
    
    # Configuration for Bot 2 (PakdelGold)
    BOT2_PYTHON = "/home/pakdelgo/virtualenv/public_html/pakdelgold/3.13/bin/python"
    BOT2_DIR = "/home/pakdelgo/public_html/pakdelgold"
    
    # We'll handle different python executables in the loop
    # Tuple format: (python_executable, script_name, working_directory)
    SCRIPTS_CONFIG = [
        (BOT1_PYTHON, "ahoora.py", BOT1_DIR),
        (BOT2_PYTHON, "pakdel.py", BOT2_DIR),
    ]

def install_prerequisites():
    """Install required packages in both virtual environments (Linux only)"""
    if IS_WINDOWS:
        return  # Skip on Windows (development environment)
    
    print("📦 Installing prerequisites in virtual environments...")
    
    # Configuration for Bot 1 (InstaManager)
    BOT1_PYTHON = "/home/pakdelgo/virtualenv/public_html/instamanager/3.13/bin/python"
    BOT1_PACKAGES = ["aiogram", "aiosqlite", "httpx"]
    
    # Configuration for Bot 2 (PakdelGold)
    BOT2_PYTHON = "/home/pakdelgo/virtualenv/public_html/pakdelgold/3.13/bin/python"
    BOT2_PACKAGES = ["aiogram", "jdatetime"]
    
    # Install for Bot 1
    print(f"📥 Installing packages for InstaManager: {', '.join(BOT1_PACKAGES)}")
    try:
        subprocess.run(
            [BOT1_PYTHON, "-m", "pip", "install", "--upgrade"] + BOT1_PACKAGES,
            check=True,
            capture_output=True
        )
        print("✅ InstaManager prerequisites installed successfully")
    except subprocess.CalledProcessError as e:
        print(f"⚠️ Warning: Failed to install InstaManager prerequisites: {e}")
    
    # Install for Bot 2
    print(f"📥 Installing packages for PakdelGold: {', '.join(BOT2_PACKAGES)}")
    try:
        subprocess.run(
            [BOT2_PYTHON, "-m", "pip", "install", "--upgrade"] + BOT2_PACKAGES,
            check=True,
            capture_output=True
        )
        print("✅ PakdelGold prerequisites installed successfully")
    except subprocess.CalledProcessError as e:
        print(f"⚠️ Warning: Failed to install PakdelGold prerequisites: {e}")
    
    print("✅ All prerequisites installation completed\n")

def run_bots():
    processes = []
    
    # Install prerequisites first (only in production/Linux)
    install_prerequisites()
    
    try:
        # Start all processes
        if IS_WINDOWS:
            for script, cwd in SCRIPTS:
                print(f"🚀 Starting {script} in {cwd}...")
                p = subprocess.Popen(
                    [PYTHON_EXEC, script], 
                    cwd=cwd, 
                    shell=False
                )
                processes.append((script, p))
        else:
            # Linux / Production loop with specific python paths
            for py_exec, script, cwd in SCRIPTS_CONFIG:
                print(f"🚀 Starting {script} in {cwd} using {py_exec}...")
                p = subprocess.Popen(
                    [py_exec, script], 
                    cwd=cwd, 
                    shell=False
                )
                processes.append((script, p))
            
        print("✅ All bots started. Press Ctrl+C to stop.")
        
        # Keep the main script running to monitor children
        while True:
            time.sleep(1)
            # Check if any process has exited unexpectedly
            for name, p in processes:
                if p.poll() is not None:
                    print(f"⚠️ Process {name} exited with code {p.returncode}")
            
            # If all processes are dead, exit runner
            if all(p.poll() is not None for _, p in processes):
                print("❌ All bots have stopped. Exiting runner.")
                break
                
    except KeyboardInterrupt:
        print("\n🛑 Stopping all bots...")
        for _, p in processes:
            if p.poll() is None:
                p.terminate()
                
        time.sleep(2)
        
        for name, p in processes:
            if p.poll() is None:
                print(f"Force killing {name}...")
                p.kill()
                
        print("👋 Done.")

if __name__ == "__main__":
    run_bots()
