#!/bin/bash
# VoiceBox G2 Firmware Flasher
# Connect the device via USB-C, then run this script.
set -e

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

echo ""
echo "╔══════════════════════════════════════╗"
echo "║  VoiceBox G2 Firmware Flasher        ║"
echo "╚══════════════════════════════════════╝"
echo ""

# Find esptool — try all common locations
find_esptool() {
  command -v esptool.py &>/dev/null && echo "esptool.py" && return
  python3 -m esptool version &>/dev/null 2>&1 && echo "python3 -m esptool" && return
  python -m esptool version &>/dev/null 2>&1 && echo "python -m esptool" && return
  command -v esptool &>/dev/null && echo "esptool" && return
  echo ""
}

ESPTOOL=$(find_esptool)

if [ -z "$ESPTOOL" ]; then
  echo "esptool not found — installing..."
  echo ""

  # Find a working pip
  PIP=""
  if command -v pip3 &>/dev/null; then PIP="pip3";
  elif python3 -m pip --version &>/dev/null 2>&1; then PIP="python3 -m pip";
  elif command -v pip &>/dev/null; then PIP="pip";
  elif python -m pip --version &>/dev/null 2>&1; then PIP="python -m pip";
  fi

  if [ -z "$PIP" ]; then
    echo "❌ Python/pip not found."
    echo ""
    echo "Install Python 3 first:"
    echo "  macOS:   brew install python3"
    echo "  Ubuntu:  sudo apt install python3 python3-pip"
    echo ""
    exit 1
  fi

  echo "Using: $PIP install esptool"
  $PIP install esptool
  echo ""

  ESPTOOL=$(find_esptool)
  if [ -z "$ESPTOOL" ]; then
    echo "❌ esptool install failed. Try manually: pip3 install esptool"
    exit 1
  fi
fi

echo "Using: $ESPTOOL"
$ESPTOOL version
echo ""

# ── Find and select USB serial port ──
PORTS=()
for p in /dev/tty.usbmodem* /dev/tty.usbserial* /dev/tty.SLAB* /dev/ttyACM* /dev/ttyUSB*; do
  [ -e "$p" ] && PORTS+=("$p")
done

if [ ${#PORTS[@]} -eq 0 ]; then
  echo "❌ No USB serial devices found."
  echo ""
  echo "   Connect the device via USB-C and try again."
  echo "   On macOS, you may need to allow the USB accessory in System Settings."
  exit 1
fi

if [ ${#PORTS[@]} -eq 1 ]; then
  PORT="${PORTS[0]}"
  echo "Found device: $PORT"
else
  echo "Multiple USB serial devices found:"
  echo ""
  for i in "${!PORTS[@]}"; do
    echo "  [$((i+1))] ${PORTS[$i]}"
  done
  echo ""
  read -p "Select device [1-${#PORTS[@]}]: " choice
  idx=$((choice - 1))
  if [ "$idx" -lt 0 ] || [ "$idx" -ge ${#PORTS[@]} ]; then
    echo "Invalid selection."
    exit 1
  fi
  PORT="${PORTS[$idx]}"
  echo ""
  echo "Selected: $PORT"
fi
echo ""
echo "Flashing (encrypted)..."
echo ""
$ESPTOOL --chip esp32s3 --port $PORT --baud 460800 \
  --before default_reset --after hard_reset \
  write_flash --encrypt --flash_mode dio --flash_freq 80m --flash_size 16MB \
  0x0 bin/bootloader.bin 0xe000 bin/partition-table.bin 0x16000 bin/ota_data_initial.bin 0x20000 bin/voicebox_g2_qual.bin

echo ""
echo "✅ Flash complete! Device will reboot."
