#!/usr/bin/env bash
# ============================================================================
# Focusa Installer
# Source: https://install.focusa.dev/focusa
# Docs:   https://install.focusa.dev  (see "Install" section)
# License: BSL 1.1 — see https://focusa.dev/LICENSE
# ============================================================================
set -euo pipefail

# ---- Defaults ----
PREFIX="${HOME}/.focusa"
CHANNEL="stable"
DRY_RUN=0
EVAL=0
LICENSE_KEY=""
UNINSTALL=0
WITH_ENGINE=0
WITH_PI=0
WITH_OPENCLAW=0
ACCEPT_LICENSE=0
NO_SERVICE=0
LICENSE_REGISTRY="https://install.focusa.dev"
PRODUCT="focusa"
TIER="operator"
WARN_BSL=1

# ---- Helpers ----
log() { printf '\033[1;34m[focusa-install]\033[0m %s\n' "$*"; }
warn() { printf '\033[1;33m[focusa-install]\033[0m %s\n' "$*"; }
err() { printf '\033[1;31m[focusa-install]\033[0m %s\n' "$*" >&2; }
die() { err "$@"; exit 1; }
have() { command -v "$1" >/dev/null 2>&1; }

usage() {
  cat <<'USAGE'
Usage: bash focusa-install.sh [options]

Options:
  --eval                 Install in evaluation mode (no commercial use)
  --license-key <key>    Activate a Focusa license key (focusa_live_xxxxx)
  --prefix <path>        Install prefix (default: ~/.focusa)
  --channel <name>       stable | preview (default: stable)
  --dry-run              Show what would happen; do not write
  --uninstall            Remove installed files at --prefix
  --with-engine          Also install UIAI Engine to share scope
  --with-pi              Install Pi (coding agent) wrapper if missing
  --with-openclaw        Install OpenClaw bridges if missing
  --no-service           Do not install systemd / launchd services
  --accept-license       Accept BSL 1.1 (required for production install)
  -h, --help             Show this help

Install:
  curl -fsSL https://install.focusa.dev/focusa -o focusa-install.sh
  less focusa-install.sh
  bash focusa-install.sh --eval

Licensed install:
  curl -fsSL https://install.focusa.dev/focusa | bash -s -- --license-key "$FOCUSA_LICENSE_KEY"
USAGE
}

# ---- Parse args ----
while [ $# -gt 0 ]; do
  case "$1" in
    --eval) EVAL=1; shift ;;
    --license-key) LICENSE_KEY="$2"; shift 2 ;;
    --prefix) PREFIX="$2"; shift 2 ;;
    --channel) CHANNEL="$2"; shift 2 ;;
    --dry-run) DRY_RUN=1; shift ;;
    --uninstall) UNINSTALL=1; shift ;;
    --with-engine) WITH_ENGINE=1; shift ;;
    --with-pi) WITH_PI=1; shift ;;
    --with-openclaw) WITH_OPENCLAW=1; shift ;;
    --no-service) NO_SERVICE=1; shift ;;
    --accept-license) ACCEPT_LICENSE=1; shift ;;
    -h|--help) usage; exit 0 ;;
    *) die "Unknown option: $1 (use --help)" ;;
  esac
done

# ---- License warning (always shown unless explicitly accepted) ----
if [ "$EVAL" -eq 0 ] && [ "$ACCEPT_LICENSE" -eq 0 ]; then
  cat <<'WARN'

  Focusa is source-available under the Business Source License 1.1.

  Personal, educational, evaluation, and non-commercial local use is permitted.
  Commercial use, hosted services, client delivery, team use, product embedding,
  and redistribution require a paid license from WPUIAI / Startempire Wire.

  See https://focusa.dev/LICENSE and https://focusa.dev/COMMERCIAL.md

  To continue as a personal/evaluation user, re-run with --eval.
  To install for commercial use, run with --accept-license and --license-key.

WARN
  if [ -z "$LICENSE_KEY" ]; then
    die "Refusing to install without a license key. Use --eval or pass --license-key + --accept-license."
  fi
fi

# ---- Uninstall path (always safe) ----
if [ "$UNINSTALL" -eq 1 ]; then
  if [ -d "$PREFIX" ]; then
    log "Removing $PREFIX"
    if [ "$DRY_RUN" -eq 1 ]; then
      log "DRY RUN: would rm -rf $PREFIX"
    else
      rm -rf "$PREFIX"
    fi
  else
    log "$PREFIX does not exist; nothing to remove"
  fi
  log "Uninstall complete. State files at $HOME/.config/focusa/ were left intact for audit."
  exit 0
fi

# ---- License validation (if key provided) ----
if [ -n "$LICENSE_KEY" ]; then
  log "Validating license key against $LICENSE_REGISTRY ..."
  if have curl; then
    # -k is needed for self-signed dev certs; production uses Let's Encrypt.
    VALIDATE_RESP=$(curl -ksS -X POST \
      -H "Content-Type: application/json" \
      -H "X-License-Key: $LICENSE_KEY" \
      -d "{\"license_key\":\"$LICENSE_KEY\"}" \
      "$LICENSE_REGISTRY/wp-json/wpuiai-ai-cloud/v1/license/validate" \
      2>/dev/null || echo "")
    if echo "$VALIDATE_RESP" | grep -q '"valid":true'; then
      log "License valid."
      TIER=$(echo "$VALIDATE_RESP" | python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('tier','operator'))" 2>/dev/null || echo "operator")
    else
      err "License validation failed."
      err "Response: ${VALIDATE_RESP:-(empty)}"
      err "Purchase a license at https://focusa.dev or pass --eval for evaluation."
      exit 2
    fi
  else
    warn "curl not available; skipping license validation (key will be saved but not verified)"
  fi
fi

# ---- Begin install (DRY-RUN aware) ----
log "Plan:"
log "  prefix:    $PREFIX"
log "  channel:   $CHANNEL"
log "  eval:      $EVAL"
log "  license:   ${LICENSE_KEY:-(none)}"
log "  tier:      $TIER"
log "  dry-run:   $DRY_RUN"
log "  with-engine: $WITH_ENGINE"
log "  with-pi:   $WITH_PI"
log "  with-openclaw: $WITH_OPENCLAW"
log "  no-service: $NO_SERVICE"

# 1. Create prefix layout
run() {
  if [ "$DRY_RUN" -eq 1 ]; then
    log "DRY RUN: $*"
  else
    eval "$@"
  fi
}

run "mkdir -p '$PREFIX/bin' '$PREFIX/state' '$PREFIX/config' '$PREFIX/libexec'"

# 2. Drop a small launcher that points at the local source clone or package
if [ "$DRY_RUN" -eq 1 ]; then
  log "DRY RUN: would write $PREFIX/bin/focusa launcher"
else
  cat > "$PREFIX/bin/focusa" <<'LAUNCHER'
#!/usr/bin/env bash
# Focusa launcher — minimal stub for Phase 1.4
# Real binary arrives when the engine binary is wired in.
PREFIX="$(cd "$(dirname "$0")/.." && pwd)"
exec python3 -m focusa_cli "$@"
LAUNCHER
  chmod +x "$PREFIX/bin/focusa"
fi

# 3. Write license state (if provided)
if [ -n "$LICENSE_KEY" ] && [ "$DRY_RUN" -eq 0 ]; then
  mkdir -p "$HOME/.config/focusa"
  cat > "$HOME/.config/focusa/license.json" <<JSON
{
  "license_key_prefix": "${LICENSE_KEY:0:16}",
  "tier": "$TIER",
  "issued_at": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
  "registry": "$LICENSE_REGISTRY",
  "eval": $([ "$EVAL" -eq 1 ] && echo true || echo false)
}
JSON
  log "Wrote license state to \$HOME/.config/focusa/license.json"
fi

# 4. Optionally install companion pieces
if [ "$WITH_ENGINE" -eq 1 ]; then
  log "Installing UIAI Engine companion (delegating to engine installer)..."
  if [ "$DRY_RUN" -eq 1 ]; then
    log "DRY RUN: curl -fsSL $LICENSE_REGISTRY/engine | bash -s -- --prefix $PREFIX"
  else
    curl -fsSL "$LICENSE_REGISTRY/engine" -o /tmp/engine-install.sh
    bash /tmp/engine-install.sh --prefix "$PREFIX" --no-service
  fi
fi

if [ "$WITH_PI" -eq 1 ]; then
  log "Installing Pi (coding agent) wrapper..."
  run "curl -fsSL https://raw.githubusercontent.com/mariozechner/pi-coding-agent/main/install.sh -o /tmp/pi-install.sh"
  run "bash /tmp/pi-install.sh"
fi

if [ "$WITH_OPENCLAW" -eq 1 ]; then
  log "Installing OpenClaw bridges (Phase 2 feature — placeholder)..."
  warn "OpenClaw bridges arrive in Phase 2 of the install gateway spec."
fi

# 5. Service install (unless --no-service)
if [ "$NO_SERVICE" -eq 0 ]; then
  if have systemctl; then
    run "ln -sf '$PREFIX/bin/focusa' /usr/local/bin/focusa"
    log "Linked /usr/local/bin/focusa -> $PREFIX/bin/focusa"
  elif have launchctl; then
    log "macOS detected; skipping launchd plist for now (Phase 2)."
  else
    log "No systemd/launchd; installed $PREFIX/bin/focusa only."
  fi
fi

# 6. Health check
run "command -v focusa || true"

log "Done."
log "Run: $PREFIX/bin/focusa license status"
log "Docs: https://install.focusa.dev"