#!/usr/bin/env python3
# Deterministic tmux passthrough test:
# 1. idle pane session, 2. attach client, 3. trigger wrapped sixel, 4. read.
import os, pty, select, subprocess, sys, time

SOCK = "pkdet"
W = "/tmp/opencode/wrapped.sixel"
ENVU = "env -u LD_PRELOAD -u TORSOCKS_CONF_FILE "

def sh(cmd, timeout=30):
    if "tmux " in cmd and not cmd.startswith(ENVU):
        cmd = ENVU + cmd
    r = subprocess.run(["sh", "-c", cmd], capture_output=True, text=True,
                       timeout=timeout)
    return r.returncode, (r.stdout or ""), (r.stderr or "")

sh("tmux -L %s kill-server 2>/dev/null" % SOCK)
sh("tmux -L %s new-session -d -s s" % SOCK)
sh("tmux -L %s set -g allow-passthrough on" % SOCK)

master, slave = pty.openpty()
env = dict(os.environ, TERM="xterm", TZ=os.environ.get("TZ", ""))
proc = subprocess.Popen(["/usr/bin/env", "-u", "LD_PRELOAD", "-u",
                         "TORSOCKS_CONF_FILE", "tmux", "-L", SOCK,
                         "attach", "-t", "s"],
                        stdin=slave, stdout=slave, stderr=slave,
                        env=env, close_fds=True)
os.close(slave)

def drain(sec):
    buf = b""
    end = time.time() + sec
    while time.time() < end:
        r, _, _ = select.select([master], [], [], 0.5)
        if master in r:
            try:
                d = os.read(master, 65536)
            except OSError:
                break
            if d:
                buf += d
    return buf

time.sleep(1.5)  # let attach redraw settle
pre = drain(1.0)
sh("tmux -L %s send-keys -t s 'cat %s; echo PEKDONE' Enter" % (SOCK, W))
out = drain(6.0)

proc.terminate()
try:
    proc.wait(timeout=3)
except subprocess.TimeoutExpired:
    proc.kill()
os.close(master)

total = pre + out
print("attach-settle bytes: %d, after-trigger bytes: %d" % (len(pre), len(out)))
i=total.find(b"#0;2;")
print("palette-at:", i)
print("BEFORE-PALETTE:", repr(total[max(0,i-60):i+40]))
print("HEAD:", repr(total[:180]))
has_dcs = b"\x1bPq" in total
has_body = (b"#0;2;" in total)          # sixel palette defs
has_ph = b"SIXEL IMAGE" in total
print("RESULT: RAW_PQ=%s SIXEL_BODY=%s PLACEHOLDER=%s" % (has_dcs, has_body, has_ph))
sys.exit(0 if (has_body and has_dcs and not has_ph) else 1)