#!/usr/bin/env python3
import subprocess
import sys
import os
import signal
from datetime import datetime

LOG_DIR = "/app/data/logs"
os.makedirs(LOG_DIR, exist_ok=True)

def get_timestamp():
    return datetime.now().strftime("%Y-%m-%d %H:%M:%S")

log_file = open(f"{LOG_DIR}/bots.log", "a")

def log(msg):
    timestamp = get_timestamp()
    log_line = f"[{timestamp}] {msg}\n"
    log_file.write(log_line)
    log_file.flush()
    print(msg)

print("🤖 Iniciando Bots de Traducción...")
print("=" * 40)

processes = []

def start_process(cmd, name):
    log(f"✅ Iniciando {name}...")
    
    log_path = f"{LOG_DIR}/{name.lower().replace(' ', '_')}.log"
    with open(log_path, "a") as f:
        p = subprocess.Popen(
            cmd,
            stdout=f,
            stderr=subprocess.STDOUT,
            preexec_fn=os.setsid
        )
    processes.append((p, name))
    return p

p1 = start_process(["python3", "botdiscord/bot.py"], "Discord Bot")
p2 = start_process(["python3", "bottelegram/telegram_bot.py"], "Telegram Bot")
p3 = start_process(["python3", "panel/main.py"], "Panel Web")

print("=" * 40)
print("🎉 Todos los servicios funcionando!")
print(f"   📍 Panel: http://localhost:8000")
print(f"   📁 Logs: {LOG_DIR}")
print("=" * 40)
print("\nCtrl+C para detener")

def signal_handler(sig, frame):
    log("🛑 Deteniendo...")
    for p, name in processes:
        try:
            os.killpg(os.getpgid(p.pid), signal.SIGTERM)
            log(f"   ✅ {name} detenido")
        except:
            pass
    log_file.close()
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)

while True:
    for p, name in processes:
        if p.poll() is not None:
            log(f"⚠️ {name} se detuvo, reiniciando...")
            if name == "Discord Bot":
                p1 = start_process(["python3", "botdiscord/bot.py"], "Discord Bot")
            elif name == "Telegram Bot":
                p2 = start_process(["python3", "bottelegram/telegram_bot.py"], "Telegram Bot")
            elif name == "Panel Web":
                p3 = start_process(["python3", "panel/main.py"], "Panel Web")
    import time
    time.sleep(5)
