#!/usr/bin/env bash
set -u

GRADLE="./gradlew"
GRADLE_BASE_FLAGS=(
  "--console=plain"
  "--no-daemon"
  "-Dfabric.development=true"
  "-Dminecraft.api.env=dev"
  "-Dminecraft.session.disable=true"
)

OPTIONS_SRC="./config/options.txt"

ROLE=""
ROLE_INDEX=""
PASSTHROUGH=()

# ---------- utils ----------

rand() { shuf -i 0-$(($1 - 1)) -n 1; }

parse_args() {
  local cleaned=()
  for ((i=0; i<${#ARGS[@]}; i++)); do
    case "${ARGS[$i]}" in
      -s|--server)
        ROLE="server"
        ;;
      -p1|--player1)
        ROLE="client"
        ROLE_INDEX=1
        ;;
      -p2|--player2)
        ROLE="client"
        ROLE_INDEX=2
        ;;
      --)
        PASSTHROUGH=( "${ARGS[@]:$((i+1))}" )
        break
        ;;
      *)
        cleaned+=( "${ARGS[$i]}" )
        ;;
    esac
  done
  ARGS=( "${cleaned[@]}" )
}

# ---------- run-dir helpers ----------

prepare_run_dir() {
  local dir="$1"
  rm -rf "$dir"
  mkdir -p "$dir"
}

inject_options() {
  local dir="$1"

  # options.txt
  if [[ -f "$OPTIONS_SRC" ]]; then
    cp "$OPTIONS_SRC" "$dir/options.txt"
  fi

  # servers.dat (client server list)
  if [[ -f "./config/servers.dat" ]]; then
    cp "./config/servers.dat" "$dir/servers.dat"
  fi

  # server.properties
  if [[ -f "./config/server.properties" ]]; then
    cp "./config/server.properties" "$dir/server.properties"
  fi

  # server icon
  if [[ -f "./config/server-icon.png" ]]; then
    cp "./config/server-icon.png" "$dir/server-icon.png"
  fi
}

ensure_server_files() {
  local dir="$1"

  [[ -f "$dir/eula.txt" ]] || echo "eula=true" > "$dir/eula.txt"

  if [[ ! -f "$dir/server.properties" ]]; then
    cat > "$dir/server.properties" <<EOF
online-mode=false
server-port=25565
level-name=world
enable-command-block=true
EOF
  fi
}

# ---------- squirrel ----------

header() {
  local action="$1"

  local squirrels=(
'   /\_/\ 
  ( o.o )
   > ^ <'

'   /\_/\ 
  ( -.- )
  o_(")(")'

'   /\_/\ 
  ( @.@ )
   > ~ <'
  )

  clear
  echo "${squirrels[$(rand ${#squirrels[@]})]}"
  echo
  case "$action" in
    run)   echo "🐿️  running chipper" ;;
    clean) echo "🐿️  cleaning workspace" ;;
    build) echo "🐿️  building project" ;;
    tree)  echo "🐿️  observing project tree" ;;
    *)     echo "🐿️  thinking..." ;;
  esac
  echo
}

# ---------- commands ----------

cmd_run() {
  header run

  case "$ROLE" in
    server)
      run_dir="run-server"
      prepare_run_dir "$run_dir"
      inject_options "$run_dir"
      ensure_server_files "$run_dir"

      echo "🖥️🐿️  starting dedicated server"
      exec "$GRADLE" runServer "${GRADLE_BASE_FLAGS[@]}" "${PASSTHROUGH[@]}"
      ;;

    client)
      run_dir="run-$ROLE_INDEX"
      task="runClient$ROLE_INDEX"
      prepare_run_dir "$run_dir"
      inject_options "$run_dir"

      echo "🎮🐿️  starting client $ROLE_INDEX"
      exec "$GRADLE" "$task" "${GRADLE_BASE_FLAGS[@]}" "${PASSTHROUGH[@]}"
      ;;

    *)
      echo "❌🐿️  no role selected"
      echo "👉🐿️  use one of:"
      echo "   --server"
      echo "   --player1"
      echo "   --player2"
      exit 1
      ;;
  esac
}

cmd_clean() {
  header clean
  "$GRADLE" clean "${GRADLE_BASE_FLAGS[@]}" "${PASSTHROUGH[@]}"
}

cmd_build() {
  header build
  "$GRADLE" build "${GRADLE_BASE_FLAGS[@]}" "${PASSTHROUGH[@]}"
}

cmd_tree() {
  header tree
  tree --gitignore
}

cmd_help() {
  cat <<'EOF'
    /\_/\ 
   ( o.o )
    > ^ <

🐿️  C H I P P E R

Usage:
  ./chipper run [role] [-- passthrough]

Roles:
  -s,  --server      Start ONLY server
  -p1, --player1     Start ONLY client 1
  -p2, --player2     Start ONLY client 2

Other commands:
  clean              Gradle clean
  build              Gradle build
  tree               Show project tree
  help               Show this menu

Examples:
  ./chipper run --server
  ./chipper run --player1
  ./chipper run --player2
  ./chipper run --player1 -- --debug
  ./chipper build
  ./chipper tree

Notes:
- No legacy player spawning
- Each role has its own run directory
- options.txt injected per run dir
- Everything after `--` is forwarded
- The squirrel is mandatory
EOF
}

# ---------- entry ----------

ARGS=( "$@" )
parse_args

case "${ARGS[0]:-help}" in
  run)   cmd_run ;;
  clean) cmd_clean ;;
  build) cmd_build ;;
  tree)  cmd_tree ;;
  help|-h) cmd_help ;;
  *)
    echo "[!] Unknown command: ${ARGS[0]}"
    cmd_help
    exit 1
    ;;
esac
