#!/usr/bin/env python3
"""Headless Listen receiver: LSTN stream -> silent-lock snap buffer -> Pulse listen_feed.

Store-nothing (no audio on disk). Auto-reconnects forever. Light CPU.
Prefers pcm24, falls back to pcm. Plays at 48 kHz into listen_feed.
"""
from __future__ import annotations

import json
import os
import socket
import select
import ssl
import subprocess
import sys
import time
from urllib.parse import urlparse

ROOT = os.environ.get("LISTEN_CODE", "/workspace/listento")
sys.path.insert(0, ROOT)

import numpy as np  # noqa: E402
import proto  # noqa: E402
from lock import Lock, unpack_ctrl, fwd_one_way_us  # noqa: E402
from tiers import decode  # noqa: E402

BASE = os.environ.get("LISTEN_URL", "https://marcusx.fun/listen").rstrip("/")
PASSWORD = os.environ.get("LISTEN_PWA_PASSWORD", "[redacted]")
SINK = os.environ.get("LISTEN_SINK", "listen_feed")
STATUS_PATH = os.environ.get("LISTEN_STATUS", "/home/box/listen-feed/status.json")
MODE_PREF = os.environ.get("LISTEN_MODE", "pcm24")
OUT_RATE = 48000
OUT_CH = 2
TARGET_S = 0.080
MAX_S = 0.200
XFADE_S = 0.003


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


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


def write_status(obj: dict) -> None:
    tmp = STATUS_PATH + ".tmp"
    try:
        with open(tmp, "w") as f:
            json.dump(obj, f, indent=2)
        os.replace(tmp, STATUS_PATH)
    except OSError as e:
        log(f"status write failed: {e}")


def resample(x: np.ndarray, src_rate: int, dst_rate: int) -> np.ndarray:
    if src_rate == dst_rate or x.size == 0:
        return x.astype(np.float32, copy=False)
    n = x.shape[0]
    n_out = max(1, int(round(n * dst_rate / src_rate)))
    t = np.linspace(0, n - 1, n_out, dtype=np.float64)
    i0 = np.floor(t).astype(np.int64)
    i1 = np.minimum(i0 + 1, n - 1)
    frac = (t - i0).astype(np.float32)[:, None]
    return (x[i0] * (1 - frac) + x[i1] * frac).astype(np.float32)


def to_stereo(x: np.ndarray) -> np.ndarray:
    if x.ndim == 1:
        x = x.reshape(-1, 1)
    ch = x.shape[1]
    if ch == 2:
        return x
    if ch == 1:
        return np.repeat(x, 2, axis=1)
    return x[:, :2]


class SnapBuffer:
    """FIFO with worklet-style snap (no slow glide)."""

    def __init__(self, rate: int = OUT_RATE, ch: int = OUT_CH):
        self.rate = rate
        self.ch = ch
        self.buf = np.zeros((0, ch), dtype=np.float32)
        self.underruns = 0
        self.snaps = 0
        self.last_snap = ""
        self.prev = np.zeros((ch,), dtype=np.float32)

    def fill_s(self) -> float:
        return self.buf.shape[0] / self.rate

    def push(self, x: np.ndarray) -> None:
        if x.size == 0:
            return
        x = to_stereo(np.ascontiguousarray(x, dtype=np.float32))
        self.buf = np.concatenate([self.buf, x], axis=0)
        max_n = int(MAX_S * self.rate)
        target_n = int(TARGET_S * self.rate)
        if self.buf.shape[0] > max_n:
            self._snap(target_n, "late")

    def _xfade_into(self, dest: np.ndarray) -> None:
        n = min(int(XFADE_S * self.rate), dest.shape[0], max(1, self.buf.shape[0]))
        if n <= 1 or self.buf.shape[0] == 0:
            self.buf = dest
            return
        w = np.linspace(0, 1, n, dtype=np.float32)[:, None]
        head = self.buf[-n:] * (1 - w) + dest[:n] * w
        self.buf = np.concatenate([head, dest[n:]], axis=0)

    def _snap(self, target_n: int, kind: str) -> None:
        if self.buf.shape[0] <= target_n:
            return
        dest = self.buf[-target_n:]
        self._xfade_into(dest)
        self.snaps += 1
        self.last_snap = kind

    def pull(self, n: int) -> np.ndarray:
        out = np.zeros((n, self.ch), dtype=np.float32)
        have = min(n, self.buf.shape[0])
        if have:
            out[:have] = self.buf[:have]
            if have:
                self.prev = out[have - 1]
            self.buf = self.buf[have:]
        if have < n:
            self.underruns += 1
            # hold last sample at ~-60 dB rather than a hard click, then silence
            if have == 0:
                out[:] = 0
        return out


class Pacat:
    def __init__(self):
        self.proc = None

    def start(self) -> None:
        self.close()
        env = os.environ.copy()
        cmd = [
            "pacat", "--playback", f"--device={SINK}",
            f"--rate={OUT_RATE}", f"--channels={OUT_CH}",
            "--format=float32le", "--latency-msec=50",
            "--stream-name=Listen",
        ]
        self.proc = subprocess.Popen(
            cmd, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL,
            stderr=subprocess.PIPE, env=env, bufsize=0,
        )
        log(f"pacat pid {self.proc.pid} -> {SINK}")

    def write(self, x: np.ndarray) -> bool:
        if self.proc is None or self.proc.poll() is not None or self.proc.stdin is None:
            return False
        try:
            self.proc.stdin.write(np.ascontiguousarray(x, dtype="<f4").tobytes())
            self.proc.stdin.flush()
            return True
        except BrokenPipeError:
            return False

    def close(self) -> None:
        if self.proc is None:
            return
        try:
            if self.proc.stdin:
                self.proc.stdin.close()
        except Exception:
            pass
        try:
            self.proc.terminate()
            self.proc.wait(timeout=2)
        except Exception:
            try:
                self.proc.kill()
            except Exception:
                pass
        self.proc = None


def http_connect(url: str, mode: str):
    u = urlparse(url)
    path = u.path if u.path.endswith("/") else u.path + "/"
    req = (
        f"GET {path}api/stream?mode={mode}&xport=1 HTTP/1.1\r\n"
        f"Host: {u.hostname}\r\n"
        f"X-Listen-Password: {PASSWORD}\r\n"
        f"Connection: close\r\n"
        f"\r\n"
    ).encode()
    port = u.port or (443 if u.scheme == "https" else 80)
    raw = socket.create_connection((u.hostname, port), timeout=15)
    if u.scheme == "https":
        raw = ssl.create_default_context().wrap_socket(raw, server_hostname=u.hostname)
    raw.sendall(req)
    raw.settimeout(5)
    return raw


def read_headers(sock) -> tuple[bytes, bool, int]:
    raw = b""
    while b"\r\n\r\n" not in raw:
        chunk = sock.recv(4096)
        if not chunk:
            raise ConnectionError("closed before headers")
        raw += chunk
        if len(raw) > 65536:
            raise ConnectionError("headers too large")
    head, rest = raw.split(b"\r\n\r\n", 1)
    line = head.split(b"\r\n", 1)[0]
    if b" 200 " not in line:
        raise ConnectionError(f"HTTP {line!r}")
    chunked = b"transfer-encoding:" in head.lower() and b"chunked" in head.lower()
    return rest, chunked, int(line.split()[1])


def sync_once(lk: Lock) -> None:
    """NTP-style /api/sync against the relay for a clock offset sample."""
    try:
        import urllib.request
        t1 = now_us()
        req = urllib.request.Request(
            BASE + "/api/sync",
            data=json.dumps({"t1": t1}).encode(),
            headers={
                "Content-Type": "application/json",
                "X-Listen-Password": PASSWORD,
            },
            method="POST",
        )
        with urllib.request.urlopen(req, timeout=5) as r:
            obj = json.loads(r.read().decode())
        t4 = now_us()
        t2 = int(obj.get("t2") or t4)
        t3 = int(obj.get("t3") or t2)
        lk.sync(int(obj.get("t1") or t1), t2, t3, t4)
        remote = obj.get("lock") or {}
        if remote.get("fwd_us") is not None or remote.get("rev_us") is not None:
            lk.observe(t4, fwd_us=remote.get("fwd_us"), rev_us=remote.get("rev_us"),
                       rate=remote.get("rate") or OUT_RATE)
    except Exception as e:
        log(f"sync failed: {type(e).__name__}: {e}")


def run_session(mode: str, lk: Lock, buf: SnapBuffer, play: Pacat, stats: dict) -> str:
    """Returns 'ok-switch' if we should try fallback mode, else 'retry'."""
    sock = http_connect(BASE, mode)
    rest, chunked, _status = read_headers(sock)
    log(f"stream open mode={mode} chunked={chunked}")
    stats["mode"] = mode
    stats["connected"] = True
    stats["connected_at"] = time.strftime("%Y-%m-%d %H:%M:%S")
    body, raw = b"", rest
    chunk_left = None
    last_sync = 0.0
    last_status = 0.0
    last_audio = time.time()
    frames = 0
    # pull cadence
    pull_n = 960  # 20 ms
    next_pull = time.time()

    def feed_bytes(data: bytes):
        nonlocal body, frames, last_audio
        body += data
        while True:
            L = proto.frame_len(body)
            if L is None or len(body) < L:
                break
            fr = proto.unpack(body[:L])
            body = body[L:]
            rx = now_us()
            typ = fr.get("type")
            if typ == getattr(proto, "T_XPORT", 7):
                # transport / armed-idle keepalive from the relay: the link is alive, nothing to play
                last_audio = time.time()
                t = proto.unpack_transport(fr) if hasattr(proto, "unpack_transport") else {}
                if t:
                    stats["transport"] = {k: t.get(k) for k in ("event", "state", "take_id", "song_pos_ns", "sender")}
                continue
            if typ == proto.T_CTRL:
                c = unpack_ctrl(fr["payload"])
                lk.observe(rx, fwd_us=c.get("fwd_us"), rev_us=c.get("rev_us"),
                           rate=c.get("rate") or fr.get("rate") or OUT_RATE)
                continue
            if typ not in (proto.T_S16, proto.T_S24, proto.T_F32):
                continue
            if not proto.crc_ok(fr):
                continue
            try:
                x = decode(fr)
            except Exception:
                continue
            rate = int(fr.get("rate") or OUT_RATE)
            x = resample(to_stereo(x), rate, OUT_RATE)
            theta = lk.clock.theta() if lk.clock.samples else 0
            fwd = fwd_one_way_us(rx, int(fr.get("stamp_us") or rx), theta)
            snapped = lk.observe(rx, fwd_us=fwd, rate=OUT_RATE)
            if snapped:
                # jump straight onto the new number; don't ease
                target_n = int(TARGET_S * OUT_RATE)
                buf._snap(target_n, "lock")
            buf.push(x)
            frames += 1
            last_audio = time.time()
            stats["frames"] = frames
            if frames == 1:
                log(f"first frame typ={typ} rate={rate} n={x.shape} fwd_us={fwd}")
            stats["last_fwd_us"] = fwd

    try:
        while True:
            now = time.time()
            if now - last_sync > 2.0:
                sync_once(lk)
                last_sync = now
            if now - last_status > 1.0:
                snap = lk.snap()
                stats.update({
                    "ok": True,
                    "sink": SINK,
                    "fill_ms": round(buf.fill_s() * 1000, 1),
                    "underruns": buf.underruns,
                    "play_snaps": buf.snaps,
                    "last_play_snap": buf.last_snap,
                    "lock": snap,
                    "nudge_ms": snap.get("nudge_ms"),
                    "nudge_samples": snap.get("nudge_samples"),
                    "locked": snap.get("locked"),
                })
                write_status(stats)
                last_status = now
            if now - last_audio > 30:
                raise ConnectionError("no frames (audio or keepalive) for 30s")
            # play
            while time.time() >= next_pull:
                block = buf.pull(pull_n)
                if not play.write(block):
                    play.start()
                    if not play.write(block):
                        raise ConnectionError("pacat write failed")
                next_pull += pull_n / OUT_RATE
                if time.time() - next_pull > 0.2:
                    next_pull = time.time()
            # recv via select so a stall never freezes playback
            timed_out = False
            try:
                sock.settimeout(0.5)
                r, _, _ = select.select([sock], [], [], 0.02)
                if not r:
                    timed_out = True
                    chunk = b""
                else:
                    chunk = sock.recv(65536)
                    if chunk == b"":
                        raise ConnectionError("stream EOF")
            except (socket.timeout, TimeoutError):
                timed_out = True
                chunk = b""
            except ssl.SSLError as e:
                if "timed out" in str(e).lower() or "want read" in str(e).lower():
                    timed_out = True
                    chunk = b""
                else:
                    raise
            if chunk:
                raw += chunk
                if chunked:
                    while raw:
                        if chunk_left is None:
                            if b"\r\n" not in raw:
                                break
                            line, raw = raw.split(b"\r\n", 1)
                            line = line.split(b";", 1)[0].strip()
                            if not line:
                                continue
                            chunk_left = int(line, 16)
                            if chunk_left == 0:
                                raise ConnectionError("chunked end")
                        take = min(chunk_left, len(raw))
                        feed_bytes(raw[:take])
                        raw = raw[take:]
                        chunk_left -= take
                        if chunk_left == 0:
                            if raw.startswith(b"\r\n"):
                                raw = raw[2:]
                                chunk_left = None
                            elif len(raw) < 2:
                                break
                            else:
                                chunk_left = None
                else:
                    feed_bytes(raw)
                    raw = b""
    finally:
        try:
            sock.close()
        except Exception:
            pass
        stats["connected"] = False
    return "retry"


def main() -> None:
    os.makedirs(os.path.dirname(STATUS_PATH) or ".", exist_ok=True)
    lk = Lock()
    buf = SnapBuffer()
    play = Pacat()
    play.start()
    stats = {"ok": False, "service": "listen-feed-receiver", "url": BASE}
    write_status(stats)
    backoff = 1.0
    mode = MODE_PREF
    tried_fallback = False
    log(f"receiver start url={BASE} mode={mode} sink={SINK} pulse={os.environ.get('PULSE_SERVER', '')}")
    try:
        while True:
            try:
                run_session(mode, lk, buf, play, stats)
                backoff = 1.0
            except Exception as e:
                msg = f"{type(e).__name__}: {e}"
                log(f"session ended: {msg}")
                stats["last_error"] = msg
                stats["connected"] = False
                write_status(stats)
                err = str(e).lower()
                if mode == "pcm24" and not tried_fallback and ("401" in err or "404" in err or "unsupported" in err):
                    mode = "pcm"
                    tried_fallback = True
                    log("falling back to mode=pcm")
                    continue
                time.sleep(backoff)
                backoff = min(10.0, backoff * 1.7)
            else:
                time.sleep(backoff)
    except KeyboardInterrupt:
        log("stopped")
    finally:
        play.close()


if __name__ == "__main__":
    main()
