#!/home/markus/workspace/skills/integrations/crafty/.venv/bin/python3
"""CLI für Storz & Bickel Crafty über BLE.

shortcut: Shebang zeigt auf .venv in diesem Checkout — bei Umsiedeln des Repos anpassen.


Usage: crafty [scan|status|temp N|heat on|off]
"""
import asyncio
import sys

from storzandbickel_ble import StorzBickelClient
from storzandbickel_ble.models import DeviceType

SCAN_TIMEOUT = 15.0


async def connect():
    client = StorzBickelClient()
    devices = await client.scan(timeout=SCAN_TIMEOUT, device_type=DeviceType.CRAFTY)
    if not devices:
        sys.exit("Kein Crafty gefunden — Gerät eingeschaltet? S&B-App getrennt?")
    return client, await client.connect_device(devices[0])


def dump_state(state):
    for k in sorted(vars(state)):
        v = getattr(state, k)
        if not k.startswith("_") and v is not None:
            print(f"{k}: {v}")


async def main():
    cmd = sys.argv[1] if len(sys.argv) > 1 else "status"
    arg = sys.argv[2] if len(sys.argv) > 2 else None

    if cmd == "scan":
        for d in await StorzBickelClient().scan(timeout=SCAN_TIMEOUT, device_type=DeviceType.CRAFTY):
            print(d)
        return

    client, dev = await connect()
    try:
        await dev.update_state()
        if cmd == "status":
            dump_state(dev.state)
        elif cmd == "temp" and arg:
            await dev.set_target_temperature(float(arg))
            await dev.update_state()
            print(f"Zieltemperatur: {dev.state.target_temperature} °C")
        elif cmd == "heat" and arg in ("on", "off"):
            await (dev.turn_heater_on() if arg == "on" else dev.turn_heater_off())
            print(f"Heizung: {arg}")
        else:
            sys.exit(__doc__)
    finally:
        await dev.disconnect()


if __name__ == "__main__":
    asyncio.run(main())
