#!/usr/bin/env bash
# install-kicad-toolkit — install circuit_toolkit into KiCad's bundled Python
# so pcbnew-dependent builders (pcb.py) can import it.
#
# Usage: ./install-kicad-toolkit.sh
#
# This is a one-time setup. After KiCad updates, re-run to pick up changes.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
TOOLKIT_SRC="$PROJECT_ROOT/kicad-claude-toolkit/python/circuit_toolkit"

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

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

echo "KiCad Python: $KICAD_PYTHON"
echo "circuit_toolkit source: $TOOLKIT_SRC"
echo ""

# Verify pcbnew works
echo "Checking pcbnew..."
if ! "$KICAD_PYTHON" -c "import pcbnew" 2>/dev/null; then
    echo "ERROR: pcbnew not importable. Run KiCad.app at least once." >&2
    exit 1
fi
echo "  pcbnew OK"

# Install circuit_toolkit in development mode
echo ""
echo "Installing circuit_toolkit (editable)..."
pushd "$TOOLKIT_SRC" >/dev/null
# KiCad ships Python 3.9; toolkit pyproject requires >=3.10. Use --no-build-isolation
# to bypass the version check (the code only needs 3.9 features).
"$KICAD_PYTHON" -m pip install --no-build-isolation -e . 2>&1
echo "  installed"

# Also install optional sim deps
echo ""
echo "Installing optional sim deps (matplotlib, numpy)..."
"$KICAD_PYTHON" -m pip install matplotlib numpy 2>&1 || echo "  (non-fatal: sim deps skipped)"

# Verify
echo ""
echo "Verifying..."
"$KICAD_PYTHON" -c "
import pcbnew
import circuit_toolkit
from circuit_toolkit.core.board import Board
from circuit_toolkit.builders.pcb import build_pcb
print(f'  circuit_toolkit {circuit_toolkit.__version__} OK (pcbnew {pcbnew.__file__})')
"

echo ""
echo "Done. circuit_toolkit is now available inside KiCad's Python."
echo "Use ./tools/kicad-python to run scripts with pcbnew access."
