#!/usr/bin/env bash
# cleat: {"name":"Simulators","keyword":"sim","icon":"iphone","subtitle":"Boot an iOS, watchOS or visionOS simulator","version":"1.0.1","requires":["xcrun"],"examples":["sim iphone 17","sim "]}
#
# Lists the simulators Xcode has available, booted ones first, and boots the
# selected one in the Simulator app. Needs Xcode's command line tools.
set -euo pipefail

if [ "${1:-}" = "--run" ]; then
    udid="$2"
    xcrun simctl boot "$udid" 2>/dev/null || true
    open -a Simulator --args -CurrentDeviceUDID "$udid"
    exit 0
fi

query="$(printf '%s' "${1:-}" | tr '[:upper:]' '[:lower:]')"
# Without Xcode there is no list; say so instead of a Python traceback.
devices="$(xcrun simctl list devices available -j 2>/dev/null || true)"
if [ -z "$devices" ]; then
    echo "No simulators found. Install Xcode and open it once." >&2
    exit 1
fi
printf '%s' "$devices" | python3 -c '
import json, sys
query = sys.argv[1]
data = json.load(sys.stdin)
rows = []
for runtime, devices in data.get("devices", {}).items():
    label = runtime.rsplit(".", 1)[-1].replace("-", " ").replace("iOS ", "iOS ").replace("OS ", "OS ")
    label = label.replace("iOS", "iOS").replace("watchOS", "watchOS").replace("tvOS", "tvOS").replace("xrOS", "visionOS")
    parts = label.split(" ", 1)
    label = parts[0] + " " + parts[1].replace(" ", ".") if len(parts) > 1 else label
    for device in devices:
        name = device.get("name", "")
        state = device.get("state", "")
        hay = (name + " " + label).lower()
        if query and query not in hay:
            continue
        icon = "iphone"
        if "ipad" in name.lower(): icon = "ipad"
        elif "watch" in name.lower(): icon = "applewatch"
        elif "tv" in name.lower(): icon = "appletv"
        elif "vision" in name.lower(): icon = "visionpro"
        rows.append((state != "Booted", name, label, state, device.get("udid", ""), icon))
rows.sort()
for booted, name, label, state, udid, icon in rows[:60]:
    subtitle = label + (" · Booted" if state == "Booted" else " · Return boots it")
    print(json.dumps({"title": name, "subtitle": subtitle, "arg": udid, "icon": icon}))
' "$query"
