#!/usr/bin/env bash
# Starchild CLI installer — one-line bootstrap.
#
#   curl -fsSL <server>/install/cli | bash
#
# What it does:
#   1. detect host platform (macOS / Linux × arm64 / amd64)
#   2. pick an install dir on $PATH (or in a sensible default), preferring
#      user-writable ones over /usr/local/bin so most users skip sudo
#   3. download the matching `starchild` binary, chmod +x, mv into place
#   4. ensure the install dir is on $PATH (best-effort: append an export
#      line to ~/.zshrc / ~/.bashrc / fish config, idempotent)
#   5. self-check: print `starchild --version`
#   6. print the next-step prompt the user should send to their agent
#
# Inspired by the bun.sh installer (shape, color helpers, shell wiring)
# but pared down to just the bits we need: no AVX/Rosetta detection, no
# completions, no tarball — `starchild` ships as a single static binary,
# so this script is mostly platform-pick → curl → mv → PATH.
#
# The literal `https://workroom.iamstarchild.com` below is rewritten by sc-chatroom's
# /install/cli handler at request time; never edit the placeholder.

set -euo pipefail

SERVER_URL='https://workroom.iamstarchild.com'

# ─── colors ────────────────────────────────────────────────────────────
Color_Off=''
Red=''; Green=''; Yellow=''; Dim=''
Bold_White=''; Bold_Green=''
if [ -t 1 ]; then
    Color_Off=$'\033[0m'
    Red=$'\033[0;31m'; Green=$'\033[0;32m'; Yellow=$'\033[0;33m'; Dim=$'\033[0;2m'
    Bold_White=$'\033[1m'; Bold_Green=$'\033[1;32m'
fi

error()     { echo -e "${Red}error${Color_Off}: $*" >&2; exit 1; }
info()      { echo -e "${Dim}$*${Color_Off}"; }
info_bold() { echo -e "${Bold_White}$*${Color_Off}"; }
success()   { echo -e "${Green}$*${Color_Off}"; }
warn()      { echo -e "${Yellow}warn${Color_Off}: $*" >&2; }

# ─── pre-flight ────────────────────────────────────────────────────────
command -v curl >/dev/null 2>&1 || error 'curl is required (apt install curl / brew install curl)'

# ─── 1. detect platform ───────────────────────────────────────────────
uname_s="$(uname -s 2>/dev/null || echo unknown)"
uname_m="$(uname -m 2>/dev/null || echo unknown)"
case "$uname_s" in
    Darwin) os=darwin ;;
    Linux)  os=linux  ;;
    *) error "unsupported OS $uname_s (only macOS / Linux are published)" ;;
esac
case "$uname_m" in
    arm64|aarch64) arch=arm64 ;;
    x86_64|amd64)  arch=amd64 ;;
    *) error "unsupported arch $uname_m (only arm64 / amd64 are published)" ;;
esac
target="${os}-${arch}"
binary_url="${SERVER_URL}/starchild-${target}"

info "Detected platform: ${Bold_White}${target}${Color_Off}"

# ─── 2. pick install dir ──────────────────────────────────────────────
# Preference order (first writable wins):
#   macOS arm64: /opt/homebrew/bin → /usr/local/bin (sudo)
#   macOS amd64: /usr/local/bin (sudo)
#   Linux:       $HOME/.local/bin (no sudo, but only if on $PATH or we'll add it)
#                → /usr/local/bin (sudo)
needs_sudo=0
case "$target" in
    darwin-arm64)
        if [ -d /opt/homebrew/bin ] && [ -w /opt/homebrew/bin ]; then
            install_dir=/opt/homebrew/bin
        else
            install_dir=/usr/local/bin
            needs_sudo=1
        fi
        ;;
    darwin-amd64)
        install_dir=/usr/local/bin
        # /usr/local/bin is user-owned on most Intel macs with Homebrew installed
        [ -w "$install_dir" ] || needs_sudo=1
        ;;
    linux-*)
        if [ -d "$HOME/.local/bin" ] || mkdir -p "$HOME/.local/bin" 2>/dev/null; then
            install_dir="$HOME/.local/bin"
        else
            install_dir=/usr/local/bin
            needs_sudo=1
        fi
        ;;
esac

target_path="${install_dir}/starchild"
info "Install path:      ${Bold_White}${target_path}${Color_Off}"

if [ "$needs_sudo" = 1 ]; then
    info "Will use sudo to write into ${install_dir} (you may be prompted)."
    sudo -v || error "sudo refused; pick a writable install dir manually and re-run."
fi

# ─── 3. download → chmod → mv ─────────────────────────────────────────
# If starchild is already installed, send its sha256 as If-None-Match so the
# server can reply 304 when we're already current — re-running the installer
# is then a cheap "check for update" rather than a forced re-download.
existing=""
if [ -x "$target_path" ]; then
    existing="$target_path"
elif command -v starchild >/dev/null 2>&1; then
    existing="$(command -v starchild)"
fi
inm=()
if [ -n "$existing" ]; then
    if command -v shasum >/dev/null 2>&1; then
        cur_sha="$(shasum -a 256 "$existing" 2>/dev/null | awk '{print $1}')"
    elif command -v sha256sum >/dev/null 2>&1; then
        cur_sha="$(sha256sum "$existing" 2>/dev/null | awk '{print $1}')"
    else
        cur_sha=""
    fi
    [ -n "$cur_sha" ] && inm=(-H "If-None-Match: \"${cur_sha}\"")
fi

tmp_bin=$(mktemp -t starchild.XXXXXX)
trap 'rm -f "$tmp_bin"' EXIT

info "Downloading from ${binary_url}…"
# -w '%{http_code}' lets us tell 304 (already current) from 200 (new build).
http_code=$(curl -fSL --progress-bar "${inm[@]}" -w '%{http_code}' -o "$tmp_bin" "$binary_url" 2>/dev/null || echo 000)

if [ "$http_code" = 304 ]; then
    rm -f "$tmp_bin"; trap - EXIT
    cur_ver="$("$existing" --version 2>/dev/null || echo installed)"
    success "✓ Already up to date (${cur_ver}) — nothing to download."
    exit 0
fi
if [ "$http_code" != 200 ]; then
    error "download failed from $binary_url (HTTP ${http_code})"
fi
if [ ! -s "$tmp_bin" ]; then
    error "download produced an empty file from $binary_url"
fi
chmod +x "$tmp_bin"

if [ "$needs_sudo" = 1 ]; then
    sudo mv -f "$tmp_bin" "$target_path"
else
    mv -f "$tmp_bin" "$target_path"
fi
trap - EXIT  # mv consumed the tempfile

success "✓ Installed starchild → ${target_path}"

# ─── 4. ensure install_dir is on $PATH (best-effort) ──────────────────
# We never edit a system-wide profile; only append to the user's interactive
# shell rc, and only if the directory isn't already on $PATH. Idempotent:
# a "# starchild" marker line guards against double-appending on re-runs.
on_path=0
case ":$PATH:" in *":${install_dir}:"*) on_path=1 ;; esac

added_to=""
if [ "$on_path" = 0 ]; then
    shell_name=$(basename "${SHELL:-bash}")
    marker="# starchild — added by install-cli.sh"
    case "$shell_name" in
        zsh)
            rc="$HOME/.zshrc"
            line="export PATH=\"${install_dir}:\$PATH\""
            ;;
        bash)
            # ~/.bash_profile is the login-shell file on macOS; ~/.bashrc on Linux.
            if [ "$os" = darwin ] && [ -f "$HOME/.bash_profile" ]; then
                rc="$HOME/.bash_profile"
            else
                rc="$HOME/.bashrc"
            fi
            line="export PATH=\"${install_dir}:\$PATH\""
            ;;
        fish)
            rc="$HOME/.config/fish/config.fish"
            mkdir -p "$(dirname "$rc")" 2>/dev/null || true
            line="set -gx PATH ${install_dir} \$PATH"
            ;;
        *)
            rc=""
            ;;
    esac

    if [ -n "$rc" ]; then
        # Don't double-append on re-runs.
        if [ -f "$rc" ] && grep -Fq "$marker" "$rc"; then
            info "PATH entry already present in $(basename "$rc")."
        else
            {
                printf '\n%s\n' "$marker"
                printf '%s\n' "$line"
            } >>"$rc"
            added_to="$rc"
            success "✓ Added ${install_dir} to PATH in $(basename "$rc")"
        fi
    else
        warn "Unrecognized shell '${shell_name}'. Add this to your shell rc manually:"
        info_bold "  export PATH=\"${install_dir}:\$PATH\""
    fi
fi

# ─── 5. self-check ────────────────────────────────────────────────────
# After mv the binary exists at $target_path, but the parent shell hasn't
# re-scanned its PATH cache — so `starchild --version` (relying on PATH)
# may "command not found". Call by absolute path here to verify the binary
# is healthy regardless of PATH state.
echo
info "Self-check:"
if version_line=$("$target_path" --version 2>&1); then
    success "  ✓ ${version_line}"
else
    warn "  starchild --version failed; the binary may be corrupted."
    warn "  Re-run the installer or download manually from ${binary_url}"
    exit 2
fi

# ─── 6. next steps ────────────────────────────────────────────────────
echo
info_bold "Next steps"
echo
if [ -n "$added_to" ]; then
    info "1. Reload your shell so 'starchild' is on PATH:"
    case "$shell_name" in
        fish) info_bold "     exec fish" ;;
        *)    info_bold "     exec ${SHELL:-bash}" ;;
    esac
    info "   (or open a new terminal — same effect)"
    echo
fi
info "2. Pair this device with your own agent. Open your agent chat and send:"
info_bold "     install skill \"@starchild/cli-bridge\" and give me a CLI key"
info "   The agent installs the bridge skill and replies with a 60s key."
echo
info "3. Paste the key locally to land a 1:1 stream to your own clawd:"
info_bold "     starchild login starchild_xxxxxxxx"
info "   Then ${Bold_White}starchild whoami${Color_Off}${Dim} verifies the bridge,"
info "   and ${Bold_White}starchild \"hello\"${Color_Off}${Dim} opens the stream.${Color_Off}"
echo
