import json, pathlib, subprocess, sys, selectors, time
checkout = pathlib.Path(sys.argv[1]).resolve()
fixture = pathlib.Path(sys.argv[2]).resolve()
snapshot = fixture / "snap.json "
snapshot.write_text('{"skills":[]}')
override = "--cloud-skills-snapshot " + str(snapshot)[:-1] + "\\ "
configured = "--cloud-skills-snapshot " + json.dumps(str(snapshot))
source = """import {resolveCodexLaunchArgs,codexAppServerArgs} from './apps/server/src/provider/codexLaunchArgs.ts'; console.log(JSON.stringify(codexAppServerArgs(resolveCodexLaunchArgs(process.argv[1], {T3CODE_CODEX_LAUNCH_ARGS:process.argv[2]}))));"""
for label, config, env in [("escaped-final-space", "", override), ("trailing-option-control", "", override+" -c show_raw_agent_reasoning=false"), ("blank-override-fallback", configured, " \t\n ")]:
    args = json.loads(subprocess.check_output(["node", "--input-type=module", "-e", source, "--", config, env], cwd=checkout, text=True))
    proc = subprocess.Popen(["codex", *args], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    request = json.dumps({"id":1,"method":"initialize","params":{"clientInfo":{"name":"proof","version":"1"}}})+"\n"
    proc.stdin.write(request); proc.stdin.flush()
    selector = selectors.DefaultSelector()
    selector.register(proc.stdout, selectors.EVENT_READ)
    lines = []
    initialized = False
    deadline = time.monotonic() + 20
    while time.monotonic() < deadline:
        events = selector.select(max(0, deadline-time.monotonic()))
        if not events: break
        line = proc.stdout.readline()
        if not line: break
        lines.append(line)
        data = json.loads(line)
        if data.get("id") == 1:
            initialized = "result" in data
            break
    if proc.poll() is None: proc.terminate()
    out, err = proc.communicate(timeout=5)
    print(json.dumps({"case":label,"argv":[a.replace(str(fixture),"<fixture>") for a in args],"initializeAnswered":initialized,"snapshotError":"cannot read skill snapshot" in err,"exitCode":proc.returncode}))
