#!/usr/bin/env bash
set -euo pipefail

usage() {
  cat <<'EOF'
Usage: cch-desktop [options] [-- <tauri args>]

Options:
  --root <path>      Use a specific project root
  --install-only     Only ensure/install dependencies
  -h, --help         Show this help

Environment:
  CCH_ROOT           Override the project root

Examples:
  cch-desktop
  cch-desktop --root ~/projects/cc-haha-main
  cch-desktop --install-only
  cch-desktop -- --verbose
EOF
}

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SCRIPT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
CURRENT_DIR="$(pwd)"
INSTALL_ONLY=0
TAURI_ARGS=()
USER_ROOT=""

while (($#)); do
  case "$1" in
    --root)
      if [ $# -lt 2 ]; then
        echo "Missing value for --root" >&2
        exit 1
      fi
      USER_ROOT="$2"
      shift 2
      ;;
    --install-only)
      INSTALL_ONLY=1
      shift
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    --)
      shift
      TAURI_ARGS=("$@")
      break
      ;;
    *)
      TAURI_ARGS+=("$1")
      shift
      ;;
  esac
done

is_repo_root() {
  local dir="$1"
  [ -f "$dir/package.json" ] && [ -d "$dir/desktop" ] && [ -d "$dir/adapters" ]
}

resolve_root() {
  if [ -n "$USER_ROOT" ] && is_repo_root "$USER_ROOT"; then
    printf '%s\n' "$USER_ROOT"
    return
  fi

  if [ -n "${CCH_ROOT:-}" ] && is_repo_root "$CCH_ROOT"; then
    printf '%s\n' "$CCH_ROOT"
    return
  fi

  if is_repo_root "$CURRENT_DIR"; then
    printf '%s\n' "$CURRENT_DIR"
    return
  fi

  if is_repo_root "$SCRIPT_ROOT"; then
    printf '%s\n' "$SCRIPT_ROOT"
    return
  fi

  local dir="$CURRENT_DIR"
  while [ "$dir" != "/" ]; do
    if is_repo_root "$dir"; then
      printf '%s\n' "$dir"
      return
    fi
    dir="$(dirname "$dir")"
  done

  for candidate in "$HOME/projects/cc-haha-main" "$HOME/work/cc-haha-main" "$HOME/code/cc-haha-main"; do
    if is_repo_root "$candidate"; then
      printf '%s\n' "$candidate"
      return
    fi
  done

  return 1
}

TARGET_ROOT="$(resolve_root || true)"

if [ -z "$TARGET_ROOT" ]; then
  echo "Could not locate the cc-haha project root." >&2
  echo "Run this from inside the repo, set CCH_ROOT, or pass --root <path>." >&2
  exit 1
fi

if ! command -v bun >/dev/null 2>&1; then
  echo "bun is not installed or not in PATH." >&2
  exit 1
fi

cd "$TARGET_ROOT"

if [ "$INSTALL_ONLY" -eq 1 ]; then
  exec bun run desktop:install
fi

if [ ${#TAURI_ARGS[@]} -gt 0 ]; then
  exec sh -c 'bun run desktop:ensure && cd ./desktop && bun run tauri dev -- "$@"' sh "${TAURI_ARGS[@]}"
fi

exec bun run desktop:dev
