#!/bin/sh
# Adom KiCad Bridge Server — Startup Script (macOS / Linux)
# Tries system Python first, then KiCad's bundled Python on macOS.

set -e

DIR="$(cd "$(dirname "$0")" && pwd)"

echo "[Adom KiCad Bridge] Starting server..."

# 1. Prefer python3.13 / 3.12 / 3.11 / 3.10 in PATH (the type-hint syntax in
#    handlers requires 3.10+). Fall back to system python3 (may be 3.9 on
#    older macOS — that path is fine if the handlers only use older syntax,
#    but warn).
for cand in python3.13 python3.12 python3.11 python3.10; do
    if command -v "$cand" >/dev/null 2>&1; then
        echo "[Adom KiCad Bridge] Using $cand"
        exec "$cand" "$DIR/server.py" "$@"
    fi
done

# 2. KiCad 9 bundled Python on macOS
KICAD_MAC_PY="/Applications/KiCad/KiCad.app/Contents/Frameworks/Python.framework/Versions/Current/bin/python3"
if [ -x "$KICAD_MAC_PY" ]; then
    echo "[Adom KiCad Bridge] Using KiCad 9 bundled Python"
    exec "$KICAD_MAC_PY" "$DIR/server.py" "$@"
fi

# 3. System python3 (last resort — may be 3.9 on stock macOS, which
#    will fail at handler-import time on the type-hint syntax).
if command -v python3 >/dev/null 2>&1; then
    PY_VER=$(python3 -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")')
    case "$PY_VER" in
        3.10|3.11|3.12|3.13|3.14)
            echo "[Adom KiCad Bridge] Using system python3 ($PY_VER)"
            exec python3 "$DIR/server.py" "$@"
            ;;
        *)
            echo "[Adom KiCad Bridge] WARNING: python3 is $PY_VER (need >= 3.10). Trying anyway..."
            exec python3 "$DIR/server.py" "$@"
            ;;
    esac
fi

echo "[Adom KiCad Bridge] ERROR: No Python 3.10+ found. Install via 'brew install [email protected]' or KiCad 9+." >&2
exit 1