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

VERSION="0.4.0"
WHEEL="oxharness-0.4.0-py3-none-any.whl"
EXPECTED_SHA256="36e8b47fa9b2a9457e4c046b7523edaf3b6180ad9df3b6331160df206bb6429d"
DEFAULT_BASE_URL="https://ox.127100.xyz"
BASE_URL="${OXHARNESS_BASE_URL:-$DEFAULT_BASE_URL}"
ASSUME_YES=0
RUN_DOCTOR=1
USE_COLOR=1
TEMP_DIR=""

if [[ -n "${NO_COLOR:-}" || ! -t 1 ]]; then
  USE_COLOR=0
fi

if [[ "$USE_COLOR" == 1 ]]; then
  RESET=$'\033[0m'
  DIM=$'\033[2m'
  CYAN=$'\033[38;5;81m'
  VIOLET=$'\033[38;5;141m'
  GREEN=$'\033[38;5;84m'
  YELLOW=$'\033[38;5;221m'
  RED=$'\033[38;5;203m'
  BOLD=$'\033[1m'
else
  RESET="" DIM="" CYAN="" VIOLET="" GREEN="" YELLOW="" RED="" BOLD=""
fi

say() { printf '%s\n' "$*"; }
step() { printf '  %s◆%s %s\n' "$CYAN" "$RESET" "$*"; }
success() { printf '  %s✓%s %s\n' "$GREEN" "$RESET" "$*"; }
warn() { printf '  %s!%s %s\n' "$YELLOW" "$RESET" "$*"; }
fail() { printf '  %s×%s %s\n' "$RED" "$RESET" "$*" >&2; exit 1; }

cleanup() {
  if [[ -n "$TEMP_DIR" && -d "$TEMP_DIR" ]]; then
    rm -rf "$TEMP_DIR"
  fi
}
trap cleanup EXIT
trap 'fail "Installation stopped near line $LINENO."' ERR

usage() {
  cat <<EOF
OxHarness installer $VERSION

Usage: install.sh [options]

  --base-url URL   Override the release server (or set OXHARNESS_BASE_URL)
  --yes            Skip OxHarness confirmation prompts
  --no-doctor      Install the CLI without setting up Git and OpenCode
  --no-color       Disable terminal colors
  -h, --help       Show this help
EOF
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --base-url)
      [[ $# -ge 2 ]] || fail "--base-url requires a value"
      BASE_URL="$2"
      shift 2
      ;;
    --yes)
      ASSUME_YES=1
      shift
      ;;
    --no-doctor)
      RUN_DOCTOR=0
      shift
      ;;
    --no-color)
      USE_COLOR=0
      RESET="" DIM="" CYAN="" VIOLET="" GREEN="" YELLOW="" RED="" BOLD=""
      shift
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *) fail "Unknown option: $1" ;;
  esac
done

BASE_URL="${BASE_URL%/}"
if [[ -z "$BASE_URL" || "$BASE_URL" == *"@@BASE"* ]]; then
  fail "This installer has not been assigned a release domain. Set OXHARNESS_BASE_URL or use --base-url."
fi
case "$BASE_URL" in
  https://*|http://127.0.0.1:*|http://localhost:*) ;;
  *) fail "The release URL must use HTTPS (localhost is allowed for testing)." ;;
esac

say ""
say "${BOLD}${VIOLET}  ╭──────────────────────────────────────────╮${RESET}"
say "${BOLD}${VIOLET}  │${RESET}  ${BOLD}OxHarness${RESET} ${DIM}· autonomous engineering CLI${RESET}  ${BOLD}${VIOLET}│${RESET}"
say "${BOLD}${VIOLET}  ╰──────────────────────────────────────────╯${RESET}"
say ""
step "Preparing OxHarness ${BOLD}v$VERSION${RESET}"

case "$(uname -s 2>/dev/null || true)" in
  Darwin) PLATFORM="macOS" ;;
  Linux) PLATFORM="Linux" ;;
  *) fail "This installer supports macOS, Linux, and WSL. Use install.ps1 on Windows." ;;
esac

download() {
  local source="$1" destination="$2"
  if command -v curl >/dev/null 2>&1; then
    curl --fail --silent --show-error --location --retry 3 --connect-timeout 15 \
      --output "$destination" "$source"
  elif command -v wget >/dev/null 2>&1; then
    wget --quiet --tries=3 --timeout=15 --output-document="$destination" "$source"
  else
    fail "curl or wget is required to download the release artifact."
  fi
}

sha256() {
  if command -v sha256sum >/dev/null 2>&1; then
    sha256sum "$1" | awk '{print $1}'
  elif command -v shasum >/dev/null 2>&1; then
    shasum -a 256 "$1" | awk '{print $1}'
  else
    fail "No SHA-256 utility was found. Install sha256sum or shasum and retry."
  fi
}

find_uv() {
  local candidate
  if command -v uv >/dev/null 2>&1; then
    command -v uv
    return 0
  fi
  for candidate in \
    "${UV_UNMANAGED_INSTALL:-}/uv" \
    "${UV_INSTALL_DIR:-}/uv" \
    "$HOME/.local/bin/uv" \
    "/opt/homebrew/bin/uv" \
    "/usr/local/bin/uv"; do
    if [[ "$candidate" != "/uv" && -x "$candidate" ]]; then
      printf '%s\n' "$candidate"
      return 0
    fi
  done
  return 1
}

find_brew() {
  local brew_bin
  if command -v brew >/dev/null 2>&1; then
    command -v brew
    return 0
  fi
  for brew_bin in /opt/homebrew/bin/brew /usr/local/bin/brew; do
    if [[ -x "$brew_bin" ]]; then
      printf '%s\n' "$brew_bin"
      return 0
    fi
  done
  return 1
}

bootstrap_uv() {
  local brew_bin
  if [[ "$PLATFORM" == "macOS" ]]; then
    brew_bin="$(find_brew || true)"
    if [[ -z "$brew_bin" ]]; then
      step "Homebrew was not found; launching its official installer"
      /bin/bash -c "$(/usr/bin/curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
      brew_bin="$(find_brew || true)"
    fi
    [[ -n "$brew_bin" ]] || fail "Homebrew installation did not produce a usable brew command."
    step "Installing uv with Homebrew"
    "$brew_bin" install uv
  else
    step "Installing uv with Astral's official user installer"
    if command -v curl >/dev/null 2>&1; then
      curl -LsSf https://astral.sh/uv/install.sh | sh
    else
      wget -qO- https://astral.sh/uv/install.sh | sh
    fi
  fi
}

TEMP_DIR="$(mktemp -d 2>/dev/null || mktemp -d -t oxharness)"
WHEEL_PATH="$TEMP_DIR/$WHEEL"
ARTIFACT_URL="$BASE_URL/releases/$VERSION/$WHEEL"
step "Downloading the platform-independent release"
download "$ARTIFACT_URL" "$WHEEL_PATH"

ACTUAL_SHA256="$(sha256 "$WHEEL_PATH")"
if [[ "$ACTUAL_SHA256" != "$EXPECTED_SHA256" ]]; then
  fail "Release checksum mismatch. Expected $EXPECTED_SHA256, received $ACTUAL_SHA256."
fi
success "Release integrity verified"

UV_BIN="$(find_uv || true)"
if [[ -z "$UV_BIN" ]]; then
  bootstrap_uv
  UV_BIN="$(find_uv || true)"
fi
[[ -n "$UV_BIN" ]] || fail "uv was installed but could not be located. Restart the shell and retry."

step "Installing OxHarness into an isolated tool environment"
"$UV_BIN" tool install --force "$WHEEL_PATH"

OX_BIN=""
for candidate in \
  "${UV_TOOL_BIN_DIR:-}/oxharness" \
  "$HOME/.local/bin/oxharness" \
  "$("$UV_BIN" tool dir --bin 2>/dev/null || true)/oxharness"; do
  if [[ "$candidate" != "/oxharness" && -x "$candidate" ]]; then
    OX_BIN="$candidate"
    break
  fi
done
if [[ -z "$OX_BIN" ]] && command -v oxharness >/dev/null 2>&1; then
  OX_BIN="$(command -v oxharness)"
fi
[[ -n "$OX_BIN" ]] || fail "OxHarness installed, but its executable could not be located."
success "Installed $($OX_BIN --version)"

if [[ "$RUN_DOCTOR" == 1 ]]; then
  configure=0
  if [[ "$ASSUME_YES" == 1 ]]; then
    configure=1
  elif [[ -t 1 && -r /dev/tty ]]; then
    printf '\n  Set up Git and OpenCode now? %s[Y/n]%s ' "$BOLD" "$RESET" >/dev/tty
    read -r answer </dev/tty || answer=""
    case "$answer" in n|N|no|NO) configure=0 ;; *) configure=1 ;; esac
  else
    warn "Non-interactive shell detected; run '$OX_BIN doctor --install' to finish setup."
  fi
  if [[ "$configure" == 1 ]]; then
    step "Checking Git, OpenCode, and platform tooling"
    doctor_args=(doctor --install)
    [[ "$ASSUME_YES" == 1 ]] && doctor_args+=(--yes)
    if ! "$OX_BIN" "${doctor_args[@]}"; then
      warn "The CLI is installed, but one or more development tools still need attention."
      warn "Retry with: $OX_BIN doctor --install"
    fi
  fi
fi

BIN_DIR="$(dirname "$OX_BIN")"
say ""
say "${BOLD}${GREEN}  OxHarness is ready.${RESET}"
say "  ${DIM}Launch the control center:${RESET} ${BOLD}$OX_BIN${RESET}"
if ! command -v oxharness >/dev/null 2>&1; then
  warn "Add $BIN_DIR to PATH to invoke 'oxharness' directly in new shells."
fi
say "  ${DIM}Docs and examples:${RESET} $BASE_URL/"
say ""
