#!/usr/bin/env bash
# kicad-python — launcher for KiCad's bundled Python with pcbnew available.
#
# Usage:
#   ./kicad-python <script.py> [args...]
#   ./kicad-python -c "import pcbnew; ..."
#   ./kicad-python -m circuit_toolkit.build my-board/
#
# Detects KiCad.app on macOS, KiCad on Linux, or KiCad Flatpak.
# Exits non-zero if KiCad Python is not found.

set -euo pipefail

KICAD_APP="/Applications/KiCad/KiCad.app"
KICAD_PYTHON="${KICAD_APP}/Contents/Frameworks/Python.framework/Versions/3.9/bin/python3"

# Try Flatpak install
if [ -x "/var/lib/flatpak/app/org.kicad.KiCad" ] || command -v flatpak &>/dev/null; then
    FLATPAK_PYTHON=$(flatpak run --command=python3 org.kicad.KiCad 2>/dev/null || true)
    if [ -n "$FLATPAK_PYTHON" ]; then
        KICAD_PYTHON="$FLATPAK_PYTHON"
    fi
fi

# Try Linux install
if [ ! -x "$KICAD_PYTHON" ]; then
    for candidate in \
        /opt/kicad/bin/python3 \
        /usr/bin/kicad-python \
        /usr/bin/python3; do
        if "$candidate" -c "import pcbnew" 2>/dev/null; then
            KICAD_PYTHON="$candidate"
            break
        fi
    done
fi

if [ ! -x "$KICAD_PYTHON" ]; then
    echo "ERROR: KiCad Python not found at $KICAD_PYTHON" >&2
    echo "Install KiCad (kicad.org) or a Flatpak, then re-run." >&2
    exit 1
fi

exec "$KICAD_PYTHON" "$@"
