#!/usr/bin/env python3
"""
Keep-alive wrapper for Telegram bot on cPanel
This checks if bot is running and restarts it if needed
Run this via cronjob every 5 minutes
"""

import os
import subprocess
import sys
import time
from pathlib import Path

BOT_DIR = Path(__file__).parent
PID_FILE = BOT_DIR / "bot.pid"
LOG_FILE = BOT_DIR / "bot.log"
BOT_SCRIPT = BOT_DIR / "bot.py"


def is_bot_running():
    """Check if bot process is running"""
    if not PID_FILE.exists():
        return False
    
    try:
        with open(PID_FILE, 'r') as f:
            pid = int(f.read().strip())
        
        # Check if process exists
        os.kill(pid, 0)
        return True
    except (OSError, ValueError):
        return False


def start_bot():
    """Start the bot process"""
    print(f"Starting bot at {time.strftime('%Y-%m-%d %H:%M:%S')}")
    
    # Kill old process if PID file exists
    if PID_FILE.exists():
        try:
            with open(PID_FILE, 'r') as f:
                old_pid = int(f.read().strip())
            os.kill(old_pid, 9)
        except (OSError, ValueError):
            pass
        PID_FILE.unlink()
    
    # Start new process
    with open(LOG_FILE, 'a') as log:
        process = subprocess.Popen(
            [sys.executable, str(BOT_SCRIPT)],
            stdout=log,
            stderr=log,
            cwd=BOT_DIR,
            start_new_session=True
        )
        
        # Save PID
        with open(PID_FILE, 'w') as f:
            f.write(str(process.pid))
        
        print(f"Bot started with PID {process.pid}")


def main():
    os.chdir(BOT_DIR)
    
    if is_bot_running():
        print(f"Bot is already running at {time.strftime('%Y-%m-%d %H:%M:%S')}")
    else:
        print(f"Bot is not running. Starting... at {time.strftime('%Y-%m-%d %H:%M:%S')}")
        start_bot()


if __name__ == "__main__":
    main()
