#!/bin/sh

check_tool() {
  if ! command -v "$1" >/dev/null; then
    echo "Required tool \`$2\` are not installed or binary \`$1\` not found." >&2
    exit 1
  fi
}

BIN_RSYNC=${BIN_RSYNC:-rsync}
BIN_SSH=${BIN_SSH:-ssh}
BIN_SCP=${BIN_SCP:-scp}
BIN_GIT=${BIN_GIT:-git}

check_tool $BIN_RSYNC "rsync"
check_tool $BIN_SSH "openssh"
check_tool $BIN_SCP "openssh"
check_tool $BIN_GIT "git"

# Color codes
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
WHITE='\033[1;37m'
NC='\033[0m' # No Color

if [ -z "$LOG_VIEW" ]; then
  LOG_VIEW=NRV
fi
   
# Logging functions
log_info()    { text=$1; shift; printf "%b%s ${text}%b\n" "$BLUE"   "$INFO_EM" "$@" "$NC" >&2; }
log_success() { text=$1; shift; printf "%b%s ${text}%b\n" "$GREEN"  "$SUCC_EM" "$@" "$NC" >&2; }
log_warning() { text=$1; shift; printf "%b%s ${text}%b\n" "$YELLOW" "$WARN_EM" "$@" "$NC" >&2; }
log_error()   { text=$1; shift; printf "%b%s ${text}%b\n" "$RED"    "$ERRO_EM" "$@" "$NC" >&2; }
log_step()    { text=$1; shift; printf "%b%s ${text}%b\n" "$PURPLE" "$STEP_EM" "$@" "$NC" >&2; }

log_header() { printf "\n%b=== %s ===%b\n" "$WHITE" "$@" "$NC"; }

setup_remote_directory() {
  local remote="$1"
  local remote_dir="$2"
  
  log_step "Creating remote profile directory..."
  if $BIN_SSH "$remote" "mkdir -p '$remote_dir' && mkdir -p '$remote_dir/script'" 2>/dev/null; then
    log_success "Remote directory ready"
  else
    log_error "Failed to create remote directory"
    exit 1
  fi
}

init_remote_git() {
  local remote="$1"
  local remote_dev_dir="$2"
  
  log_step "Initializing git repository on remote..."
  if $BIN_SSH "$remote" "
    cd '$remote_dev_dir' && 
    if ! git -c safe.directory=$remote_dev_dir rev-parse --is-inside-work-tree >/dev/null 2>&1; then 
      echo \"Initializing git repository...\"
      cd '$remote_dev_dir'
      git -c safe.directory=$remote_dev_dir init
    fi
  " >/dev/null 2>&1; then
    log_success "Git repository ready"
  else
    log_warning "Git setup failed"
  fi
}

sync_project_files() {
  local local_dir="$1"
  local remote="$2"
  local remote_dir="$3"
  
  log_step "Syncing required files..."
  
  if $BIN_GIT ls-files -z | $BIN_RSYNC -av --delete --files-from=- --from0 "$local_dir/" "$remote:$remote_dir/"; then
    log_success "Required files synced"
  else
    log_error "Failed to sync files"
    exit 1
  fi
}

run_vproxy_bot() {
  local local_dir="$1"
  local local_project="$2"
  local remote="$3"
  local remote_dir="$4"
  local project="$5"

  log_header "DEPLOYING TG_BOT PROJECT"
  
  if [ ! -d "$local_project" ]; then
    log_error "Project directory not found: $local_project"
    exit 1
  fi

  setup_remote_directory "$remote" "$remote_dir"
  init_remote_git "$remote" "$remote_dir"
  sync_project_files "$local_dir" "$remote" "$remote_dir"

  if $BIN_SCP -r "$local_dir/package/vproxy-bot/.env" "$remote:$remote_dir/package/vproxy-bot/"; then
    log_success "env file synced"
  else
    log_error "Failed to sync env file in $LOCAL_DIR/package/vproxy-bot/.env"
    exit 1
  fi

  $BIN_SSH "$remote" " cd '$remote_dir' && git add ."
  
  log_header "RUNNING ON REMOTE"
  log_info "Executing: ${WHITE}cd '$remote_dir' && cd '$project' && env VPROXY_REMOTE_MODE=1 nix develop --impure -c cargo run${NC}"
  
  if $BIN_SSH -tt "$REMOTE" \
     "cd '$remote_dir/package/$project' && env VPROXY_REMOTE_MODE=1 nix develop --impure -c cargo run"; then
    log_success "Remote execution completed successfully!"
  else
    log_error "Remote execution failed"
    exit 1
  fi
}

run_dreamproxy() {
  local local_dir="$1"
  local dreamproxy_dir="$local_dir/package/dreamproxy"

  log_header "RUNNING DREAMPROXY PROJECT"

  [ -f "$dreamproxy_dir/.env" ] || (
    log_error "env file not found: $dreamproxy_dir/.env"
    exit 1
  )

  set -a
  source "$dreamproxy_dir/.env"
  set +a

  nix run "$local_dir#dreamproxy-bot"
}

check_remote_disk_space() {
  local remote="$1"
  local path="$2"
  
  log_step "Checking remote disk space..."
  
  # Get disk usage information using df
  local disk_info=$($BIN_SSH "$remote" "df '$path' 2>/dev/null | tail -1" 2>/dev/null)
  
  if [ -z "$disk_info" ]; then
    log_warning "Could not retrieve disk space information for $path"
    return 0
  fi
  
  # Parse df output: Filesystem Size Used Avail Use% Mounted
  local used_percent=$(echo "$disk_info" | awk '{print $5}' | sed 's/%//')
  local available=$(echo "$disk_info" | awk '{print $4}')
  local size=$(echo "$disk_info" | awk '{print $2}')
  local filesystem=$(echo "$disk_info" | awk '{print $1}')
  
  if [ -z "$used_percent" ] || [ -z "$available" ] || [ -z "$size" ]; then
    log_warning "Could not parse disk space information"
    return 0
  fi
  
  # Calculate available percentage
  local available_percent=$((100 - used_percent))
  
  # Convert sizes from KB to human readable format
  local size_mb=$((size / 1024))
  local available_mb=$((available / 1024))
  
  log_info "Disk space on ${WHITE}$filesystem${NC}:"
  log_info "Total: ${WHITE}${size_mb}MB${BLUE}, Available: ${WHITE}${available_mb}MB${BLUE} (${WHITE}${available_percent}%%${BLUE})"
  
  # Check if available space is less than 10%
  if [ "$available_percent" -lt 10 ]; then
    log_error "⚠️  LOW DISK SPACE WARNING!"
    log_error "Only ${WHITE}${available_percent}%%${RED} (${WHITE}${available_mb}MB${RED}) available on remote dev directory"
    log_error "Consider running: ${WHITE}$0 clear all${NC} to free up space"
    log_warning "Continuing anyway, but build may fail due to insufficient space..."
    return 1
  elif [ "$available_percent" -lt 20 ]; then
    log_warning "Disk space getting low: ${WHITE}${available_percent} prec${GREEN} available"
    log_info "Consider cleaning up when convenient: ${WHITE}$0 clear${NC}"
  else
    log_success "Disk space OK: ${WHITE}${available_percent}%%${GREEN} available"
  fi
  
  return 0
}

get_leptos_port() {
  local port="$1"
  local default_port="3000"
  
  if [ -z "$port" ]; then
    echo "$default_port"
    return 0
  fi
  
  # Validate port is a number and in valid range
  if ! echo "$port" | grep -q '^[0-9]\+$' || [ "$port" -lt 1024 ] || [ "$port" -gt 65535 ]; then
    log_warning "Invalid port: $port, using default: $default_port"
    echo "$default_port"
  else
    echo "$port"
  fi
}

watch_and_sync() {
  local remote="$1"
  local local_dir="$2"
  local remote_dir="$3"
  local project="$4"
  
  log_step "Starting file watcher for live sync..."
  
  # Check if inotifywait is available
  if ! command -v inotifywait >/dev/null 2>&1; then
    log_error "inotifywait not found. Please install inotify-tools:"
    log_info "  Ubuntu/Debian: sudo apt-get install inotify-tools"
    log_info "  Arch: sudo pacman -S inotify-tools"
    log_info "  Or use your package manager to install inotify-tools"
    return 1
  fi
  
  # Function to sync files
  sync_files() {
    log_info "Syncing files to remote..."
    if $BIN_GIT ls-files -z | $BIN_RSYNC -av --delete --files-from=- --from0 "$local_dir/" "$remote:$remote_dir/" >/dev/null 2>&1; then
      log_success "Files synced successfully"
      # Trigger git add on remote to refresh nix
      $BIN_SSH "$remote" "cd '$remote_dir' && git add . >/dev/null 2>&1" || true
    else
      log_warning "Sync failed, retrying in next change..."
    fi
  }
  
  # Watch for file changes (excluding target/, .git/, node_modules/)
  log_info "Watching for file changes in: ${WHITE}$local_dir${NC}"
  log_info "Excluding: target/, .git/, node_modules/, .env files"
  log_info "Press ${WHITE}Ctrl+C${NC} to stop watching"
  
  # Use inotifywait to monitor file changes
  inotifywait -m -r \
    --exclude '(target/|\.git/|node_modules/|\.env)' \
    --format '%w%f %e' \
    -e modify,create,delete,move \
    "$local_dir" 2>/dev/null | while read file event; do
    
    # Debounce rapid changes (wait a bit to batch multiple changes)
    sleep 0.5
    
    # Skip if file doesn't exist (might have been deleted)
    if [[ "$event" != *"DELETE"* ]] && [ ! -f "$file" ] && [ ! -d "$file" ]; then
      continue
    fi
    
    log_step "File changed: $(basename "$file") ($event)"
    sync_files
  done
}

# Parse command line arguments
WATCH_MODE=false
PROJECT=""
PROFILE=""
CUSTOM_PORT=""
CUSTOM_RELOAD_PORT=""

# Parse flags and arguments
while [ $# -gt 0 ]; do
  case "$1" in
    -w)
      WATCH_MODE=true
      shift
      ;;
    -p)
      if [ -z "$2" ] || [ "${2#-}" != "$2" ]; then
        log_error "Option -p requires a port number"
        exit 1
      fi
      CUSTOM_PORT="$2"
      shift 2
      ;;
    -r)
      if [ -z "$2" ] || [ "${2#-}" != "$2" ]; then
        log_error "Option -r requires a reload port number"
        exit 1
      fi
      CUSTOM_RELOAD_PORT="$2"
      shift 2
      ;;
    help)
      help
      exit 0
      ;;
    clear)
      SUBCOMMAND="clear"
      shift
      ;;
    *)
      if [ -z "$PROJECT" ] && [ -z "$SUBCOMMAND" ]; then
        PROJECT="$1"
      elif [ -z "$PROFILE" ]; then
        PROFILE="$1"
      else
        log_error "Too many arguments: $1"
        exit 1
      fi
      shift
      ;;
  esac
done

APP_NAME="$(basename $0)"

help() {
  printf "%bUsage:%b %s [-w] [-p port] [-r reload_port] <project|clear> [profile|all]\n" "$WHITE" "$NC" "$APP_NAME" 
  printf "%bProject Examples:%b\n" "$WHITE" "$NC"
  printf "  %s vproxy-web [profile]              - Deploy and serve vproxy-web\n" "$APP_NAME"
  printf "  %s -p 4000 vproxy-web [profile]      - Deploy with custom port 4000\n" "$APP_NAME"
  printf "  %s vproxy-bot [profile]                  - Deploy vproxy-bot\n" "$APP_NAME"
  printf "%bWatch Examples:%b\n" "$WHITE" "$NC"
  printf "  %s -w vproxy-web [profile]           - Live development with auto-sync\n" "$APP_NAME"
  printf "  %s -w -p 4000 vproxy-web [profile]   - Watch mode with custom port\n" "$APP_NAME"
  printf "  %s -w -p 4000 -r 4001 vproxy-web     - Watch with custom ports\n" "$APP_NAME"
  printf "%bClear Examples:%b\n" "$WHITE" "$NC"
  printf "  %s clear [profile]                   - Clear specific profile dev directory\n" "$APP_NAME"
  printf "  %s clear all                         - Clear all profiles in dev directory\n" "$APP_NAME"
}

if [ -z "$PROJECT" ] && [ -z "$SUBCOMMAND" ]; then
  log_error "Missing required arguments"
  help
  exit 1
fi

log_header "VPROXY REMOTE RUNNER"

REMOTE_DEV_DIR="/root/dev"

# Set up port configuration
LEPTOS_PORT=$(get_leptos_port "$CUSTOM_PORT")
if [ -n "$CUSTOM_RELOAD_PORT" ]; then
  LEPTOS_RELOAD_PORT=$(get_leptos_port "$CUSTOM_RELOAD_PORT")
else
  # Auto-calculate reload port as main port + 1
  LEPTOS_RELOAD_PORT=$((LEPTOS_PORT + 1))
fi

if [ -n "$CUSTOM_PORT" ]; then
  LEPTOS_SITE_ADDR="0.0.0.0:$LEPTOS_PORT"
  log_info "Using custom port: ${WHITE}$LEPTOS_PORT${NC}"
else
  LEPTOS_SITE_ADDR=""
  log_info "Using default port: ${WHITE}$LEPTOS_PORT${NC}"
fi

if [ -n "$CUSTOM_RELOAD_PORT" ]; then
  log_info "Using custom reload port: ${WHITE}$LEPTOS_RELOAD_PORT${NC}"
else
  log_info "Using auto-calculated reload port: ${WHITE}$LEPTOS_RELOAD_PORT${NC}"
fi

clear_all_profiles() {
  log_header "CLEARING ALL PROFILES"
  log_warning "This will remove ALL profile directories from remote dev directory!"
  read -p "Are you sure you want to continue? (y/n): " CONFIRM
  if [ "$CONFIRM" != "y" ]; then
    log_info "Operation cancelled"
    exit 0
  fi
  
  log_step "Removing all profiles from remote dev directory..."
  if $BIN_SSH "$REMOTE" "rm -rf $REMOTE_DEV_DIR/* 2>/dev/null || true"; then
    log_success "All profiles cleared successfully"
    
    # Check disk space after clearing
    log_step "Checking disk space after cleanup..."
    check_remote_disk_space "$REMOTE" "$REMOTE_DEV_DIR"
  else
    log_error "Failed to clear all profiles"
    exit 1
  fi
}

clear_single_profile() {
  local profile="$1"
  local remote_dir="$REMOTE_DEV_DIR/$profile"

  
  log_header "CLEARING PROFILE: $profile"
  log_warning "This will remove the profile directory: ${WHITE}$remote_dir${NC}"
  read -p "Are you sure you want to continue? (y/n): " CONFIRM
  if [ "$CONFIRM" != "y" ]; then
    log_info "Operation cancelled"
    exit 0
  fi
  
  log_step "Removing profile directory from remote..."
  if $BIN_SSH "$REMOTE" "rm -rf '$remote_dir' 2>/dev/null || true"; then
    log_success "Profile ${WHITE}$profile${NC} cleared successfully"
    
    # Check disk space after clearing
    log_step "Checking disk space after cleanup..."
    check_remote_disk_space "$REMOTE" "$REMOTE_DEV_DIR"
  else
    log_error "Failed to clear profile $profile"
    exit 1
  fi
}

# If no profile specified, try to get from git user name or use a default
if [ -z "$PROFILE" ]; then
  log_step "Auto-detecting profile for clearing..."
  GIT_USER=$($BIN_GIT config user.name 2>/dev/null | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]//g')
  if [ -n "$GIT_USER" ]; then
    PROFILE="$GIT_USER"
    log_success "Using git user profile: ${WHITE}$PROFILE${NC}"
  else
    PROFILE="default"
    log_warning "Git user not found, using: ${WHITE}$PROFILE${NC}"
  fi
else
  log_info "Using specified profile: ${WHITE}$PROFILE${NC}"
fi

# Handle clear command first
if [ "$SUBCOMMAND" = "clear" ]; then
  if [ "$PROFILE" = "all" ]; then
    clear_all_profiles
  else
    clear_single_profile "$PROFILE"
  fi
  exit 0
fi

# Handle watch mode
if [ "$WATCH_MODE" = "true" ]; then
  # Only support vproxy-web for now
  if [ "$PROJECT" != "vproxy-web" ]; then
    log_error "Watch mode currently only supports vproxy-web"
    exit 1
  fi
  
  # Set up directories
  REMOTE_DIR="$REMOTE_DEV_DIR/$PROFILE"
  
  log_step "Detecting local directories..."
  if git_root=$($BIN_GIT rev-parse --show-toplevel 2>/dev/null); then
    LOCAL_DIR="$git_root"
    log_success "Found git root: ${WHITE}$LOCAL_DIR${NC}"
  else
    LOCAL_DIR="$(pwd)"
    log_warning "Not in git repo, using current dir: ${WHITE}$LOCAL_DIR${NC}"
    read -p "Are you really want continue? (y/n): " CONTINUE
    if [ "$CONTINUE" != "y" ]; then
      log_error "Aborting..."
      exit 0
    fi
  fi
  
  LOCAL_PROJECT="$LOCAL_DIR/package/$PROJECT"
  
  if [ ! -d "$LOCAL_PROJECT" ]; then
    log_error "Project directory not found: $LOCAL_PROJECT"
    exit 1
  fi
  
  log_header "WATCH MODE: $PROJECT"
  log_info "Profile: ${WHITE}$PROFILE${NC}"
  log_info "Local project: ${WHITE}$LOCAL_PROJECT${NC}"
  log_info "Remote target: ${WHITE}$REMOTE:$REMOTE_DIR${NC}"
  
  # Check disk space
  check_remote_disk_space "$REMOTE" "$REMOTE_DEV_DIR"
  
  # Initial setup (similar to regular deployment)
  log_step "Setting up remote environment..."
  if $BIN_SSH "$REMOTE" "mkdir -p '$REMOTE_DIR' && mkdir -p '$REMOTE_DIR/script'" 2>/dev/null; then
    log_success "Remote directory ready"
  else
    log_error "Failed to create remote directory"
    exit 1
  fi
  
  # Initialize git repository
  log_step "Initializing git repository on remote..."
  if $BIN_SSH "$REMOTE" "
    cd '$REMOTE_DEV_DIR' && 
    if ! git -c safe.directory=$REMOTE_DEV_DIR rev-parse --is-inside-work-tree >/dev/null 2>&1; then 
      echo \"Initializing git repository...\"
      cd '$REMOTE_DEV_DIR'
      git -c safe.directory=$REMOTE_DEV_DIR init
    fi
  " >/dev/null 2>&1; then
    log_success "Git repository ready"
  else
    log_warning "Git setup failed"
  fi
  
  # Initial sync
  log_step "Initial file sync..."
  if $BIN_GIT ls-files -z | $BIN_RSYNC -av --delete --files-from=- --from0 "$LOCAL_DIR/" "$REMOTE:$REMOTE_DIR/" >/dev/null; then
    log_success "Initial sync completed"
  else
    log_error "Initial sync failed"
    exit 1
  fi
  
  # Sync .env if exists
  if [ -f "$LOCAL_PROJECT/.env" ]; then
    if $BIN_SCP -r "$LOCAL_PROJECT/.env" "$REMOTE:$REMOTE_DIR/"; then
      log_success "env file synced from $LOCAL_PROJECT/.env to $REMOTE:$REMOTE_DIR/.env"
    else
      log_warning "Failed to sync env file"
    fi
  else
    log_info "No .env file found in $LOCAL_PROJECT, skipping env sync"
  fi
  
  $BIN_SSH "$REMOTE" "cd '$REMOTE_DIR' && git add ." >/dev/null 2>&1 || true
  
  log_header "STARTING WATCH MODE"
  log_info "Starting remote cargo leptos watch..."
  log_info "Starting local file watcher..."
  log_info "Port forwarding: remote:$LEPTOS_PORT -> local:$LEPTOS_PORT (app)"
  log_info "Port forwarding: remote:$LEPTOS_RELOAD_PORT -> local:$LEPTOS_RELOAD_PORT (reload)"
  log_info "Access the application at: ${WHITE}http://localhost:$LEPTOS_PORT${NC}"
  if [ -n "$LEPTOS_SITE_ADDR" ]; then
    log_info "Using custom LEPTOS_SITE_ADDR: ${WHITE}$LEPTOS_SITE_ADDR${NC}"
  fi
  log_info "Hot reload on port: ${WHITE}$LEPTOS_RELOAD_PORT${NC}"
  log_warning "Press ${WHITE}Ctrl+C${NC} to stop both processes"
  
  # Create a temporary script to handle cleanup on exit
  trap 'log_warning "Stopping watch mode..."; kill $(jobs -p) 2>/dev/null || true; exit 0' INT TERM
  
  # Start file watcher in background
  watch_and_sync "$REMOTE" "$LOCAL_DIR" "$REMOTE_DIR" "$PROJECT" &
  WATCHER_PID=$!
  
  # Start remote leptos watch with port forwarding
  LEPTOS_ENV_CMD=""
  if [ -n "$LEPTOS_SITE_ADDR" ]; then
    LEPTOS_ENV_CMD="LEPTOS_SITE_ADDR='$LEPTOS_SITE_ADDR' "
  fi
  LEPTOS_ENV_CMD="${LEPTOS_ENV_CMD}LEPTOS_RELOAD_PORT='$LEPTOS_RELOAD_PORT' "
  
  # Forward both app port and reload port
  $BIN_SSH -tt -L $LEPTOS_PORT:127.0.0.1:$LEPTOS_PORT -L $LEPTOS_RELOAD_PORT:127.0.0.1:$LEPTOS_RELOAD_PORT -o ServerAliveInterval=30 -g "$REMOTE" \
    "cd '$REMOTE_DIR/package/$PROJECT' && env VPROXY_REMOTE_MODE=1 ${LEPTOS_ENV_CMD}nix develop --impure -c cargo leptos watch" &
  REMOTE_PID=$!
  
  # Wait for both processes
  wait $WATCHER_PID $REMOTE_PID
  
  exit 0
fi

log_info "Project: ${WHITE}$PROJECT${NC}"

log_step "Detecting local directories..."
if git_root=$($BIN_GIT rev-parse --show-toplevel 2>/dev/null); then
  LOCAL_DIR="$git_root"
  log_success "Found git root: ${WHITE}$LOCAL_DIR${NC}"
else
  LOCAL_DIR="$(pwd)"
  log_warning "Not in git repo, using current dir: ${WHITE}$LOCAL_DIR${NC}"
  read -p "Are you realy want continue? (y/n): " CONTINUE
  if [ "$CONTINUE" != "y" ]; then
    log_error "Aborting..."
    exit 0
  fi
fi
LOCAL_FLAKE="$LOCAL_DIR/flake.nix"
LOCAL_PACKAGE="$LOCAL_DIR/package"
LOCAL_PROJECT="$LOCAL_DIR/package/$PROJECT"
 
REMOTE_DIR="$REMOTE_DEV_DIR/$PROFILE"
 
log_info "Remote target: ${WHITE}$REMOTE:$REMOTE_DIR${NC}"

# Check disk space before starting any operations
check_remote_disk_space "$REMOTE" "$REMOTE_DEV_DIR"

if [ "$PROJECT" = "vproxy-bot" ]; then
  run_vproxy_bot "$LOCAL_DIR" "$LOCAL_PROJECT" "$REMOTE" "$REMOTE_DIR" "$PROJECT"
elif [ "$PROJECT" = "dreamproxy" ]; then
  run_dreamproxy "$LOCAL_DIR"
elif [ "$PROJECT" = "vproxy-web" ]; then
  log_header "DEPLOYING VPROXY-WEB PROJECT"
  
  if [ ! -d "$LOCAL_PROJECT" ]; then
    log_error "Project directory not found: $LOCAL_PROJECT"
    exit 1
  fi

  log_step "Creating remote profile directory..."
  if $BIN_SSH "$REMOTE" "mkdir -p '$REMOTE_DIR' && mkdir -p '$REMOTE_DIR/script'" 2>/dev/null; then
    log_success "Remote directory ready"
  else
    log_error "Failed to create remote directory"
    exit 1
  fi

  # Initialize git repository to prevent nix from copying target directory
  log_step "Initializing git repository on remote..."
  if $BIN_SSH "$REMOTE" "
    cd '$REMOTE_DEV_DIR' && 
    if ! git -c safe.directory=$REMOTE_DEV_DIR rev-parse --is-inside-work-tree >/dev/null 2>&1; then 
      echo \"Initializing git repository...\"
      cd '$REMOTE_DEV_DIR'
      git -c safe.directory=$REMOTE_DEV_DIR init
    fi
  "; then
    log_success "Git repository ready"
  else
    log_warning "Git setup failed"
  fi

  log_step "Syncing required files..."
  
  if $BIN_GIT ls-files -z | $BIN_RSYNC -av --delete --files-from=- --from0 "$LOCAL_DIR/" "$REMOTE:$REMOTE_DIR/"; then
    log_success "Required files synced"
  else
    log_error "Failed to sync files"
    exit 1
  fi

  # Check for .env file and sync if exists
  if [ -f "$LOCAL_PROJECT/.env" ]; then
    if $BIN_SCP -r "$LOCAL_PROJECT/.env" "$REMOTE:$REMOTE_DIR/"; then
      log_success "env file synced from $LOCAL_PROJECT/.env to $REMOTE:$REMOTE_DIR/.env"
    else
      log_warning "Failed to sync env file"
    fi
  else
    log_info "No .env file found in $LOCAL_PROJECT, skipping env sync"
  fi

  $BIN_SSH "$REMOTE" " cd '$REMOTE_DIR' && git add ."
  
  log_header "RUNNING ON REMOTE WITH PORT BINDING"
  log_info "Binding remote port $LEPTOS_PORT to local port $LEPTOS_PORT..."
  LEPTOS_ENV_CMD=""
  if [ -n "$LEPTOS_SITE_ADDR" ]; then
    LEPTOS_ENV_CMD="LEPTOS_SITE_ADDR='$LEPTOS_SITE_ADDR' "
    log_info "Using custom LEPTOS_SITE_ADDR: ${WHITE}$LEPTOS_SITE_ADDR${NC}"
  fi
  log_info "Executing: ${WHITE}cd '$REMOTE_DIR/package/$PROJECT' && env VPROXY_REMOTE_MODE=1 ${LEPTOS_ENV_CMD}nix develop --impure -c cargo leptos serve${NC}"
  log_info "Access the application at: ${WHITE}http://localhost:$LEPTOS_PORT${NC}"
  
  # Use SSH with port forwarding (-L) and keep connection alive (-o ServerAliveInterval=30)
  if $BIN_SSH -tt -L $LEPTOS_PORT:127.0.0.1:$LEPTOS_PORT -o ServerAliveInterval=30 "$REMOTE" \
     "cd '$REMOTE_DIR/package/$PROJECT' && env VPROXY_REMOTE_MODE=1 ${LEPTOS_ENV_CMD}nix develop --impure -c cargo leptos serve"; then
    log_success "Remote execution completed successfully!"
  else
    log_error "Remote execution failed"
    exit 1
  fi
elif [ "$PROJECT" = "legacy-web" ]; then
  log_header "RUNNING LEGACY WEB PROJECT"

  WEB_DIR="$LOCAL_DIR/package/web"

  [ -f "$WEB_DIR/.env" ] || (
    log_error "env file not found: $WEB_DIR/.env"
    exit 1
  )

  set -a
  source "$WEB_DIR/.env"
  set +a

  cd "$WEB_DIR"

  npm install
  npm run dev
else
  log_error "Unsupported project: $PROJECT"
  log_info "Currently supported projects: vproxy-bot, dreamproxy, vproxy-web, legacy-web"
  exit 1
fi
