TOOL_NAME = "list_hue_rooms"
TOOL_DESCRIPTION = """Haalt alle kamers op van een Philips Hue bridge met het aantal lampen per kamer en hun status."""
TOOL_ARGS = '{"type":"object","properties":{"bridge_ip":{"type":"string","description":"IP address of the Hue bridge, e.g. 192.168.178.197"},"app_key":{"type":"string","description":"Hue application key"}},"required":["bridge_ip","app_key"]}'

import os
import requests

from tools._std import tool_error, tool_ok

def run(args: dict) -> str:
    """Haalt alle kamers op van een Philips Hue bridge met lampen per kamer.
    Vereist: bridge_ip (str), app_key (str)."""
    bridge_ip = args.get("bridge_ip") or os.getenv("HUE_BRIDGE_IP", "")
    app_key = args.get("app_key") or os.getenv("HUE_APPLICATION_KEY", "")
    if not bridge_ip or not app_key:
        return tool_error(
            "Fout: zowel 'bridge_ip' als 'app_key' zijn vereist.",
            {"bridge_ip": bool(bridge_ip), "app_key": bool(app_key)},
        )
    try:
        groups_resp = requests.get(
            f"http://{bridge_ip}/api/{app_key}/groups",
            timeout=5,
        )
        lights_resp = requests.get(
            f"http://{bridge_ip}/api/{app_key}/lights",
            timeout=5,
        )
    except requests.RequestException as e:
        return tool_error(f"Netwerkfout: {e}", {"bridge_ip": bridge_ip})

    groups_data = groups_resp.json()
    lights_data = lights_resp.json()

    if isinstance(groups_data, list) and groups_data and groups_data[0].get("error"):
        return tool_error(
            f"Bridge-fout: {groups_data[0]['error']}",
            {"bridge_ip": bridge_ip, "error": groups_data[0]["error"]},
        )

    lines = ["| Kamer | Type | Lampen | Aan | Lamp namen |",
             "|-------|------|--------|-----|------------|"]
    found = False
    claimed_ids: set[str] = set()
    rooms = []
    for group_id, group in groups_data.items():
        if not isinstance(group, dict):
            continue
        if group.get("type") not in ("Room", "Zone"):
            continue
        found = True
        light_ids = group.get("lights", [])
        lamp_names = []
        on_count = 0
        for lid in light_ids:
            claimed_ids.add(str(lid))
            lmeta = lights_data.get(str(lid), {})
            state = lmeta.get("state", {}) if isinstance(lmeta, dict) else {}
            name = lmeta.get("name", lid) if isinstance(lmeta, dict) else lid
            lamp_names.append(name)
            if state.get("on"):
                on_count += 1
        names_str = ", ".join(lamp_names) if lamp_names else "-"
        rooms.append({
            "id": str(group_id),
            "name": group.get("name"),
            "type": group.get("type"),
            "light_count": len(light_ids),
            "lights_on": on_count,
            "light_names": lamp_names,
        })
        lines.append(f"| {group.get('name')} | {group.get('type')} | {len(light_ids)} | {on_count}/{len(light_ids)} | {names_str} |")

    if not found:
        return tool_ok(
            {"bridge_ip": bridge_ip, "rooms": [], "unassigned": []},
            "Geen kamers gevonden op de bridge.",
        )

    # Lampen die niet aan een kamer zijn gekoppeld
    unassigned = []
    for lid, lmeta in lights_data.items():
        if str(lid) in claimed_ids:
            continue
        if not isinstance(lmeta, dict):
            continue
        state = lmeta.get("state", {})
        on = "aan" if state.get("on") else "uit"
        unassigned.append({"id": str(lid), "name": lmeta.get("name", lid), "state": on})

    if unassigned:
        lines.append("")
        lines.append(
            "**Niet gekoppeld aan een kamer:** "
            + ", ".join(f"{item['name']} ({item['state']})" for item in unassigned)
        )

    return tool_ok(
        {"bridge_ip": bridge_ip, "rooms": rooms, "unassigned": unassigned},
        "\n".join(lines),
    )
