#!/bin/bash

# ==============================================================================
# Mobile Development Environment Launcher
# ==============================================================================
# This script configures and starts the development server for mobile testing.
# It automatically detects the local machine's IP address and exposes the
# Vite server to the local network, allowing Android/iOS devices to connect.
# ==============================================================================

set -e

# Colors for output
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# Function to print banner
print_banner() {
  echo -e "${BLUE}"
  echo "================================================================"
  echo "   🚗 MyRoadTrip - Mobile Development Environment"
  echo "================================================================"
  echo -e "${NC}"
}

# Function to detect IP address
detect_ip() {
  local ip_addr=""

  # MacOS
  if [[ "$OSTYPE" == "darwin"* ]]; then
    # Try en0 (usually Wi-Fi)
    ip_addr=$(ipconfig getifaddr en0 || true)
    
    # Try en1 (usually Ethernet on some Macs) if en0 fails
    if [ -z "$ip_addr" ]; then
      ip_addr=$(ipconfig getifaddr en1 || true)
    fi
  # Linux
  elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
    ip_addr=$(hostname -I | awk '{print $1}')
  fi

  echo "$ip_addr"
}

# Function to check dependencies
check_dependencies() {
  if ! command -v pnpm &> /dev/null; then
    echo -e "${RED}Error: pnpm is not installed.${NC}"
    echo "Please install pnpm to continue."
    exit 1
  fi
}

# Main execution
main() {
  print_banner

  echo -e "${BLUE}[INFO]${NC} Checking dependencies..."
  check_dependencies

  echo -e "${BLUE}[INFO]${NC} Detecting local network IP..."
  IP=$(detect_ip)

  if [ -z "$IP" ]; then
    echo -e "${RED}[ERROR] Could not detect local IP address.${NC}"
    echo -e "${YELLOW}Tip: Ensure you are connected to a Wi-Fi or Ethernet network.${NC}"
    exit 1
  fi

  API_URL="http://$IP:3001"
  
  echo -e "${GREEN}[SUCCESS]${NC} Network configuration detected!"
  echo -e "----------------------------------------------------------------"
  echo -e " 🏠 Local IP:   ${YELLOW}$IP${NC}"
  echo -e " 🔌 API URL:    ${YELLOW}$API_URL${NC}"
  echo -e "----------------------------------------------------------------"
  echo -e "${BLUE}[INFO]${NC} Setting VITE_API_URL environment variable..."
  
  # Export for the web app to pick up
  export VITE_API_URL="$API_URL"

  echo -e "${BLUE}[INFO]${NC} Starting Vite dev server..."
  echo -e "${YELLOW}Press Ctrl+C to stop the server.${NC}"
  echo ""

  # Run the dev command with host exposed
  # We use exec to replace the shell process with pnpm, ensuring signals are passed correctly
  exec pnpm --filter=@my-roadtrip/web dev --host 0.0.0.0
}

# Run main function
main
