"""Sync resource queries: clusters and machine hostnames."""

from __future__ import annotations

import json
from typing import Any

from omni import OmniClient


def _coerce_item(raw: Any) -> dict[str, Any] | None:
    if isinstance(raw, dict):
        return raw
    if isinstance(raw, str):
        try:
            loaded = json.loads(raw)
        except json.JSONDecodeError:
            return None
        if isinstance(loaded, dict):
            return loaded
    return None


def main() -> None:
    client = OmniClient()
    try:
        clusters = client.resources.list({"namespace": "default", "type": "Clusters.omni.sidero.dev"})
        cluster_items = clusters.get("items", [])
        print(f"clusters: {len(cluster_items)}")

        machine_statuses = client.resources.list({"namespace": "default", "type": "MachineStatuses.omni.sidero.dev"})
        items = machine_statuses.get("items", [])
        print("machines:")
        for raw in items:
            item = _coerce_item(raw)
            if item is None:
                continue
            metadata = item.get("metadata", {})
            spec = item.get("spec", {})
            network = spec.get("network", {}) if isinstance(spec, dict) else {}
            machine_id = metadata.get("id")
            hostname = network.get("hostname") if isinstance(network, dict) else None
            if isinstance(machine_id, str):
                print(f"  {machine_id} -> {hostname or '<no-hostname>'}")
    finally:
        client.close()


if __name__ == "__main__":
    main()
