#!/usr/bin/env bash
# =============================================================================
# WILD ECHO::DEPLOY — Raspberry Pi Setup Script
# One-command field deployment setup for WILD ECHO biodiversity monitoring
#
# Usage:
#   curl -sSL https://wildecho.com.au/install.sh | sudo bash -s -- \
#     --site "Yellingbo Reserve" \
#     --lat -37.686 \
#     --lon 145.514 \
#     --token YOUR_WILD_ECHO_TOKEN
#
# Optional:
#   --schedule  dawn_dusk|dawn_only|24h|night|custom  (default: dawn_dusk)
#   --apn       4G APN (default: telstra.internet)
#   --telegram  Telegram bot token for alerts
#   --chat-id   Telegram chat ID for alerts
#   --api-url   Override WILD ECHO API URL
# =============================================================================

set -euo pipefail

# ── Colours ──────────────────────────────────────────────────────────────────
RED='\033[0;31m'
GREEN='\033[0;32m'
AMBER='\033[0;33m'
BLUE='\033[0;34m'
BOLD='\033[1m'
NC='\033[0m'

log()   { echo -e "${GREEN}[WILD ECHO]${NC} $*"; }
warn()  { echo -e "${AMBER}[WARN]${NC} $*"; }
error() { echo -e "${RED}[ERROR]${NC} $*" >&2; exit 1; }
head()  { echo -e "\n${BOLD}${BLUE}══ $* ══${NC}"; }

# ── Defaults ─────────────────────────────────────────────────────────────────
SITE_NAME=""
SITE_LAT=""
SITE_LON=""
WILD_ECHO_TOKEN=""
RECORD_SCHEDULE="dawn_dusk"
SIM_APN="telstra.internet"
TELEGRAM_BOT_TOKEN=""
TELEGRAM_CHAT_ID=""
WILD_ECHO_API_URL="https://api.wildecho.com.au/v1"
RECORDER_URL="https://wildecho.com.au/deploy/recorder.py"
SERVICE_URL="https://wildecho.com.au/deploy/wildecho-recorder.service"
INSTALL_DIR="/opt/wildecho"
SERVICE_NAME="wildecho-recorder"
UPLOAD_INTERVAL_MINUTES=30

# ── Arg parsing ──────────────────────────────────────────────────────────────
while [[ $# -gt 0 ]]; do
  case "$1" in
    --site)       SITE_NAME="$2";            shift 2 ;;
    --lat)        SITE_LAT="$2";             shift 2 ;;
    --lon)        SITE_LON="$2";             shift 2 ;;
    --token)      WILD_ECHO_TOKEN="$2";      shift 2 ;;
    --schedule)   RECORD_SCHEDULE="$2";      shift 2 ;;
    --apn)        SIM_APN="$2";              shift 2 ;;
    --telegram)   TELEGRAM_BOT_TOKEN="$2";   shift 2 ;;
    --chat-id)    TELEGRAM_CHAT_ID="$2";     shift 2 ;;
    --api-url)    WILD_ECHO_API_URL="$2";    shift 2 ;;
    *) warn "Unknown argument: $1"; shift ;;
  esac
done

# ── Validate required args ───────────────────────────────────────────────────
[[ -z "$SITE_NAME" ]]       && error "Required: --site \"Site Name\""
[[ -z "$SITE_LAT" ]]        && error "Required: --lat <latitude>"
[[ -z "$SITE_LON" ]]        && error "Required: --lon <longitude>"
[[ -z "$WILD_ECHO_TOKEN" ]] && error "Required: --token YOUR_WILD_ECHO_TOKEN"

# ── Root check ───────────────────────────────────────────────────────────────
[[ $EUID -ne 0 ]] && error "This script must be run as root (sudo)"

# ── Generate site ID ─────────────────────────────────────────────────────────
SITE_ID="WE-$(echo "${SITE_NAME}${SITE_LAT}${SITE_LON}" | md5sum | head -c 8 | tr '[:lower:]' '[:upper:]')"

echo ""
echo -e "${BOLD}${GREEN}"
echo "  ██╗    ██╗██╗██╗     ██████╗     ███████╗ ██████╗██╗  ██╗ ██████╗ "
echo "  ██║    ██║██║██║     ██╔══██╗    ██╔════╝██╔════╝██║  ██║██╔═══██╗"
echo "  ██║ █╗ ██║██║██║     ██║  ██║    █████╗  ██║     ███████║██║   ██║"
echo "  ██║███╗██║██║██║     ██║  ██║    ██╔══╝  ██║     ██╔══██║██║   ██║"
echo "  ╚███╔███╔╝██║███████╗██████╔╝    ███████╗╚██████╗██║  ██║╚██████╔╝"
echo "   ╚══╝╚══╝ ╚═╝╚══════╝╚═════╝     ╚══════╝ ╚═════╝╚═╝  ╚═╝ ╚═════╝ "
echo -e "${NC}"
echo -e "  ${BOLD}WILD ECHO::DEPLOY${NC} — Raspberry Pi Field Setup"
echo -e "  Site: ${BOLD}${SITE_NAME}${NC}  |  ID: ${BOLD}${SITE_ID}${NC}"
echo -e "  Coords: ${SITE_LAT}, ${SITE_LON}  |  Schedule: ${RECORD_SCHEDULE}"
echo ""

# ── 1. System update ─────────────────────────────────────────────────────────
head "Step 1/8: System Update"
apt-get update -qq
apt-get upgrade -y -qq
log "System packages updated"

# ── 2. Install system deps ───────────────────────────────────────────────────
head "Step 2/8: Installing System Dependencies"
apt-get install -y -qq \
  python3 python3-pip python3-venv python3-dev \
  ffmpeg sox libsox-fmt-all \
  git curl wget \
  libasound2-dev portaudio19-dev \
  libatlas-base-dev \
  libopenblas-dev \
  i2c-tools \
  gpsd gpsd-clients \
  libssl-dev libffi-dev \
  build-essential
log "System dependencies installed"

# ── 3. Enable I2C (for INA219, accelerometer) ────────────────────────────────
head "Step 3/8: Configuring Hardware Interfaces"
if grep -q "^#dtparam=i2c_arm" /boot/config.txt 2>/dev/null; then
  sed -i 's/^#dtparam=i2c_arm/dtparam=i2c_arm/' /boot/config.txt
elif ! grep -q "^dtparam=i2c_arm" /boot/config.txt 2>/dev/null; then
  echo "dtparam=i2c_arm=on" >> /boot/config.txt
fi
modprobe i2c-dev 2>/dev/null || true
log "I2C enabled"

# ── 4. Create install directory and venv ─────────────────────────────────────
head "Step 4/8: Creating WILD ECHO Directory"
mkdir -p "$INSTALL_DIR"/{recordings,uploads,logs}
python3 -m venv "$INSTALL_DIR/venv"
log "Created $INSTALL_DIR with venv"

# ── 5. Install Python packages ───────────────────────────────────────────────
head "Step 5/8: Installing Python Packages"
"$INSTALL_DIR/venv/bin/pip" install --upgrade pip -q
"$INSTALL_DIR/venv/bin/pip" install \
  librosa \
  soundfile \
  numpy \
  requests \
  birdnetlib \
  schedule \
  gpiozero \
  RPi.GPIO \
  adafruit-circuitpython-ina219 \
  smbus2 \
  ephem \
  python-dotenv \
  gps3 \
  -q
log "Python packages installed"

# ── 6. Download recorder.py ──────────────────────────────────────────────────
head "Step 6/8: Downloading WILD ECHO Recorder"
if curl -sSL --fail "$RECORDER_URL" -o "$INSTALL_DIR/recorder.py" 2>/dev/null; then
  log "Downloaded recorder.py from $RECORDER_URL"
else
  warn "Could not download recorder.py from server — using bundled version"
  # Bundled fallback: create a minimal recorder.py that imports from the package
  cat > "$INSTALL_DIR/recorder.py" << 'PYEOF'
#!/usr/bin/env python3
"""WILD ECHO Recorder — fetched from server on first run"""
import os, urllib.request, sys

RECORDER_URL = "https://wildecho.com.au/deploy/recorder.py"
try:
    print("[WILD ECHO] Downloading latest recorder...")
    urllib.request.urlretrieve(RECORDER_URL, __file__)
    print("[WILD ECHO] Downloaded. Restarting...")
    os.execv(sys.executable, [sys.executable] + sys.argv)
except Exception as e:
    print(f"[WILD ECHO] Could not download recorder: {e}")
    print("[WILD ECHO] Please check network and retry.")
    sys.exit(1)
PYEOF
fi
chmod +x "$INSTALL_DIR/recorder.py"

# ── 7. Write .env config ─────────────────────────────────────────────────────
head "Step 7/8: Writing Configuration"
cat > "$INSTALL_DIR/.env" << EOF
# WILD ECHO Field Recorder Configuration
# Generated by pi_setup.sh on $(date -u +"%Y-%m-%d %Human:%M:%S UTC")
# Site ID: ${SITE_ID}

# ── API ───────────────────────────────────────────────────────────────────────
WILD_ECHO_API_URL=${WILD_ECHO_API_URL}
WILD_ECHO_TOKEN=${WILD_ECHO_TOKEN}

# ── Site Identity ────────────────────────────────────────────────────────────
SITE_ID=${SITE_ID}
SITE_NAME=${SITE_NAME}
SITE_LAT=${SITE_LAT}
SITE_LON=${SITE_LON}

# ── Telegram Alerts ──────────────────────────────────────────────────────────
TELEGRAM_BOT_TOKEN=${TELEGRAM_BOT_TOKEN}
TELEGRAM_CHAT_ID=${TELEGRAM_CHAT_ID}

# ── 4G Connectivity ──────────────────────────────────────────────────────────
SIM_APN=${SIM_APN}

# ── Recording Schedule ───────────────────────────────────────────────────────
# Options: dawn_dusk | dawn_only | 24h | night | custom
RECORD_SCHEDULE=${RECORD_SCHEDULE}
# Used when RECORD_SCHEDULE=custom (comma-separated HH:MM times)
RECORD_TIMES=

# ── Upload Settings ──────────────────────────────────────────────────────────
UPLOAD_INTERVAL_MINUTES=${UPLOAD_INTERVAL_MINUTES}
MAX_RECORDING_HOURS=2
RECORDING_SAMPLE_RATE=48000

# ── Hardware ─────────────────────────────────────────────────────────────────
# Set to 1 if hardware is connected
HAS_GPS=0
HAS_INA219=0
HAS_ACCELEROMETER=0
HAS_LED=0

# GPIO pins for LEDs (BCM numbering)
LED_GREEN_PIN=17
LED_AMBER_PIN=27
LED_RED_PIN=22

# ── Local Analysis ───────────────────────────────────────────────────────────
ENABLE_LOCAL_ANALYSIS=1
ALERT_ON_INVASIVE=1
# Comma-separated invasive species to trigger immediate alert
INVASIVE_SPECIES=cane_toad,red_fox,feral_cat

# ── Logging ──────────────────────────────────────────────────────────────────
LOG_LEVEL=INFO
LOG_DIR=/opt/wildecho/logs
RECORDING_DIR=/opt/wildecho/recordings
UPLOAD_DIR=/opt/wildecho/uploads
EOF
chmod 600 "$INSTALL_DIR/.env"
log "Configuration written to $INSTALL_DIR/.env"

# ── 8. Install systemd service ───────────────────────────────────────────────
head "Step 8/8: Installing Systemd Service"

# Determine the service user (pi or current sudo user)
SERVICE_USER="pi"
if ! id -u pi &>/dev/null; then
  SERVICE_USER="${SUDO_USER:-$(logname 2>/dev/null || echo root)}"
  warn "User 'pi' not found, using '$SERVICE_USER'"
fi

# Try downloading service file, else write inline
if ! curl -sSL --fail "$SERVICE_URL" -o "/etc/systemd/system/${SERVICE_NAME}.service" 2>/dev/null; then
  cat > "/etc/systemd/system/${SERVICE_NAME}.service" << EOF
[Unit]
Description=WILD ECHO Field Recorder
After=network.target
Wants=network-online.target

[Service]
Type=simple
User=${SERVICE_USER}
WorkingDirectory=${INSTALL_DIR}
ExecStart=${INSTALL_DIR}/venv/bin/python3 ${INSTALL_DIR}/recorder.py
Restart=always
RestartSec=30
StandardOutput=journal
StandardError=journal
Environment=PYTHONUNBUFFERED=1
EnvironmentFile=${INSTALL_DIR}/.env

[Install]
WantedBy=multi-user.target
EOF
fi

# Fix service user in downloaded file if needed
sed -i "s/^User=.*/User=${SERVICE_USER}/" "/etc/systemd/system/${SERVICE_NAME}.service"

# Fix ownership
chown -R "$SERVICE_USER":"$SERVICE_USER" "$INSTALL_DIR" 2>/dev/null || \
  chown -R root:root "$INSTALL_DIR"

systemctl daemon-reload
systemctl enable "$SERVICE_NAME"
systemctl start "$SERVICE_NAME"

sleep 2
if systemctl is-active --quiet "$SERVICE_NAME"; then
  log "Service ${SERVICE_NAME} is running ✓"
else
  warn "Service started but may need network — check: journalctl -u ${SERVICE_NAME} -f"
fi

# ── Done ─────────────────────────────────────────────────────────────────────
echo ""
echo -e "${BOLD}${GREEN}╔══════════════════════════════════════════════════════════╗${NC}"
echo -e "${BOLD}${GREEN}║          ✅  WILD ECHO SETUP COMPLETE                    ║${NC}"
echo -e "${BOLD}${GREEN}╚══════════════════════════════════════════════════════════╝${NC}"
echo ""
echo -e "  ${BOLD}Site Name:${NC}   ${SITE_NAME}"
echo -e "  ${BOLD}Site ID:${NC}     ${SITE_ID}"
echo -e "  ${BOLD}Location:${NC}    ${SITE_LAT}, ${SITE_LON}"
echo -e "  ${BOLD}Schedule:${NC}    ${RECORD_SCHEDULE}"
echo -e "  ${BOLD}API:${NC}         ${WILD_ECHO_API_URL}"
echo -e "  ${BOLD}Install Dir:${NC} ${INSTALL_DIR}"
echo ""
echo -e "  ${BOLD}Service Status:${NC}"
systemctl status "$SERVICE_NAME" --no-pager -l | head -5 | sed 's/^/    /'
echo ""
echo -e "  ${BOLD}Useful commands:${NC}"
echo -e "    journalctl -u ${SERVICE_NAME} -f      # Live logs"
echo -e "    systemctl restart ${SERVICE_NAME}      # Restart recorder"
echo -e "    cat ${INSTALL_DIR}/.env                # View config"
echo ""
