#!/usr/bin/env python3
"""Decode a testo QR code (testo 300, testo 330/320) into measurements.

    python3 decode_testo_qr.py qrcode.png     # pip install -r requirements.txt (patched pyzbar + Pillow)
    python3 decode_testo_qr.py example.bin    # raw bytes already read from the QR code

Steps: binary QR bytes -> gunzip -> UTF-8 text -> one JSON document per line -> normalize.
"""
import gzip
import json
import sys
from datetime import datetime, timezone

SCHEMA_T300 = "measurement-slim-v2.0.0"   # testo 300, field "schema", timestamps in milliseconds
SCHEMA_T330 = "slim-schema-v1."           # testo 330/320, field "$schema", timestamps in seconds


def read_qr_bytes(path: str) -> bytes:
    if path.endswith(".bin"):
        with open(path, "rb") as f:
            return f.read()
    from PIL import Image
    from pyzbar.pyzbar import ZBarSymbol, decode

    codes = decode(Image.open(path), symbols=[ZBarSymbol.QRCODE], binary=True)
    if len(codes) != 1:
        raise ValueError(f"expected exactly one QR code, found {len(codes)}")
    return codes[0].data


def parse_measurements(qr_bytes: bytes) -> list[dict]:
    text = gzip.decompress(qr_bytes).decode("utf-8")  # gzip also verifies its CRC
    return [json.loads(line) for line in text.splitlines() if line.strip()]


def to_utc(timestamp: str, schema: str) -> datetime:
    seconds = int(timestamp) / 1000 if SCHEMA_T300 in schema else int(timestamp)
    return datetime.fromtimestamp(seconds, tz=timezone.utc)


def channels(measurement: dict):
    """Yield (quantity, label, unit, value, status, time) per value, for both formats."""
    schema = measurement.get("$schema") or measurement.get("schema", "")
    for channel in measurement.get("channels", []):
        quantity = channel["type"]["name"]  # testo 330: language-neutral id; testo 300: display label
        label = channel["type"].get("description", quantity)
        unit = channel["unit"]["name"]
        for v in channel.get("values", []):
            status = v.get("status")  # invalid / overrange / underrange / empty (testo 330: value is then 0.0)
            value = None if status else v.get("value")
            yield quantity, label, unit, value, status, to_utc(v["timeStamp"], schema)


if __name__ == "__main__":
    for m in parse_measurements(read_qr_bytes(sys.argv[1])):
        schema = m.get("$schema") or m.get("schema", "")
        print(f"== {m['type'].get('id', m['type']['name'])} ({schema.rsplit('/', 1)[-1]})")
        for quantity, label, unit, value, status, time in channels(m):
            shown = status if status else f"{value} {unit}"
            print(f"  {quantity:<32} {label:<14} {shown:<16} {time:%Y-%m-%d %H:%M:%S}Z")
