#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Script untuk menjalankan bot Telegram sebagai service.
Ini akan memastikan bot tetap berjalan bahkan setelah terminal ditutup.
"""

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

# Konfigurasi logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler("bot_service.log"),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

def run_bot():
    """Menjalankan bot sebagai proses terpisah."""
    script_dir = Path(__file__).parent.absolute()
    bot_script = script_dir / "bot.py"
    
    logger.info(f"Memulai bot dari {bot_script}")
    
    try:
        # Jalankan bot sebagai proses terpisah
        process = subprocess.Popen(
            [sys.executable, str(bot_script)],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
        
        logger.info(f"Bot berhasil dimulai dengan PID: {process.pid}")
        
        # Pantau output bot
        while True:
            output = process.stdout.readline()
            if output:
                logger.info(f"Bot output: {output.strip()}")
            
            error = process.stderr.readline()
            if error:
                logger.error(f"Bot error: {error.strip()}")
            
            # Periksa apakah proses masih berjalan
            if process.poll() is not None:
                logger.warning(f"Bot berhenti dengan kode: {process.returncode}")
                # Restart bot jika berhenti
                logger.info("Memulai ulang bot...")
                return run_bot()
            
            time.sleep(1)
    
    except KeyboardInterrupt:
        logger.info("Menerima sinyal interrupt, menghentikan bot...")
        if process and process.poll() is None:
            process.terminate()
            process.wait()
        logger.info("Bot dihentikan")
        sys.exit(0)
    
    except Exception as e:
        logger.error(f"Error saat menjalankan bot: {str(e)}")
        if process and process.poll() is None:
            process.terminate()
            process.wait()
        logger.info("Memulai ulang bot dalam 5 detik...")
        time.sleep(5)
        return run_bot()

if __name__ == "__main__":
    logger.info("Memulai service bot Telegram...")
    run_bot()
