#!/usr/bin/env python3
"""
Gandalf's Hyperliquid Trading Bot - Proper Process-Based Starter
Runs dashboard and bot in separate processes
"""

import sys
import os
import subprocess
import time
import signal
import atexit

def main():
    bot_dir = os.path.dirname(os.path.abspath(__file__))
    os.chdir(bot_dir)

    print("="*60)
    print("🧙‍♂️ GANDALF'S HYPERLIQUID TRADER")
    print("="*60)

    # Clean up old processes
    subprocess.run(["pkill", "-f", "hyperliquid_bot.py"], stderr=subprocess.DEVNULL)
    subprocess.run(["pkill", "-f", "dashboard.py"], stderr=subprocess.DEVNULL)
    time.sleep(1)

    # Start dashboard process
    print("📊 Starting Dashboard...")
    dashboard_log = open("/home/node/.openclaw/workspace/crypto-wallet/bot/dashboard.log", "w")
    dash_proc = subprocess.Popen(
        [sys.executable, "dashboard.py"],
        cwd=bot_dir,
        stdout=dashboard_log,
        stderr=subprocess.STDOUT,
        preexec_fn=os.setsid
    )

    # Give dashboard time to start
    time.sleep(3)

    # Start bot in background
    print("🤖 Starting Trading Bot...")
    bot_log = open("/home/node/.openclaw/workspace/crypto-wallet/bot/bot.log", "w")
    bot_proc = subprocess.Popen(
        [sys.executable, "hyperliquid_bot.py"],
        cwd=bot_dir,
        stdout=bot_log,
        stderr=subprocess.STDOUT,
        preexec_fn=os.setsid
    )

    print(f"📊 Dashboard: http://localhost:5000")
    print(f"📜 Bot Log: /home/node/.openclaw/workspace/crypto-wallet/bot/bot.log")
    print(f"📜 Trades Log: /home/node/.openclaw/workspace/crypto-wallet/bot/trades.log")
    print("="*60)
    print("🟢 Bot is running! Use Ctrl+C to stop.")

    def cleanup():
        print("\n🛑 Stopping bot...")
        try:
            os.killpg(os.getpgid(dash_proc.pid), signal.SIGTERM)
            os.killpg(os.getpgid(bot_proc.pid), signal.SIGTERM)
        except:
            pass

    atexit.register(cleanup)

    # Monitor processes
    try:
        while True:
            time.sleep(30)
            if dash_proc.poll() is not None:
                print("⚠️ Dashboard crashed, restarting...")
                dashboard_log = open("/home/node/.openclaw/workspace/crypto-wallet/bot/dashboard.log", "w")
                dash_proc = subprocess.Popen(
                    [sys.executable, "dashboard.py"],
                    cwd=bot_dir,
                    stdout=dashboard_log,
                    stderr=subprocess.STDOUT
                )
            if bot_proc.poll() is not None:
                print("⚠️ Bot crashed, restarting...")
                bot_log = open("/home/node/.openclaw/workspace/crypto-wallet/bot/bot.log", "w")
                bot_proc = subprocess.Popen(
                    [sys.executable, "hyperliquid_bot.py"],
                    cwd=bot_dir,
                    stdout=bot_log,
                    stderr=subprocess.STDOUT
                )
    except KeyboardInterrupt:
        cleanup()

if __name__ == "__main__":
    main()
