#!/usr/bin/env python3
"""Einmaliger Test: Karte vom Roborock holen und als roomboy_map.png speichern."""
import asyncio, json
from pathlib import Path

COCKPIT_DIR = Path(__file__).parent

async def fetch_map():
    roborock_file = Path.home() / ".roborock"
    cache = json.loads(roborock_file.read_text())
    from roborock import UserData as UD
    from roborock.devices.device_manager import UserParams as UP, create_device_manager as cdm

    ud = UD.from_dict(cache["user_data"])
    up = UP(username=cache["email"], user_data=ud)
    dm = await cdm(up)

    # Erstes Gerät
    devices = list(dm._devices.values()) if hasattr(dm, '_devices') else []
    print(f"Geräte gefunden: {len(devices)}")

    cfg_path = Path(__file__).parent.parent / "hue" / "roborock_config.json"
    cfg = json.loads(cfg_path.read_text()) if cfg_path.exists() else {}
    duid = cfg.get("devices", [{}])[0].get("duid", "")
    print(f"DUID: {duid!r}")

    device = await dm.get_device(duid)
    print(f"Gerät: {device}")

    if device.v1_properties is None:
        print("FEHLER: kein V1-Protokoll")
        return

    await device.v1_properties.start()
    trait = device.v1_properties.map_content
    if trait is None:
        print("FEHLER: keine Map-Unterstützung")
        return

    print("Lade Karte…")
    await trait.refresh()
    img_bytes = trait.image_content
    if not img_bytes:
        print("FEHLER: leere Karte")
        return

    out = COCKPIT_DIR / "roomboy_map.png"
    out.write_bytes(img_bytes)
    print(f"Gespeichert: {out} ({len(img_bytes)} bytes)")

    try:
        cal = trait.map_data.calibration() if trait.map_data else None
        if cal:
            print(f"Kalibrierung: {cal}")
    except Exception as e:
        print(f"Kalibrierung: nicht verfügbar ({e})")

asyncio.run(fetch_map())
