#!/usr/bin/env python3
"""
familiar_bridge.py · the Familiar's nervous system (Spellworks, agent D)

STARTER CODE, NOT YET TESTED ON HARDWARE.

One small asyncio process on the Pi in the head:
  * a WebSocket server on 127.0.0.1:8765 for the show page (Chromium kiosk)
  * a serial line to the ESP32 light node: 115200 baud, one JSON message per line
  * GPIO through gpiozero: one reed switch per drawer, one ultrasonic distance sensor
Every line from the page goes to the node unchanged. Every line from the node,
and every drawer or presence event, goes to every connected page.
  * {"t":"say","text":"...","voice":"<character>"} lines from the page are
    spoken here instead, with Piper (an offline neural voice) through a small
    sox effect per character, or espeak-ng, one line at a time. They are
    never logged and never sent to the node.

Privacy: it never logs what anyone types. Key events from the node are counted,
never printed.

Run on a laptop with no Pi and no node:
    GPIOZERO_PIN_FACTORY=mock python3 familiar_bridge.py --serial none --verbose

Needs (Raspberry Pi OS, from apt, no pip):
    sudo apt install python3-websockets python3-serial python3-gpiozero python3-lgpio
Voice (optional): piper plus its .onnx voices in /opt/familiar/voices, sox, espeak-ng
    sudo apt install sox espeak-ng
"""

import argparse
import asyncio
import glob
import json
import logging
import os
import shlex
import shutil
import socket
import subprocess
import tempfile
import threading
import time

FW = "familiar-bridge 0.1"
log = logging.getLogger("familiar-bridge")

# BCM pin numbers. One normally open reed switch per drawer, wired pin to GND;
# the magnet sits on the drawer, so a closed drawer holds the switch closed.
# Kept clear of I2S audio (GPIO 18 to 21), PWM audio (12, 13), I2C (2, 3) and UART (14, 15).
DRAWER_PINS = {
    "ember": 4, "loom": 5, "wire": 6, "static": 16, "garage": 17,
    "feed": 22, "grove": 25, "typewriter": 26, "mirror": 27,
}
# HC-SR04 style sensor: 5 V supply, TRIG straight in, ECHO through a divider so the
# Pi only ever sees about 3 V (gpiozero docs: 330 ohm from ECHO, 470 ohm to GND,
# junction to the GPIO). The HC-SR04P runs on 3.3 V and needs no divider.
TRIG_PIN, ECHO_PIN = 23, 24
NEAR_CM = 150        # someone is here
FAR_CM = 220         # someone has gone (hysteresis gap between the two)
AWAY_HOLD_S = 30     # how long beyond FAR_CM before we call it empty

# The Familiar's voices, one per character id. Keep in step with
# assets/js/core/voices.js (VOICE_CHARACTERS): "piper" is the model name (the
# .onnx file in --voices-dir), "sox" the effect chain put on the wav before
# aplay, "espeak" the fallback as (voice+variant, pitch 0..99, words per
# minute) with a similar pitch and pace. "tube" has no words in the browser
# (it is the murmur); here it is the Familiar's voice through a small old
# speaker. An unknown id speaks as the Familiar.
VOICES = {
    "familiar": {"piper": "en_US-ryan-medium", "sox": "pitch -150 reverb 18",
                 "espeak": ("en-us+m3", 32, 140)},
    "child": {"piper": "en_US-amy-medium", "sox": "pitch 450 tempo 1.06",
              "espeak": ("en-us+f4", 85, 175)},
    "adult": {"piper": "en_US-lessac-medium", "sox": "",
              "espeak": ("en-us", 50, 160)},
    "calm": {"piper": "en_US-amy-medium", "sox": "tempo 0.86 reverb 40",
             "espeak": ("en-us+f2", 42, 125)},
    "spellbound": {"piper": "en_US-ryan-medium", "sox": "pitch -420 tempo 0.9 reverb 70 echo 0.8 0.7 90 0.3",
                   "espeak": ("en-us+m7", 12, 128)},
    "tube": {"piper": "en_US-ryan-medium", "sox": "highpass 320 lowpass 3200 overdrive 4 gain -4",
             "espeak": ("en-us+m3", 35, 145)},
}
DEFAULT_VOICE = "familiar"


def voice_for(voice_id) -> dict:
    """The voice settings for a character id (the Familiar when unknown)."""
    return VOICES.get(str(voice_id or "").strip().lower(), VOICES[DEFAULT_VOICE])


# ----------------------------------------------------------------------------
# systemd: READY and WATCHDOG through $NOTIFY_SOCKET, no extra library needed
# ----------------------------------------------------------------------------
def sd_notify(msg: str) -> None:
    addr = os.environ.get("NOTIFY_SOCKET")
    if not addr:
        return
    if addr.startswith("@"):
        addr = "\0" + addr[1:]
    try:
        with socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) as s:
            s.connect(addr)
            s.sendall(msg.encode())
    except OSError as e:
        log.debug("sd_notify failed: %s", e)


class Bridge:
    def __init__(self, loop: asyncio.AbstractEventLoop, args):
        self.loop = loop
        self.args = args
        self.clients = set()
        self.serial = None
        self.serial_lock = threading.Lock()
        self.serial_path = None
        self.drawers = {}          # id -> open (bool)
        self.near = None
        self.counts = {"page_lines": 0, "node_lines": 0, "keys": 0, "casts": 0, "said": 0}
        self.say_lock = threading.Lock()

    # ------------------------------------------------------------------ pages
    async def handler(self, ws, path=None):  # path: older websockets versions pass it
        self.clients.add(ws)
        log.info("page connected (%d open)", len(self.clients))
        try:
            await ws.send(json.dumps({"evt": "hello", "fw": FW, "node": self.serial is not None}))
            for did, is_open in self.drawers.items():
                if is_open:
                    await ws.send(json.dumps({"evt": "drawer", "id": did, "open": True}))
            if self.near is not None:
                await ws.send(json.dumps({"evt": "presence", "near": self.near}))
            async for message in ws:
                for line in str(message).splitlines():
                    self.from_page(line.strip())
        except Exception as e:  # a page going away is normal
            log.debug("page closed: %s", e)
        finally:
            self.clients.discard(ws)
            log.info("page disconnected (%d open)", len(self.clients))

    def from_page(self, line: str) -> None:
        if not line:
            return
        try:
            msg = json.loads(line)
        except ValueError:
            log.debug("dropped a line that is not JSON")
            return
        self.counts["page_lines"] += 1
        if not isinstance(msg, dict):
            return
        if msg.get("t") == "say":
            self.say(str(msg.get("text", ""))[:200], str(msg.get("voice") or DEFAULT_VOICE)[:32])
            return
        if msg.get("t") == "ping" and self.serial is None:
            # no node attached: answer for it, so the page knows the bridge is alive
            self.broadcast({"evt": "pong", "fw": FW + " (no node)"})
            return
        self.to_node(json.dumps(msg, separators=(",", ":")))

    # ------------------------------------------------------------------ voice
    def say(self, text: str, voice: str = DEFAULT_VOICE) -> None:
        """Speak one line in a character's voice. Never logged (privacy)."""
        text = " ".join(text.split())
        if not text:
            return
        self.counts["said"] += 1
        threading.Thread(target=self._say_blocking, args=(text, voice), daemon=True).start()

    def _piper_model(self, name: str):
        """The .onnx path for a Piper model name, else the --piper-model default, else None."""
        for path in (os.path.join(self.args.voices_dir, name + ".onnx"), self.args.piper_model):
            if path and os.path.exists(path):
                return path
        return None

    def _say_blocking(self, text: str, voice: str = DEFAULT_VOICE) -> None:
        if not self.say_lock.acquire(timeout=20):  # one voice at a time
            return
        v = voice_for(voice)
        tmp = None
        try:
            piper = shutil.which("piper")
            model = self._piper_model(v["piper"]) if piper else None
            if piper and model:
                # piper writes a wav (with its own sample rate), sox adds the character, aplay plays it.
                # The files live in RAM (/dev/shm) and are deleted right after.
                tmp = tempfile.mkdtemp(prefix="familiar-say-", dir="/dev/shm" if os.path.isdir("/dev/shm") else None)
                raw_wav = os.path.join(tmp, "line.wav")
                fx_wav = os.path.join(tmp, "line-fx.wav")
                subprocess.run([piper, "--model", model, "--output_file", raw_wav], input=text.encode(),
                               stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=30, check=True)
                play = raw_wav
                if v["sox"] and shutil.which("sox"):
                    try:
                        subprocess.run(["sox", raw_wav, fx_wav] + shlex.split(v["sox"]),
                                       stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=20, check=True)
                        play = fx_wav
                    except Exception as e:  # a bad effect never silences the voice
                        log.warning("sox effect failed, playing the plain voice: %s", e)
                subprocess.run(["aplay", "-q", play], stderr=subprocess.DEVNULL, timeout=60)
            elif shutil.which("espeak-ng"):
                ev, pitch, speed = v["espeak"]
                subprocess.run(["espeak-ng", "-v", ev, "-p", str(pitch), "-s", str(speed), text],
                               timeout=30, stderr=subprocess.DEVNULL)
            else:
                log.warning("no voice installed (piper or espeak-ng)")
        except Exception as e:
            log.warning("voice failed: %s", e)
            # last try, so the line is still heard: plain espeak-ng
            try:
                if shutil.which("espeak-ng"):
                    subprocess.run(["espeak-ng", "-s", "150", "-p", "35", text], timeout=30, stderr=subprocess.DEVNULL)
            except Exception:
                pass
        finally:
            if tmp:
                shutil.rmtree(tmp, ignore_errors=True)
            self.say_lock.release()

    def broadcast(self, msg) -> None:
        line = msg if isinstance(msg, str) else json.dumps(msg, separators=(",", ":"))
        for ws in list(self.clients):
            asyncio.ensure_future(self._send(ws, line))

    async def _send(self, ws, line):
        try:
            await ws.send(line)
        except Exception:
            self.clients.discard(ws)

    def broadcast_threadsafe(self, msg) -> None:
        self.loop.call_soon_threadsafe(self.broadcast, msg)

    # ------------------------------------------------------------------- node
    def find_port(self):
        if self.args.serial == "none":
            return None
        if self.args.serial != "auto":
            return self.args.serial
        for pattern in ("/dev/serial/by-id/*", "/dev/ttyACM*", "/dev/ttyUSB*"):
            hits = sorted(glob.glob(pattern))
            if hits:
                return hits[0]
        return None

    def to_node(self, line: str) -> None:
        with self.serial_lock:
            if self.serial is None:
                return
            try:
                self.serial.write((line + "\n").encode())
            except Exception as e:
                log.warning("serial write failed: %s", e)
                self.close_serial()

    def close_serial(self):
        try:
            if self.serial:
                self.serial.close()
        except Exception:
            pass
        self.serial = None

    def serial_thread(self):
        """Owns the serial port: opens it, reads lines, reopens after a cable pull."""
        import serial  # pyserial
        while True:
            path = self.find_port()
            if path is None:
                if self.args.serial == "none":
                    return
                time.sleep(2)
                continue
            try:
                port = serial.Serial()
                port.port = path
                port.baudrate = self.args.baud
                port.timeout = 0.2
                port.dtr = False   # keep the ESP32's auto-reset lines quiet if we can
                port.rts = False
                port.open()
                with self.serial_lock:
                    self.serial = port
                    self.serial_path = path
                log.info("node on %s at %d baud", path, self.args.baud)
                self.broadcast_threadsafe({"evt": "log", "msg": "node connected"})
                time.sleep(1.2)    # if the node did reset, give it a moment to say hello
                self.to_node('{"t":"ping"}')
                buf = b""
                while True:
                    chunk = port.read(256)
                    if chunk:
                        buf += chunk
                        while b"\n" in buf:
                            raw, buf = buf.split(b"\n", 1)
                            self.from_node(raw.decode("utf-8", "replace").strip())
                        if len(buf) > 4096:
                            buf = b""
            except Exception as e:
                log.warning("serial: %s (retrying in 2 s)", e)
                with self.serial_lock:
                    self.close_serial()
                self.broadcast_threadsafe({"evt": "log", "msg": "node disconnected"})
                time.sleep(2)

    def from_node(self, line: str) -> None:
        if not line:
            return
        self.counts["node_lines"] += 1
        try:
            msg = json.loads(line)
        except ValueError:
            log.debug("node said something that is not JSON (%d bytes)", len(line))
            return
        evt = msg.get("evt") if isinstance(msg, dict) else None
        if evt == "key":
            self.counts["keys"] += 1           # count only, never the character
        elif evt == "cast":
            self.counts["casts"] += 1
        elif evt in ("log", "hello", "pong"):
            log.info("node: %s", {k: v for k, v in msg.items() if k != "char"})
        self.broadcast_threadsafe(line)

    # ------------------------------------------------------------------- GPIO
    def setup_gpio(self):
        if self.args.no_gpio:
            log.info("GPIO off (--no-gpio)")
            return
        try:
            from gpiozero import Button, DistanceSensor
        except Exception as e:
            log.warning("gpiozero not available, no drawers or presence: %s", e)
            return
        self._buttons = []
        for did, pin in DRAWER_PINS.items():
            try:
                b = Button(pin, pull_up=True, bounce_time=0.05)
            except Exception as e:
                log.warning("drawer %s on GPIO%d: %s", did, pin, e)
                continue
            self.drawers[did] = not b.is_pressed      # pressed = magnet close = drawer shut
            b.when_released = lambda d=did: self.drawer_event(d, True)
            b.when_pressed = lambda d=did: self.drawer_event(d, False)
            self._buttons.append(b)
        try:
            # queue_len smooths the jitter you get without pigpio (pigpio does not run on a Pi 5)
            self._sonar = DistanceSensor(echo=ECHO_PIN, trigger=TRIG_PIN, max_distance=4.0, queue_len=5)
            log.info("distance sensor on TRIG %d, ECHO %d", TRIG_PIN, ECHO_PIN)
        except Exception as e:
            self._sonar = None
            log.warning("no distance sensor: %s", e)

    def drawer_event(self, did, is_open):
        self.drawers[did] = is_open
        log.info("drawer %s %s", did, "open" if is_open else "shut")
        self.broadcast_threadsafe({"evt": "drawer", "id": did, "open": is_open})

    async def presence_loop(self):
        sonar = getattr(self, "_sonar", None)
        if sonar is None:
            return
        near_reads, far_since = 0, None
        while True:
            await asyncio.sleep(0.15)
            try:
                cm = sonar.distance * 100.0
            except Exception:
                continue
            changed = False
            if not self.near:
                near_reads = near_reads + 1 if cm < NEAR_CM else 0
                if near_reads >= 2:
                    self.near, changed, far_since = True, True, None
            else:
                if cm > FAR_CM:
                    far_since = far_since or time.monotonic()
                    if time.monotonic() - far_since > AWAY_HOLD_S:
                        self.near, changed = False, True
                else:
                    far_since = None
            if changed:
                log.info("presence: %s", "near" if self.near else "away")
                self.broadcast({"evt": "presence", "near": self.near, "cm": int(cm)})

    # --------------------------------------------------------------- watchdog
    async def watchdog_loop(self):
        sd_notify("READY=1")
        while True:
            sd_notify("WATCHDOG=1")
            await asyncio.sleep(10)
            if self.args.verbose:
                log.info("alive: %d pages, node %s, counts %s", len(self.clients),
                         "on " + str(self.serial_path) if self.serial else "off", self.counts)


async def main(args):
    import websockets  # python3-websockets

    loop = asyncio.get_running_loop()
    bridge = Bridge(loop, args)
    bridge.setup_gpio()
    threading.Thread(target=bridge.serial_thread, daemon=True).start()
    async with websockets.serve(bridge.handler, args.host, args.port, max_size=65536):
        log.info("%s listening on ws://%s:%d", FW, args.host, args.port)
        await asyncio.gather(bridge.presence_loop(), bridge.watchdog_loop())


if __name__ == "__main__":
    p = argparse.ArgumentParser(description="The Familiar's hardware bridge")
    p.add_argument("--host", default="127.0.0.1", help="stay on 127.0.0.1: nothing outside the Pi should reach this")
    p.add_argument("--port", type=int, default=8765)
    p.add_argument("--serial", default="auto", help="auto, none, or a path like /dev/ttyUSB0")
    p.add_argument("--baud", type=int, default=115200)
    p.add_argument("--no-gpio", action="store_true", help="skip drawers and presence")
    p.add_argument("--piper-model", default="/opt/familiar/voices/en_US-lessac-medium.onnx",
                   help="Piper voice used when a character's own model is missing (falls back to espeak-ng)")
    p.add_argument("--voices-dir", default="/opt/familiar/voices",
                   help="folder of Piper .onnx voices, one per character model name (see VOICES)")
    p.add_argument("--piper-rate", type=int, default=22050, help="kept for older setups (the wav now carries its own rate)")
    p.add_argument("--verbose", action="store_true")
    a = p.parse_args()
    logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
    try:
        asyncio.run(main(a))
    except KeyboardInterrupt:
        pass
