#!/usr/bin/env sh
# =============================================================================
# OpenHome CLI installer  (macOS / Linux)
#
#   curl -fsSL https://app.openhome.com/install.sh | sh
#
# Clones the OpenHome `abilities` repo and installs its `openhome` CLI globally
# via pipx. Safe to re-run: an existing clone is updated, present tools skipped.
#
# Overrides:
#   OPENHOME_DIR     clone location   (default: ~/openhome_cli/abilities)
#   OPENHOME_BRANCH  branch           (default: dev)
#   OPENHOME_REPO    repo URL         (default: official repo)
#
# The whole script is wrapped in main() and only invoked on the last line, so a
# truncated download (e.g. dropped connection during `curl | sh`) executes
# nothing rather than a partial installer.
# =============================================================================

set -eu

# -- output helpers (colors auto-disabled when stdout isn't a terminal) --------
if [ -t 1 ]; then
    BOLD=$(printf '\033[1m'); DIM=$(printf '\033[2m'); RESET=$(printf '\033[0m')
    GREEN=$(printf '\033[32m'); YELLOW=$(printf '\033[33m'); RED=$(printf '\033[31m')
else
    BOLD=; DIM=; RESET=; GREEN=; YELLOW=; RED=
fi
info()  { printf '%s->%s %s\n' "$GREEN" "$RESET" "$1"; }
warn()  { printf '%s!%s %s\n' "$YELLOW" "$RESET" "$1"; }
err()   { printf '%sx%s %s\n' "$RED" "$RESET" "$1" >&2; }
step()  { printf '\n%s%s%s\n' "$BOLD" "$1" "$RESET"; }
have()  { command -v "$1" >/dev/null 2>&1; }
die()   { err "$1"; exit 1; }

# install_pkg APT_NAME DNF_NAME PACMAN_NAME ZYPPER_NAME (per-manager package names)
install_pkg() {
    case "$PKG" in
        apt)    $SUDO apt-get update -qq 2>/dev/null || true; $SUDO apt-get install -y "$1" ;;
        dnf)    $SUDO dnf install -y "$2" ;;
        pacman) $SUDO pacman -Sy --noconfirm "$3" ;;
        zypper) $SUDO zypper install -y "$4" ;;
        *)      return 1 ;;
    esac
}

# py_in_range PY -> success if PY is Python >= 3.10.
py_in_range() {
    _v="$("$1" -c 'import sys; print("%d %d" % sys.version_info[:2])' 2>/dev/null)" || return 1
    # shellcheck disable=SC2086
    set -- $_v
    [ "${1:-0}" -eq 3 ] && [ "${2:-0}" -ge 10 ] 2>/dev/null
}


main() {
    REPO_URL="${OPENHOME_REPO:-https://github.com/openhome-dev/abilities.git}"
    BRANCH="${OPENHOME_BRANCH:-dev}"
    # NOTE: the clone path must NOT contain a directory named exactly "openhome".
    # Such a directory lands on sys.path (e.g. when the CLI runs `python -m
    # openhome ...`, which puts the cwd on the path) and Python claims it as an
    # empty *namespace package*, shadowing the real installed `openhome` package -
    # which breaks subcommands with "cannot import name ... (unknown location)".
    # We therefore default to ~/openhome_cli (not named "openhome", so no clash),
    # while keeping the repo browsable/editable at a visible path.
    TARGET_DIR="${OPENHOME_DIR:-$HOME/openhome_cli/abilities}"
    CLI_DIR="$TARGET_DIR/cli"

    # One-time migration: earlier versions cloned to ~/openhome/abilities. That
    # ~/openhome directory triggers the namespace-package collision above, so if
    # we're using the default location and that old clone exists, remove it.
    if [ "${OPENHOME_DIR:-}" = "" ] && [ "$TARGET_DIR" != "$HOME/openhome/abilities" ] && [ -d "$HOME/openhome/abilities/.git" ]; then
        warn "removing old clone at ~/openhome (its name shadows the 'openhome' package)"
        rm -rf "$HOME/openhome/abilities"
        rmdir "$HOME/openhome" 2>/dev/null || warn "note: ~/openhome still exists and is not empty - remove it manually to avoid import issues"
    fi

    # Guard: warn if the chosen path still contains an 'openhome' component (e.g.
    # via an OPENHOME_DIR override), since that reintroduces the collision.
    case "$TARGET_DIR/" in
        *"/openhome/"*) warn "OPENHOME_DIR contains a directory named 'openhome', which can shadow the Python package and break commands - consider a path like ~/openhome_cli/abilities" ;;
    esac

    # -- detect platform + package manager -------------------------------------
    OS="$(uname -s)"
    case "$OS" in
        Darwin) PLATFORM="mac" ;;
        Linux)  PLATFORM="linux" ;;
        *) die "Unsupported OS '$OS'. Supports macOS and Linux. On Windows use install.ps1." ;;
    esac

    PKG=""
    SUDO=""
    if [ "$PLATFORM" = "linux" ]; then
        [ "$(id -u)" -ne 0 ] && SUDO="sudo"
        if   have apt-get; then PKG="apt"
        elif have dnf;     then PKG="dnf"
        elif have pacman;  then PKG="pacman"
        elif have zypper;  then PKG="zypper"
        fi
    fi

    # -- 1. git ----------------------------------------------------------------
    step "1/5  Checking git"
    if have git; then
        info "git present ($(git --version | awk '{print $3}'))"
    else
        warn "git not found - installing"
        if [ "$PLATFORM" = "mac" ]; then
            have brew || die "Homebrew required to install git on macOS. Install from https://brew.sh then re-run."
            brew install git
        else
            install_pkg git git git git || die "Could not install git automatically. Install it and re-run."
        fi
        have git || die "git still not available after install."
        info "git installed"
    fi

    # -- 2. Python >= 3.10 ------------------------------------------------------
    # Prefer the newest 3.10-3.13 already installed, then any other 3.10+.
    step "2/5  Checking Python (need >= 3.10)"
    PYTHON=""
    for candidate in python3.13 python3.12 python3.11 python3.10 python3 python; do
        if have "$candidate" && py_in_range "$candidate"; then PYTHON="$candidate"; break; fi
    done
    if [ -z "$PYTHON" ]; then
        warn "No Python 3.10+ found - installing one"
        if [ "$PLATFORM" = "mac" ]; then
            have brew || die "Homebrew required to install Python on macOS. Install from https://brew.sh then re-run."
            brew install python@3.13 || brew install python@3.12 || die "Could not install a 3.10-3.13 Python via Homebrew."
        else
            install_pkg python3.13 python3.13 python python3.13 2>/dev/null \
                || install_pkg python3.12 python3.12 python python3.12 2>/dev/null \
                || install_pkg python3 python3 python python3 \
                || die "Could not install a 3.10-3.13 Python automatically. Install Python 3.13 and re-run."
        fi
        for candidate in python3.13 python3.12 python3.11 python3.10 python3 python; do
            if have "$candidate" && py_in_range "$candidate"; then PYTHON="$candidate"; break; fi
        done
        [ -n "$PYTHON" ] || die "Installed Python is still older than 3.10. Install Python 3.13 and re-run."
    fi
    # Pin to an absolute path so every later step (and pipx) uses exactly this one.
    PYTHON="$(command -v "$PYTHON")"
    info "Python OK ($("$PYTHON" --version 2>&1 | awk '{print $2}') at $PYTHON)"

    # -- 3. PortAudio + mpv + build tools (best-effort; pyaudio needs these) ---
    step "3/5  Checking audio libs (PortAudio + mpv) and build tools"
    if [ "$PLATFORM" = "mac" ]; then
        if have brew; then
            brew list portaudio >/dev/null 2>&1 && info "portaudio present" || { warn "installing portaudio"; brew install portaudio; }
            brew list mpv        >/dev/null 2>&1 && info "mpv present"        || { warn "installing mpv";        brew install mpv; }
        else
            warn "Homebrew not found - cannot auto-install PortAudio/mpv."
            warn "The CLI install may fail building pyaudio. Install brew (https://brew.sh) then: brew install portaudio mpv"
        fi
        if xcode-select -p >/dev/null 2>&1; then
            info "C compiler present (Xcode command-line tools)"
        else
            warn "Xcode command-line tools not found - needed to build pyaudio when no prebuilt wheel exists"
            warn "starting install (a dialog may appear); re-run this script after it completes"
            xcode-select --install 2>/dev/null || true
        fi
    else
        if [ -n "$PKG" ]; then
            warn "installing PortAudio dev headers + mpv (may prompt for sudo)"
            install_pkg portaudio19-dev portaudio-devel portaudio portaudio-devel || warn "could not install PortAudio automatically"
            install_pkg mpv mpv mpv mpv || warn "could not install mpv automatically"
            if have cc || have gcc; then
                info "C compiler present"
            else
                warn "no C compiler found - installing"
                install_pkg build-essential gcc base-devel gcc || warn "could not install a compiler automatically"
            fi
            info "audio libs + build tools step done"
        else
            warn "No known package manager - install PortAudio dev headers, mpv, and gcc manually, or the pyaudio build may fail."
        fi
    fi

    # Python dev headers (Python.h): needed to compile pyaudio from source when
    # no prebuilt wheel exists. Only acts when the header is actually missing.
    if "$PYTHON" -c 'import os, sysconfig; raise SystemExit(0 if os.path.exists(os.path.join(sysconfig.get_path("include"), "Python.h")) else 1)' 2>/dev/null; then
        info "Python dev headers present (Python.h)"
    else
        warn "Python dev headers (Python.h) missing - needed to build pyaudio from source"
        PYVER="$("$PYTHON" -c 'import sys; print("%d.%d" % sys.version_info[:2])' 2>/dev/null || echo 3)"
        if [ "$PLATFORM" = "mac" ]; then
            if have brew; then
                brew list "python@${PYVER}" >/dev/null 2>&1 \
                    && warn "python@${PYVER} present but Python.h not found; if pyaudio build fails, try: brew reinstall python@${PYVER}" \
                    || warn "if the pyaudio build fails, ensure your Python ships dev headers (e.g. Homebrew's python@${PYVER})"
            else
                warn "if the pyaudio build fails, ensure your Python ships dev headers (Python.h)"
            fi
        elif [ -n "$PKG" ]; then
            case "$PKG" in
                apt) $SUDO apt-get install -y "python${PYVER}-dev" 2>/dev/null \
                         || install_pkg python3-dev python3-devel python python3-devel \
                         || warn "could not install Python dev headers automatically" ;;
                *)   install_pkg python3-dev python3-devel python python3-devel \
                         || warn "could not install Python dev headers automatically" ;;
            esac
        else
            warn "No known package manager - install your Python's dev headers (Python.h) manually."
        fi
    fi

    # -- 4. pipx ---------------------------------------------------------------
    step "4/5  Checking pipx"
    # Point pipx at the interpreter we selected so every venv it builds uses it.
    export PIPX_DEFAULT_PYTHON="$PYTHON"
    if have pipx; then
        info "pipx present"
        PIPX="pipx"
    else
        warn "pipx not found - installing"
        if [ "$PLATFORM" = "mac" ]; then
            have brew || die "Homebrew required to install pipx on macOS. Install from https://brew.sh then re-run."
            brew install pipx
        else
            # PEP 668 blocks plain --user on modern Linux; distro pkg first, then pip fallback.
            install_pkg pipx pipx python-pipx python-pipx \
                || "$PYTHON" -m pip install --user --break-system-packages pipx >/dev/null 2>&1 \
                || die "Could not install pipx. Try: sudo apt install pipx  (or your distro's equivalent)"
        fi
        have pipx || PIPX="$PYTHON -m pipx"
        info "pipx installed"
    fi
    PIPX="${PIPX:-pipx}"

    # -- make the pipx bin dir work NOW and in EVERY future shell --------------
    # This is the classic "global command didn't register" failure: pipx drops the
    # `openhome` launcher into its bin dir, but that dir is only on PATH for future
    # shells if it's been persisted. We do this UNCONDITIONALLY (even when pipx was
    # already installed - the case that bit us), detect pipx's REAL bin dir instead
    # of assuming ~/.local/bin, run pipx's own ensurepath, AND additionally write the
    # PATH export into the user's shell rc file(s) so a newly opened terminal finds
    # the command regardless of which shell they use.
    PIPX_BIN="$($PIPX environment --value PIPX_BIN_DIR 2>/dev/null || true)"
    [ -n "$PIPX_BIN" ] || PIPX_BIN="$HOME/.local/bin"

    $PIPX ensurepath --force >/dev/null 2>&1 \
        || "$PYTHON" -m pipx ensurepath --force >/dev/null 2>&1 || true

    # Append the export to a shell rc only if that file doesn't already reference it
    # (pipx's ensurepath may already have done so - avoid duplicate lines).
    persist_path() {
        [ -n "${1:-}" ] || return 0
        if [ -f "$1" ] && grep -Fq "$PIPX_BIN" "$1" 2>/dev/null; then return 0; fi
        printf '\n# Added by the OpenHome installer (pipx bin dir)\nexport PATH="%s:$PATH"\n' "$PIPX_BIN" >> "$1" 2>/dev/null || true
    }
    case "${SHELL:-}" in
        *zsh)  persist_path "$HOME/.zshrc" ;;
        *bash) persist_path "$HOME/.bashrc"; persist_path "$HOME/.bash_profile" ;;
        *)     : ;;
    esac
    # macOS defaults to zsh even when $SHELL isn't visible in a piped install; also
    # cover ~/.zprofile, which macOS login shells read.
    if [ "$PLATFORM" = "mac" ]; then
        persist_path "$HOME/.zshrc"
        persist_path "$HOME/.zprofile"
    fi

    # Make it usable in THIS run too (verify + login below depend on it).
    case ":$PATH:" in
        *":$PIPX_BIN:"*) ;;
        *) PATH="$PIPX_BIN:$PATH"; export PATH ;;
    esac
    hash -r 2>/dev/null || true

    # -- 5. clone repo + install CLI -------------------------------------------
    step "5/5  Fetching the abilities repo and installing the CLI"
    if [ -d "$TARGET_DIR/.git" ]; then
        info "repo already at $TARGET_DIR - updating"
        git -C "$TARGET_DIR" fetch -q origin "$BRANCH" \
            || die "Couldn't download the latest version. Check your connection and re-run."
        # Local work is set aside, never lost: commits the update would drop go
        # to a backup branch, edited or added files to a stash. Ignored files
        # (user/, .env) are left as they are.
        if ! git -C "$TARGET_DIR" merge-base --is-ancestor HEAD FETCH_HEAD 2>/dev/null; then
            BACKUP="openhome-backup-$(date +%Y%m%d-%H%M%S)"
            git -C "$TARGET_DIR" branch -f "$BACKUP" HEAD \
                && warn "your local commits were kept on branch '$BACKUP'"
        fi
        if [ -n "$(git -C "$TARGET_DIR" status --porcelain)" ]; then
            # Git before 2.22 can't stash without a name; give it one for this command.
            git -C "$TARGET_DIR" -c user.name="OpenHome installer" -c user.email="installer@openhome.invalid" \
                stash push --include-untracked -m "openhome installer backup" >/dev/null \
                && warn "your local changes were saved (restore with: git -C $TARGET_DIR stash pop)"
        fi
        git -C "$TARGET_DIR" checkout -q -B "$BRANCH" FETCH_HEAD \
            || die "Couldn't update $TARGET_DIR."
    else
        if [ -e "$TARGET_DIR" ]; then
            die "$TARGET_DIR exists but is not a git repo. Move it aside or set OPENHOME_DIR to another path."
        fi
        info "cloning $REPO_URL ($BRANCH) -> $TARGET_DIR"
        mkdir -p "$(dirname "$TARGET_DIR")"
        git clone --branch "$BRANCH" --depth 1 "$REPO_URL" "$TARGET_DIR"
    fi

    if $PIPX list 2>/dev/null | grep -q "openhome-client"; then
        info "openhome CLI already installed via pipx - reinstalling to match this checkout"
        $PIPX install --force --python "$PYTHON" --editable "$CLI_DIR"
    else
        $PIPX install --python "$PYTHON" --editable "$CLI_DIR"
    fi

    if [ ! -f "$TARGET_DIR/.env" ] && [ -f "$TARGET_DIR/.env.example" ]; then
        cp "$TARGET_DIR/.env.example" "$TARGET_DIR/.env"
        info "created $TARGET_DIR/.env (add your OPENHOME_API_KEY)"
    fi

    # -- verify + report -------------------------------------------------------
    step "Verifying"
    info "installed version: $(git -C "$TARGET_DIR" log -1 --format='%h %s')"
    if have openhome; then
        info "openhome command is on PATH"
        OPENHOME_PATH="$(command -v openhome)"
    else
        warn "openhome isn't on PATH in THIS shell yet - it's been added for new shells."
        warn "Open a new terminal, or run:  export PATH=\"$PIPX_BIN:\$PATH\""
        OPENHOME_PATH="$PIPX_BIN/openhome (after opening a new terminal)"
    fi

    SETTINGS_URL="https://app.openhome.com/dashboard/settings"

    cat <<EOF

${BOLD}${GREEN}OpenHome CLI installed.${RESET}

${BOLD}Where things are${RESET}
  Repo + templates:   ${TARGET_DIR}
  CLI package:        ${CLI_DIR}
  openhome command:   ${OPENHOME_PATH}
  Config (.env):      ${TARGET_DIR}/.env

${BOLD}Get your API key${RESET}
  ${SETTINGS_URL}
  ${DIM}(opening in your browser - if it didn't open, copy the link above)${RESET}
EOF

    if [ "$PLATFORM" = "mac" ]; then
        open "$SETTINGS_URL" >/dev/null 2>&1 || true
    else
        xdg-open "$SETTINGS_URL" >/dev/null 2>&1 || true
    fi

    # Interactive terminal -> log in now; curl-pipe has no usable stdin -> instruct.
    if [ -t 0 ] && have openhome; then
        printf '\n%sLogging in - paste your API key when prompted.%s\n' "$BOLD" "$RESET"
        openhome login || warn "login didn't complete - run \`openhome login\` yourself afterwards"
    else
        cat <<EOF

${BOLD}Next step${RESET}
  Run: ${DIM}openhome login${RESET}   and paste your API key (from the link above).

${DIM}If 'openhome' isn't found, open a new terminal first (pipx updated your PATH).${RESET}
EOF
    fi
}

main "$@"