#!/usr/bin/env python3
import os, sys, subprocess, signal, time
from pathlib import Path
root=Path(__file__).parent
binary=root/'opencode/node_modules/@opencode/cli-linux-x64/bin/opencode'
if 'serve' not in sys.argv[1:]:
    os.execv(str(binary), [str(binary), *sys.argv[1:]])
p=subprocess.Popen([str(binary), *sys.argv[1:]])
def stop(sig, frame):
    p.send_signal(signal.SIGCONT)
    p.terminate()
    try: p.wait(timeout=5)
    except subprocess.TimeoutExpired: p.kill()
    sys.exit(0)
signal.signal(signal.SIGTERM,stop)
signal.signal(signal.SIGINT,stop)
started=time.monotonic()
while p.poll() is None:
    try: duty=float((root/'duty').read_text())
    except FileNotFoundError: duty=1
    if (root/'staged').exists() and time.monotonic()-started>25: duty=0.005
    if duty>=1:
        p.send_signal(signal.SIGCONT)
        time.sleep(.1)
    else:
        p.send_signal(signal.SIGCONT)
        time.sleep(.1*duty)
        p.send_signal(signal.SIGSTOP)
        time.sleep(.1*(1-duty))
sys.exit(p.returncode)
