import subprocess
import time
import urllib.request
import os
from pathlib import Path

class XOpat:
    def __init__(self, proc, base_url):
        self.proc = proc
        self.base_url = base_url

    def stop(self):
        self.proc.terminate()
        self.proc.wait()

def start_xopat(binary):
    binary = Path(binary)
    env = os.environ.copy()

    proc = subprocess.Popen(
        [str(binary)],
        cwd=str(binary.parent),
        env=env,
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL,
    )

    prefix = os.environ.get("JUPYTERHUB_SERVICE_PREFIX", "").rstrip("/")
    base_url = f"{prefix}/proxy/9000" if prefix else "http://127.0.0.1:9000"

    for _ in range(50):
        try:
            urllib.request.urlopen("http://127.0.0.1:9000", timeout=0.5)
            return XOpat(proc, base_url)
        except Exception:
            time.sleep(0.2)
    proc.terminate()
    raise RuntimeError("xOpat did not start on http://127.0.0.1:9000")