#!/bin/sh
# Treeship one-liner setup: install CLI, init, instrument agents
# Usage: curl -fsSL treeship.dev/setup | sh
#
# Platform support at v0.9.3: macOS and Linux only.
# Windows users: this script is POSIX sh -- use WSL, or wait for v0.10.0
# which adds a native Windows binary and PowerShell setup path.
set -e

echo ""
echo "  Setting up Treeship..."
echo ""

# Step 1: Install CLI
if command -v treeship >/dev/null 2>&1; then
  echo "  ✓ CLI already installed ($(treeship --version))"
else
  echo "  Installing Treeship CLI..."
  curl -fsSL treeship.dev/install | sh
fi

# Step 2: Init (skip if already done)
if [ -d "$HOME/.treeship" ] && [ -f "$HOME/.treeship/config.json" ]; then
  SHIP_ID=$(grep -o '"ship_id":"[^"]*"' "$HOME/.treeship/config.json" 2>/dev/null | head -1 | cut -d'"' -f4)
  if [ -n "$SHIP_ID" ]; then
    echo "  ✓ Already initialized ($SHIP_ID)"
  else
    treeship init --quiet
  fi
else
  treeship init --quiet
fi

# Version gate: the TREESHIP.md drop in `treeship add` requires v0.9.3+.
# If an older binary is on PATH, the rest of setup still works, but the
# trust file won't appear -- warn loudly so the user knows to upgrade.
#
# Comparison strategy:
#   1. Prefer node for strict semver semantics including prerelease handling
#      (0.9.3-rc.1 must be treated as < 0.9.3 per semver.org section 11.4).
#   2. Fall back to `sort -V` if node is missing -- handles 99% of cases
#      correctly but cannot reliably reject prereleases of the target
#      version. Emits a softer warning in that case.
#   3. If we cannot extract a version string at all from `treeship --version`,
#      warn that the gate could not run, rather than silently skipping.
RAW_VER=$(treeship --version 2>/dev/null || true)
INSTALLED_VER=$(printf '%s' "$RAW_VER" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?' | head -1)
MIN_VER="0.9.3"

ts_gate_warn() {
  echo ""
  echo "  ⚠  $1"
  echo "     Setup will continue but won't write TREESHIP.md."
  echo "     To upgrade: reinstall via your package manager, or re-run"
  echo "     curl -fsSL treeship.dev/install | sh"
  echo ""
}

if [ -z "$INSTALLED_VER" ]; then
  if [ -n "$RAW_VER" ]; then
    ts_gate_warn "Could not parse a semver from \`treeship --version\` output: \"$RAW_VER\". Cannot verify CLI is >= ${MIN_VER}."
  fi
  # If RAW_VER is empty, the CLI isn't installed yet -- Step 1 above will
  # install it, so don't warn here.
elif command -v node >/dev/null 2>&1; then
  # Strict semver compare via node. Exits 0 if installed >= min, 1 otherwise.
  if ! node -e '
    const [inst, min] = process.argv.slice(1);
    const parse = v => {
      const [core, pre] = v.split("-");
      const [ma, mi, pa] = core.split(".").map(n => parseInt(n, 10));
      return { ma, mi, pa, pre: pre ?? null };
    };
    const a = parse(inst), b = parse(min);
    if (a.ma !== b.ma) process.exit(a.ma > b.ma ? 0 : 1);
    if (a.mi !== b.mi) process.exit(a.mi > b.mi ? 0 : 1);
    if (a.pa !== b.pa) process.exit(a.pa > b.pa ? 0 : 1);
    // cores equal: a release > prerelease of the same core (semver 11.4)
    if (a.pre === null && b.pre === null) process.exit(0);
    if (a.pre === null) process.exit(0);   // installed release > min prerelease
    if (b.pre === null) process.exit(1);   // installed prerelease < min release
    process.exit(a.pre >= b.pre ? 0 : 1);   // rough prerelease compare
  ' "$INSTALLED_VER" "$MIN_VER" >/dev/null 2>&1; then
    ts_gate_warn "Treeship CLI is v${INSTALLED_VER}; the trust file drop requires v${MIN_VER}+ (stable, not a prerelease)."
  fi
else
  # Fallback: sort -V. Handles ordinary release versions correctly but
  # may not reject prereleases (e.g. some implementations sort 0.9.3-rc.1
  # equal to or after 0.9.3). Mention the limitation.
  LOWEST=$(printf '%s\n%s\n' "$INSTALLED_VER" "$MIN_VER" | sort -V | head -1)
  if [ "$LOWEST" != "$MIN_VER" ]; then
    ts_gate_warn "Treeship CLI is v${INSTALLED_VER}; the trust file drop requires v${MIN_VER}+. (Note: \`node\` not found; could not strictly check prerelease status.)"
  fi
fi

# Step 3: Instrument detected agents (also drops ./TREESHIP.md, the
# framework-agnostic trust + usage doc, into this project, when CLI >= 0.9.3)
echo ""
treeship add --all

echo ""
echo "  ✓ Treeship ready."
echo ""
echo "  Try: treeship session start --name \"my first task\""
echo ""
if [ -f "./TREESHIP.md" ]; then
  echo "  AI agents: read ./TREESHIP.md for what gets captured and how to use treeship wrap."
else
  echo "  AI agents: see https://github.com/zerkerlabs/treeship/blob/main/TREESHIP.md"
fi
echo ""
