#!/bin/bash
# Frontend Service Control Script for ROA2WEB Unified App
# Manages the Vite dev server on port 3000

# Script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$SCRIPT_DIR"

# Source helper functions
source "$SCRIPT_DIR/scripts/service-helpers.sh"

# Service configuration
SERVICE_NAME="Frontend Unified"
PORT=3000
LOG_FILE="/tmp/vite-unified.log"
NODE_MODULES_DIR="$ROOT_DIR/node_modules"

# Function to start frontend
start_frontend() {
  print_header "Starting $SERVICE_NAME"

  # Check if port is already in use
  if ! check_port_available $PORT "$SERVICE_NAME"; then
    print_warning "$SERVICE_NAME may already be running"
    print_info "Use './start-frontend.sh status' to check or './start-frontend.sh stop' to stop it"
    return 1
  fi

  # Check node_modules
  if [ ! -d "$NODE_MODULES_DIR" ]; then
    print_info "node_modules not found, installing frontend dependencies..."
    print_info "This may take 2-3 minutes..."
    cd "$ROOT_DIR"
    npm install
    if [ $? -ne 0 ]; then
      print_error "npm install failed"
      return 1
    fi
  fi

  # Start Vite dev server
  print_info "Starting Vite dev server..."
  cd "$ROOT_DIR"

  # Start in background with nohup
  nohup npm run dev > "$LOG_FILE" 2>&1 &
  local pid=$!

  print_info "Started with PID: $pid"
  print_info "Log file: $LOG_FILE"

  # Wait for port to be ready
  if wait_for_port $PORT "$SERVICE_NAME" 10; then
    print_success "$SERVICE_NAME started successfully!"
    echo ""
    print_info "🌐 Frontend URLs:"
    echo "  • Local:   http://localhost:$PORT"
    echo "  • Network: http://$(hostname -I | awk '{print $1}'):$PORT"
    echo ""
    print_info "📄 View logs: tail -f $LOG_FILE"
    return 0
  else
    print_error "Failed to start $SERVICE_NAME (timeout waiting for port $PORT)"
    print_info "Check logs: tail -20 $LOG_FILE"
    return 1
  fi
}

# Function to stop frontend
stop_frontend() {
  print_header "Stopping $SERVICE_NAME"

  kill_port $PORT "$SERVICE_NAME"

  # Clean up log file (optional - comment out if you want to keep logs)
  # if [ -f "$LOG_FILE" ]; then
  #   rm "$LOG_FILE"
  #   print_info "Cleaned up log file"
  # fi

  return 0
}

# Function to restart frontend
restart_frontend() {
  print_header "Restarting $SERVICE_NAME"

  stop_frontend
  sleep 2
  start_frontend

  return $?
}

# Function to show frontend status
status_frontend() {
  print_header "$SERVICE_NAME Status"

  if check_service_status $PORT "$SERVICE_NAME"; then
    echo ""
    print_info "Service is healthy"

    # Show recent logs
    if [ -f "$LOG_FILE" ]; then
      echo ""
      tail_logs "$LOG_FILE" 10
    fi
    return 0
  else
    echo ""
    print_warning "Service is not running"

    # Show last logs if available
    if [ -f "$LOG_FILE" ]; then
      echo ""
      print_info "Last logs before shutdown:"
      tail_logs "$LOG_FILE" 10
    fi
    return 1
  fi
}

# Main script logic
case "${1:-}" in
  start)
    start_frontend
    ;;
  stop)
    stop_frontend
    ;;
  restart)
    restart_frontend
    ;;
  status)
    status_frontend
    ;;
  *)
    echo "Usage: $0 {start|stop|restart|status}"
    echo ""
    echo "Commands:"
    echo "  start   - Start the frontend dev server"
    echo "  stop    - Stop the frontend dev server"
    echo "  restart - Restart the frontend dev server"
    echo "  status  - Show frontend status and recent logs"
    echo ""
    echo "Examples:"
    echo "  ./start-frontend.sh start    # Start frontend"
    echo "  ./start-frontend.sh restart  # Quick restart (most common for dev)"
    echo "  ./start-frontend.sh status   # Check if running"
    exit 1
    ;;
esac
