#!/usr/bin/env python3
"""reaper-link: box REAPER as the producer side of Listen's record link (spec section 8).

  REAPER record pressed  -> transport rec_start {song_pos_ns, bpm, take_id} -> relay -> performer's sender
  REAPER stopped         -> transport stop -> sender stops streaming
  while recording        -> collect the performer's song-stamped frames (RAM), Marcus track monitors input
  after stop             -> "lag adjusted on the way over": place every frame by its song_pos_ns into
                            ~/ListenSession/takes/<take_id>.wav (sample 0 = song position where recording
                            began), mute REAPER's own lag-shifted raw recording on that track, insert the
                            aligned take at that position, save the project.

Transport is polled from REAPER's web remote (/_/TRANSPORT, /_/BEATPOS). Item edits run as Lua in the
running REAPER via `reaper -nonewinst script.lua`. Monitoring is set over OSC. Password [redacted] only.
Env: LISTEN_URL, LISTEN_PWA_PASSWORD, REAPER_WWW (http://127.0.0.1:8091), REAPER_BIN, REAPER_OSC (127.0.0.1:8000),
     LISTEN_TAKES (~/ListenSession/takes), LISTEN_TRACK ("Marcus (Listen)"), LISTEN_TRACK_INDEX (2), LINK_STATUS.
"""
from __future__ import annotations

import base64
import json
import os
import re
import secrets
import socket
import ssl
import struct
import subprocess
import sys
import tempfile
import threading
import time
import urllib.request
from urllib.parse import urlparse, urlunparse

ROOT = os.environ.get("LISTEN_CODE", "/workspace/listento")
sys.path.insert(0, ROOT)
import numpy as np  # noqa: E402
import proto  # noqa: E402

BASE = os.environ.get("LISTEN_URL", "https://marcusx.fun/listen").rstrip("/")
PASSWORD = os.environ.get("LISTEN_PWA_PASSWORD", "[redacted]")
WWW = os.environ.get("REAPER_WWW", "http://127.0.0.1:8091").rstrip("/")
REAPER_BIN = os.environ.get("REAPER_BIN", "/home/box/opt/REAPER/reaper")
OSC = (os.environ.get("REAPER_OSC", "127.0.0.1:8000").split(":")[0], int(os.environ.get("REAPER_OSC", "127.0.0.1:8000").split(":")[1]))
TAKES = os.path.expanduser(os.environ.get("LISTEN_TAKES", "~/ListenSession/takes"))
TRACK_NAME = os.environ.get("LISTEN_TRACK", "Marcus (Listen)")
TRACK_INDEX = int(os.environ.get("LISTEN_TRACK_INDEX", "2"))  # 1-based (OSC / web remote numbering)
STATUS = os.environ.get("LINK_STATUS", "/home/box/listen-feed/reaper-link.json")
RPP = os.environ.get("LISTEN_RPP", os.path.expanduser("~/ListenSession/ListenSession.rpp"))
RATE = 48000
POLL_S = 0.010
GRACE_S = float(os.environ.get("LINK_GRACE_S", "0.8"))   # quiet time after the last frame before finalizing
GRACE_MAX_S = float(os.environ.get("LINK_GRACE_MAX_S", "6"))
WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
REC_STATES = (5, 6)


def log(msg: str) -> None:
    print(time.strftime("%Y-%m-%d %H:%M:%S ") + msg, flush=True)


def now_us() -> int:
    return int(time.time() * 1e6)


# ---------------------------------------------------------------- WebSocket (role=listen, mode=pcm)
class WS:
    def __init__(self, url: str):
        self.url, self.sock, self.buf, self.lock = url, None, b"", threading.Lock()

    def connect(self):
        u = urlparse(self.url)
        secure = u.scheme in ("wss", "https")
        raw = socket.create_connection((u.hostname, u.port or (443 if secure else 80)), timeout=15)
        if secure:
            raw = ssl.create_default_context().wrap_socket(raw, server_hostname=u.hostname)
        key = base64.b64encode(secrets.token_bytes(16)).decode()
        path = u.path + ("?" + u.query if u.query else "")
        raw.sendall((f"GET {path} HTTP/1.1\r\nHost: {u.hostname}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"
                     f"Sec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\nX-Listen-Password: {PASSWORD}\r\n\r\n").encode())
        buf = b""
        while b"\r\n\r\n" not in buf:
            c = raw.recv(4096)
            if not c:
                raise ConnectionError("closed during upgrade")
            buf += c
        head, self.buf = buf.split(b"\r\n\r\n", 1)
        if b" 101 " not in head.split(b"\r\n", 1)[0]:
            raise ConnectionError("upgrade failed: " + head.split(b"\r\n", 1)[0].decode(errors="replace"))
        raw.settimeout(None)
        self.sock = raw

    def send_text(self, s: str):
        p = s.encode()
        h = bytearray([0x81])
        if len(p) < 126:
            h.append(0x80 | len(p))
        else:
            h.append(0x80 | 126)
            h += struct.pack("!H", len(p))
        m = secrets.token_bytes(4)
        with self.lock:
            self.sock.sendall(bytes(h) + m + bytes(b ^ m[i % 4] for i, b in enumerate(p)))

    def _read(self, n):
        while len(self.buf) < n:
            c = self.sock.recv(65536)
            if not c:
                raise ConnectionError("closed")
            self.buf += c
        out, self.buf = self.buf[:n], self.buf[n:]
        return out

    def recv(self):
        while True:
            h = self._read(2)
            op, ln = h[0] & 0x0F, h[1] & 0x7F
            if ln == 126:
                ln = struct.unpack("!H", self._read(2))[0]
            elif ln == 127:
                ln = struct.unpack("!Q", self._read(8))[0]
            mask = self._read(4) if h[1] & 0x80 else b""
            p = self._read(ln) if ln else b""
            if mask:
                p = bytes(b ^ mask[i % 4] for i, b in enumerate(p))
            if op == 0x8:
                raise ConnectionError("ws closed")
            if op == 0x9:
                with self.lock:
                    m = secrets.token_bytes(4)
                    self.sock.sendall(bytes([0x8A, 0x80 | len(p)]) + m + bytes(b ^ m[i % 4] for i, b in enumerate(p)))
                continue
            if op == 0xA:
                continue
            return op, p

    def close(self):
        try:
            self.sock.close()
        except Exception:
            pass


# ---------------------------------------------------------------- REAPER I/O
def www(cmd: str, timeout=0.4) -> str:
    with urllib.request.urlopen(WWW + "/_/" + cmd, timeout=timeout) as r:
        return r.read().decode(errors="replace")


def transport():
    """-> (playstate, position_seconds)"""
    for line in www("TRANSPORT").splitlines():
        p = line.split("\t")
        if p and p[0] == "TRANSPORT" and len(p) >= 3:
            return int(p[1]), float(p[2])
    raise RuntimeError("no TRANSPORT line")


def bpm_now(pos: float):
    try:
        for line in www("BEATPOS").splitlines():
            p = line.split("\t")
            if p and p[0] == "BEATPOS" and len(p) >= 4 and float(p[2]) > 0.05:
                return round(float(p[3]) * 60.0 / float(p[2]), 3)
    except Exception:
        pass
    try:  # constant project tempo from the .rpp
        m = re.search(r"^\s*TEMPO\s+([0-9.]+)", open(RPP).read(), re.M)
        return float(m.group(1)) if m else None
    except Exception:
        return None


def dismiss_save_dialog() -> bool:
    """REAPER's 'Select files to save or delete' prompt (Preferences > Recording > prompt on stop) blocks
    its main thread, so the web remote and Lua stall after every stop. Press its 'Save All' (keeps the raw
    recording; the link mutes it and adds the aligned take)."""
    env = dict(os.environ)
    env.setdefault("DISPLAY", ":3")
    try:
        w = subprocess.run(["xdotool", "search", "--name", "Select files to save or delete"], env=env,
                           capture_output=True, text=True, timeout=3).stdout.split()
        if not w:
            return False
        g = subprocess.run(["xdotool", "getwindowgeometry", "--shell", w[0]], env=env, capture_output=True,
                           text=True, timeout=3).stdout
        kv = dict(line.split("=", 1) for line in g.split() if "=" in line)
        # 'Save All' sits at (202, 283) inside the 644x334 dialog
        x, y = int(kv["X"]) + 202, int(kv["Y"]) + 283
        subprocess.run(["xdotool", "mousemove", str(x), str(y), "click", "1"], env=env, capture_output=True, timeout=5)
        log("dismissed REAPER's save-recorded-files prompt (Save All)")
        return True
    except Exception:
        return False


def track_flags(idx: int):
    try:
        for line in www(f"TRACK/{idx}").splitlines():
            p = line.split("\t")
            if p and p[0] == "TRACK" and len(p) > 3:
                return int(p[3])
    except Exception:
        pass
    return None


def _pad(b):
    b = (b.encode() if isinstance(b, str) else b) + b"\x00"
    return b + b"\x00" * ((-len(b)) % 4)


def osc(addr: str, *ints):
    msg = _pad(addr) + _pad("," + "i" * len(ints)) + b"".join(struct.pack(">i", v) for v in ints)
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        s.sendto(msg, OSC)
    finally:
        s.close()


def lua(code: str, result_path: str, timeout=15.0) -> str:
    """Run Lua inside the running REAPER and wait for it to write result_path (ends with END)."""
    try:
        os.unlink(result_path)
    except FileNotFoundError:
        pass
    fd, path = tempfile.mkstemp(prefix="listen-link-", suffix=".lua")
    with os.fdopen(fd, "w") as f:
        f.write(code)
    env = dict(os.environ)
    env.setdefault("DISPLAY", ":3")
    subprocess.run([REAPER_BIN, "-nonewinst", path], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
                   timeout=20, cwd="/tmp")
    t_end = time.time() + timeout
    try:
        while time.time() < t_end:
            try:
                txt = open(result_path).read()
                if txt.rstrip().endswith("END"):
                    return txt
            except FileNotFoundError:
                pass
            time.sleep(0.05)
        raise TimeoutError("REAPER did not run the Lua script")
    finally:
        try:
            os.unlink(path)
        except Exception:
            pass


def _luastr(s: str) -> str:
    return "[==[" + s + "]==]"


LUA_TRACK = """
local function listen_track()
  local want = %s
  for i = 0, reaper.CountTracks(0) - 1 do
    local tr = reaper.GetTrack(0, i)
    local _, nm = reaper.GetSetMediaTrackInfo_String(tr, "P_NAME", "", false)
    if nm == want then return tr end
  end
  return reaper.GetTrack(0, %d)
end
"""


def lua_items(res: str) -> str:
    return (LUA_TRACK % (_luastr(TRACK_NAME), TRACK_INDEX - 1)) + """
local out = io.open(%s, "w")
local tr = listen_track()
if tr then
  for i = 0, reaper.CountTrackMediaItems(tr) - 1 do
    local it = reaper.GetTrackMediaItem(tr, i)
    local _, guid = reaper.GetSetMediaItemInfo_String(it, "GUID", "", false)
    local tk = reaper.GetActiveTake(it)
    local fn = ""
    if tk then fn = reaper.GetMediaSourceFileName(reaper.GetMediaItemTake_Source(tk), "") end
    out:write(string.format("ITEM\\t%%s\\t%%.9f\\t%%.9f\\t%%d\\t%%s\\n", guid,
      reaper.GetMediaItemInfo_Value(it, "D_POSITION"), reaper.GetMediaItemInfo_Value(it, "D_LENGTH"),
      math.floor(reaper.GetMediaItemInfo_Value(it, "B_MUTE")), fn))
  end
end
out:write("END\\n")
out:close()
""" % _luastr(res)


def lua_place(res: str, wav: str, pos: float, take_id: str, mute_guids: list) -> str:
    guids = "{" + ",".join(_luastr(g) for g in mute_guids) + "}"
    return (LUA_TRACK % (_luastr(TRACK_NAME), TRACK_INDEX - 1)) + """
local out = io.open(%s, "w")
local tr = listen_track()
local mute = %s
reaper.Undo_BeginBlock()
for i = 0, reaper.CountTrackMediaItems(tr) - 1 do
  local it = reaper.GetTrackMediaItem(tr, i)
  local _, guid = reaper.GetSetMediaItemInfo_String(it, "GUID", "", false)
  for _, g in ipairs(mute) do if g == guid then reaper.SetMediaItemInfo_Value(it, "B_MUTE", 1) end end
end
local item = reaper.AddMediaItemToTrack(tr)
local take = reaper.AddTakeToMediaItem(item)
local src = reaper.PCM_Source_CreateFromFile(%s)
reaper.SetMediaItemTake_Source(take, src)
local len = reaper.GetMediaSourceLength(src)
reaper.SetMediaItemInfo_Value(item, "D_POSITION", %.9f)
reaper.SetMediaItemInfo_Value(item, "D_LENGTH", len)
reaper.GetSetMediaItemTakeInfo_String(take, "P_NAME", %s, true)
reaper.UpdateArrange()
reaper.Undo_EndBlock("Listen: aligned take " .. %s, -1)
reaper.Main_OnCommand(40026, 0) -- save project
local _, guid = reaper.GetSetMediaItemInfo_String(item, "GUID", "", false)
out:write(string.format("PLACED\\t%%s\\t%%.9f\\t%%.9f\\t%%s\\n", guid,
  reaper.GetMediaItemInfo_Value(item, "D_POSITION"), reaper.GetMediaItemInfo_Value(item, "D_LENGTH"),
  reaper.GetMediaSourceFileName(src, "")))
out:write("END\\n")
out:close()
""" % (_luastr(res), guids, _luastr(wav), pos, _luastr(take_id), _luastr(take_id))


def parse_items(txt: str):
    out = []
    for line in txt.splitlines():
        p = line.split("\t")
        if p[0] == "ITEM" and len(p) >= 6:
            out.append({"guid": p[1], "pos": float(p[2]), "len": float(p[3]), "mute": int(p[4]), "file": p[5]})
    return out


def write_wav_f32(path: str, x: np.ndarray, rate: int = RATE) -> None:
    """IEEE-float WAV (format 3), interleaved stereo."""
    x = np.ascontiguousarray(x, dtype="<f4")
    ch = x.shape[1]
    data = x.tobytes()
    hdr = b"RIFF" + struct.pack("<I", 4 + 26 + 12 + 8 + len(data)) + b"WAVE"
    hdr += b"fmt " + struct.pack("<IHHIIHHH", 18, 3, ch, rate, rate * ch * 4, ch * 4, 32, 0)
    hdr += b"fact" + struct.pack("<II", 4, x.shape[0])
    hdr += b"data" + struct.pack("<I", len(data))
    tmp = path + ".tmp"
    with open(tmp, "wb") as f:
        f.write(hdr)
        f.write(data)
    os.replace(tmp, path)


def decode(fr) -> np.ndarray:
    ch = max(1, fr["ch"])
    if fr["type"] == proto.T_F32:
        x = np.frombuffer(fr["payload"], dtype="<f4").astype(np.float32)
    elif fr["type"] == proto.T_S24:
        b = np.frombuffer(fr["payload"], dtype=np.uint8).reshape(-1, 3).astype(np.int32)
        v = b[:, 0] | (b[:, 1] << 8) | (b[:, 2] << 16)
        v = np.where(v >= 0x800000, v - 0x1000000, v)
        x = (v / 8388608.0).astype(np.float32)
    elif fr["type"] == proto.T_S16:
        x = (np.frombuffer(fr["payload"], dtype="<i2") / 32768.0).astype(np.float32)
    else:
        raise ValueError("not pcm")
    x = x.reshape(-1, ch)
    if ch == 1:
        x = np.repeat(x, 2, axis=1)
    return x[:, :2]


# ---------------------------------------------------------------- the link
class Take:
    def __init__(self, take_id, pos0_obs, t_obs, p0_est, bpm, rec_wall):
        self.take_id, self.pos_obs, self.t_obs, self.p0_est, self.bpm = take_id, pos0_obs, t_obs, p0_est, bpm
        self.rec_wall = rec_wall
        self.frames = []      # (song_ns, arrival_s, samples)
        self.unstamped = 0
        self.stop_wall = None
        self.p_stop = None
        self.last_rx = 0.0
        self.acks = {}
        self.collect = True


class Link:
    def __init__(self):
        self.ws = None
        self.ws_up = False
        self.take: Take | None = None
        self.lock = threading.Lock()
        self.status = {"service": "reaper-link", "url": BASE, "www": WWW, "takes": TAKES, "last_take": None}
        self.sender = None

    # --- relay side
    def ws_loop(self):
        u = urlparse(BASE)
        url = urlunparse(("wss" if u.scheme == "https" else "ws", u.netloc, u.path.rstrip("/") + "/ws",
                          "", "role=listen&mode=pcm", ""))
        back = 1.0
        while True:
            try:
                ws = WS(url)
                ws.connect()
                self.ws, self.ws_up, back = ws, True, 1.0
                log(f"relay connected {url}")
                while True:
                    op, p = ws.recv()
                    if op == 0x1 or p[:1] == b"{":
                        self.on_text(p)
                    else:
                        self.on_frame(p)
            except Exception as e:
                self.ws_up = False
                log(f"relay link down: {type(e).__name__}: {e}")
                time.sleep(back)
                back = min(10.0, back * 1.7)

    def on_text(self, p: bytes):
        try:
            o = json.loads(p)
        except Exception:
            return
        t = o.get("type")
        if t in ("hello", "stream"):
            self.sender = o.get("sender")
        elif t == "transport_ack" and o.get("from") == "sender":
            with self.lock:
                tk = self.take
                if tk is not None and o.get("take_id") == tk.take_id:
                    tk.acks[o.get("event")] = {"rx_us": o.get("rx_us"), "local_rx_s": time.time()}
            log(f"performer ack {o.get('event')} take={o.get('take_id')}")

    def on_frame(self, p: bytes):
        if len(p) < 56 or p[4] not in (proto.T_S16, proto.T_S24, proto.T_F32):
            return
        with self.lock:
            tk = self.take
        if tk is None or not tk.collect:
            return
        fr = proto.unpack(p)
        if not fr or not proto.crc_ok(fr):
            return
        if not (fr["flags"] & proto.F_PLAYING) or fr["song_pos_ns"] < 0:
            tk.unstamped += 1
            return
        tk.frames.append((fr["song_pos_ns"], time.time(), decode(fr)))
        tk.last_rx = time.time()

    def send_transport(self, obj: dict):
        obj = {"type": "transport", **obj}
        if self.ws_up and self.ws is not None:
            try:
                self.ws.send_text(json.dumps(obj))
                return "ws"
            except Exception as e:
                log(f"ws send failed ({e}); falling back to POST")
        req = urllib.request.Request(BASE + "/api/transport", data=json.dumps({**obj, "by": "reaper-link"}).encode(),
                                     headers={"Content-Type": "application/json", "X-Listen-Password": PASSWORD},
                                     method="POST")
        with urllib.request.urlopen(req, timeout=5) as r:
            r.read()
        return "http"

    # --- REAPER side
    def run(self):
        threading.Thread(target=self.ws_loop, daemon=True).start()
        state, rec = None, False
        stopped_pos, stopped_t = None, 0.0
        last_rec_pos, last_rec_t, prev_t = 0.0, 0.0, time.time()
        saved_flags = None
        last_status = 0.0
        while True:
            t0 = time.time()
            try:
                st, pos = transport()
            except Exception as e:
                dismiss_save_dialog()
                if time.time() - last_status > 5:
                    self.status.update({"reaper": f"unreachable: {e}"})
                    self.write_status()
                    last_status = time.time()
                time.sleep(0.5)
                continue
            t = time.time()
            is_rec = st in REC_STATES
            if is_rec and not rec:
                rec = True
                take_id = "take-" + time.strftime("%Y%m%d-%H%M%S")
                # REAPER starts recording at the edit cursor (= the stopped position); use that when it agrees
                est = pos - (t - prev_t) / 2.0
                p0_est = stopped_pos if (stopped_pos is not None and abs(est - stopped_pos) < 0.5) else est
                bpm = bpm_now(pos)
                tk = Take(take_id, pos, t, p0_est, bpm, t - (t - prev_t) / 2.0)
                with self.lock:
                    self.take = tk
                how = self.send_transport({"event": "rec_start", "take_id": take_id, "song_pos_ns": int(round(pos * 1e9)),
                                           "host_us": int(t * 1e6), "bpm": bpm, "rate": RATE})
                # mute & replace: while recording, the Marcus track monitors its input = the incoming stream
                saved_flags = track_flags(TRACK_INDEX)
                osc(f"/track/{TRACK_INDEX}/monitor", 1)
                log(f"REC {take_id} at {pos:.3f}s (p0 est {p0_est:.6f}s) bpm={bpm} -> rec_start via {how}")
            elif rec and not is_rec:
                rec = False
                with self.lock:
                    tk = self.take
                p_stop = last_rec_pos + min(t - last_rec_t, 2 * POLL_S + 0.01) / 2.0
                tk.p_stop, tk.stop_wall = p_stop, t
                how = self.send_transport({"event": "stop", "take_id": tk.take_id, "song_pos_ns": int(round(p_stop * 1e9)),
                                           "host_us": int(t * 1e6), "rate": RATE})
                if saved_flags is not None and not (saved_flags & 128):
                    osc(f"/track/{TRACK_INDEX}/monitor", 2 if saved_flags & 256 else 0)
                log(f"STOP {tk.take_id} at ~{p_stop:.3f}s -> stop via {how}; aligning take")
                threading.Thread(target=self.finalize, args=(tk,), daemon=True).start()
            if is_rec:
                last_rec_pos, last_rec_t = pos, t
            elif st == 0:
                stopped_pos, stopped_t = pos, t
            prev_t = t
            if t - last_status > 1.0:
                self.status.update({"reaper_state": st, "reaper_pos": pos, "recording": rec, "relay_ws": self.ws_up,
                                    "sender": self.sender, "updated": time.strftime("%Y-%m-%d %H:%M:%S")})
                self.write_status()
                last_status = t
            time.sleep(max(0.0, POLL_S - (time.time() - t0)))

    def finalize(self, tk: Take):
        try:
            res = self._finalize(tk)
            self.status["last_take"] = res
            self.write_status()
        except Exception as e:
            log(f"finalize {tk.take_id} failed: {type(e).__name__}: {e}")
            self.status["last_take"] = {"take_id": tk.take_id, "error": f"{type(e).__name__}: {e}"}
            self.write_status()

    def _finalize(self, tk: Take) -> dict:
        os.makedirs(TAKES, exist_ok=True)
        resf = os.path.join(tempfile.gettempdir(), f"listen-link-{os.getpid()}.txt")
        # 1) REAPER's own (lag-shifted) recording on the Marcus track gives the exact record-start position
        time.sleep(0.6)
        raw_items, p0, p0_src = [], tk.p0_est, "estimate"
        try:
            items = parse_items(lua(lua_items(resf), resf))
            for it in items:
                f = it["file"]
                if not f or "/takes/" in f or os.path.abspath(f).startswith(os.path.abspath(TAKES)):
                    continue
                try:
                    fresh = os.path.getmtime(f) >= tk.rec_wall - 1.0
                except OSError:
                    fresh = False
                if fresh and abs(it["pos"] - tk.p0_est) < 0.25:
                    raw_items.append(it)
            if raw_items:
                # REAPER can split one recording at existing item edges: every piece of that file is this take
                src = min(raw_items, key=lambda it: abs(it["pos"] - tk.p0_est))["file"]
                raw_items = [it for it in items if it["file"] == src]
                p0, p0_src = min(it["pos"] for it in raw_items), "reaper raw item"
                tk.p_stop = max(it["pos"] + it["len"] for it in raw_items)  # exact record length too
        except Exception as e:
            log(f"item scan failed: {e}")
        # 2) wait for the frames still on the way ("lag adjusted on the way over")
        t_end = tk.stop_wall + GRACE_MAX_S
        while time.time() < t_end:
            if time.time() - max(tk.last_rx, tk.stop_wall) > GRACE_S:
                break
            time.sleep(0.05)
        tk.collect = False
        with self.lock:
            if self.take is tk:
                self.take = None
        frames = sorted(tk.frames, key=lambda f: f[0])
        p0_ns = int(round(p0 * 1e9))
        n_total = int(round((tk.p_stop - p0) * RATE))
        if frames:
            last_end = int(round((frames[-1][0] - p0_ns) * RATE / 1e9)) + frames[-1][2].shape[0]
            n_total = max(n_total, min(last_end, n_total + RATE // 2))
        n_total = max(n_total, 1)
        out = np.zeros((n_total, 2), dtype=np.float32)
        covered = np.zeros(n_total, dtype=bool)
        lags, dropped_before, dropped_after = [], 0, 0
        for sp, arr_t, x in frames:
            off = int(round((sp - p0_ns) * RATE / 1e9))
            a, b = off, off + x.shape[0]
            if b <= 0:
                dropped_before += 1
                continue
            if a >= n_total:
                dropped_after += 1
                continue
            xa = max(0, -a)
            a2, b2 = max(a, 0), min(b, n_total)
            out[a2:b2] = x[xa:xa + (b2 - a2)]
            covered[a2:b2] = True
            # arrival lag: when it got here vs when REAPER's playhead passed that song position
            lags.append(arr_t - (tk.t_obs + (sp / 1e9 - tk.pos_obs)))
        wav = os.path.join(TAKES, f"{tk.take_id}.wav")
        write_wav_f32(wav, out)
        first_cov = int(np.argmax(covered)) if covered.any() else None
        info = {
            "take_id": tk.take_id, "wav": wav, "rate": RATE, "samples": n_total,
            "song_start_s": p0, "song_start_src": p0_src, "song_start_est_s": tk.p0_est, "song_stop_s": tk.p_stop,
            "bpm": tk.bpm, "frames": len(frames), "unstamped_frames": tk.unstamped,
            "frames_before_start": dropped_before, "frames_after_stop": dropped_after,
            "first_audio_sample": first_cov,
            "coverage": round(float(covered.mean()), 4),
            "arrival_lag_ms": ({"min": round(min(lags) * 1000, 1), "median": round(float(np.median(lags)) * 1000, 1),
                                "max": round(max(lags) * 1000, 1)} if lags else None),
            "performer_ack": tk.acks, "muted_raw_items": [i["guid"] for i in raw_items],
        }
        log(f"take {tk.take_id}: {len(frames)} frames, coverage {info['coverage']}, lag {info['arrival_lag_ms']}")
        # 3) mute REAPER's raw lagged recording, insert the aligned take at the record-start position, save
        try:
            txt = lua(lua_place(resf, wav, p0, tk.take_id, [i["guid"] for i in raw_items]), resf)
            for line in txt.splitlines():
                p = line.split("\t")
                if p[0] == "PLACED":
                    info["placed"] = {"guid": p[1], "pos_s": float(p[2]), "len_s": float(p[3]), "file": p[4]}
            log(f"placed {tk.take_id} on '{TRACK_NAME}' at {info.get('placed', {}).get('pos_s')}s; project saved")
        except Exception as e:
            info["placed"] = {"error": f"{type(e).__name__}: {e}"}
            log(f"placement failed: {e}")
        with open(os.path.join(TAKES, f"{tk.take_id}.json"), "w") as f:
            json.dump(info, f, indent=2)
        return info

    def write_status(self):
        tmp = STATUS + ".tmp"
        try:
            with open(tmp, "w") as f:
                json.dump(self.status, f, indent=2)
            os.replace(tmp, STATUS)
        except OSError:
            pass


if __name__ == "__main__":
    log(f"reaper-link start relay={BASE} reaper={WWW} track='{TRACK_NAME}' takes={TAKES}")
    Link().run()
