import os
import sys
import subprocess
import time

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
BOT_FILE = os.path.join(BASE_DIR, "shop8.py")
PID_FILE = os.path.join(BASE_DIR, "shop8.pid")


def bot_running():
    if not os.path.exists(PID_FILE):
        return False

    try:
        with open(PID_FILE, "r") as f:
            pid = int(f.read().strip())

        os.kill(pid, 0)
        return True
    except Exception:
        try:
            os.remove(PID_FILE)
        except Exception:
            pass
        return False


if not bot_running():
    process = subprocess.Popen(
        [sys.executable, BOT_FILE],
        cwd=BASE_DIR,
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL,
        start_new_session=True,
    )

    with open(PID_FILE, "w") as f:
        f.write(str(process.pid))


def application(environ, start_response):
    start_response(
        "200 OK",
        [("Content-Type", "text/plain; charset=utf-8")]
    )
    return [b"Shop8 bot is running."]