#!/usr/bin/env python3
"""Minimal stdlib Home Assistant WebSocket client.

Usage: ha_ws.py '<json message without id>' ['<json>' ...]
Token comes from pass (entry ha/token). Prints each result as JSON.
"""
import base64, json, os, socket, struct, sys

HOST, PORT = os.environ.get("HA_HOST", "homeassistant.local"), 8123
import subprocess
TOKEN = subprocess.run(["pass", "show", "ha/token"], capture_output=True, text=True, check=True).stdout.strip()


def send(sock, text):
    data = text.encode()
    header = bytearray([0x81])
    n = len(data)
    if n < 126:
        header.append(0x80 | n)
    elif n < 65536:
        header += bytes([0x80 | 126]) + struct.pack(">H", n)
    else:
        header += bytes([0x80 | 127]) + struct.pack(">Q", n)
    mask = os.urandom(4)
    header += mask
    sock.sendall(bytes(header) + bytes(b ^ mask[i % 4] for i, b in enumerate(data)))


def recv_exact(sock, n):
    buf = b""
    while len(buf) < n:
        chunk = sock.recv(n - len(buf))
        if not chunk:
            raise ConnectionError("closed")
        buf += chunk
    return buf


def recv(sock):
    msg = b""
    while True:
        b1, b2 = recv_exact(sock, 2)
        n = b2 & 0x7F
        if n == 126:
            n = struct.unpack(">H", recv_exact(sock, 2))[0]
        elif n == 127:
            n = struct.unpack(">Q", recv_exact(sock, 8))[0]
        msg += recv_exact(sock, n)
        if b1 & 0x80:
            return json.loads(msg)


def main():
    s = socket.create_connection((HOST, PORT), timeout=30)
    key = base64.b64encode(os.urandom(16)).decode()
    s.sendall((f"GET /api/websocket HTTP/1.1\r\nHost: {HOST}:{PORT}\r\nUpgrade: websocket\r\n"
               f"Connection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n").encode())
    resp = b""
    while b"\r\n\r\n" not in resp:
        resp += s.recv(1)
    recv(s)  # auth_required
    send(s, json.dumps({"type": "auth", "access_token": TOKEN}))
    if recv(s).get("type") != "auth_ok":
        sys.exit("auth failed")
    for i, arg in enumerate(sys.argv[1:], start=1):
        msg = json.loads(arg)
        msg["id"] = i
        send(s, json.dumps(msg))
        while True:
            r = recv(s)
            if r.get("id") == i and r.get("type") == "result":
                print(json.dumps(r, ensure_ascii=False))
                break


if __name__ == "__main__":
    main()
