#!/usr/bin/env bash
# TzamunCode installer.  Usage:  curl -fsSL https://code.tzamun.ai/install | bash
set -euo pipefail

BASE="https://code.tzamun.ai"
DEST="${TZAMUNCODE_HOME:-$HOME/.tzamuncode}"
BIN="${TZAMUNCODE_BIN:-$HOME/.local/bin}"
# TzamunCode's own config dir (isolated from any OpenCode install).
CFG_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/tzamuncode"
CFG="$CFG_DIR/tzamuncode.json"

say(){ printf '\033[32m›\033[0m %s\n' "$*"; }
warn(){ printf '\033[33m!\033[0m %s\n' "$*"; }

case "$(uname -s)" in
  Linux|Darwin) ;;
  *) echo "Unsupported OS: $(uname -s). TzamunCode needs Linux or macOS." >&2; exit 1;;
esac

# Preflight: a few native deps (node-pty, tree-sitter grammars) compile via
# node-gyp during `bun install`, which needs a C toolchain. Check up front and
# fail with clear guidance instead of a cryptic node-gyp ENOENT mid-install.
miss=""
command -v node    >/dev/null 2>&1 || miss="$miss node"
{ command -v cc || command -v gcc || command -v clang; } >/dev/null 2>&1 || miss="$miss C-compiler"
command -v make    >/dev/null 2>&1 || miss="$miss make"
command -v python3 >/dev/null 2>&1 || miss="$miss python3"
if [ -n "$miss" ]; then
  warn "Missing build prerequisites:$miss"
  case "$(uname -s)" in
    Darwin) echo "  macOS:         xcode-select --install   # + Node from https://nodejs.org or 'brew install node'";;
    Linux)  echo "  Debian/Ubuntu: sudo apt-get install -y build-essential python3 nodejs"
            echo "  RHEL/Alma:     sudo dnf install -y gcc gcc-c++ make python3 nodejs";;
  esac
  echo "Then re-run:  curl -fsSL https://code.tzamun.ai/install | bash"
  exit 1
fi

# 1. Bun runtime
if command -v bun >/dev/null 2>&1; then
  BUN="$(command -v bun)"
elif [ -x "$HOME/.bun/bin/bun" ]; then
  BUN="$HOME/.bun/bin/bun"
else
  say "Installing Bun runtime…"
  curl -fsSL https://bun.sh/install | bash >/dev/null
  BUN="$HOME/.bun/bin/bun"
fi
[ -x "$BUN" ] || { echo "Bun install failed" >&2; exit 1; }
# Bun must be on PATH so packages' postinstall scripts (e.g. fix-node-pty,
# which runs `bun run …`) can find it — full-path invocation isn't enough.
export PATH="$(cd "$(dirname "$BUN")" && pwd):$PATH"

# node-gyp builds native deps (tree-sitter grammars, node-pty). It ships inside
# npm but isn't exposed on PATH for Bun's build scripts, so ensure a standalone
# one. Prefer npm's user-writable prefix; fall back to Bun's global bin.
if ! command -v node-gyp >/dev/null 2>&1; then
  say "Installing node-gyp (builds native modules)…"
  npm install -g node-gyp >/dev/null 2>&1 || bun add -g node-gyp >/dev/null 2>&1 || true
fi
command -v node-gyp >/dev/null 2>&1 \
  || warn "node-gyp not found — native builds may fail. Fix: npm install -g node-gyp, then re-run."

# 2. Download + extract source
say "Downloading TzamunCode…"
rm -rf "$DEST"; mkdir -p "$DEST"
curl -fsSL "$BASE/tzamuncode.tar.gz" | tar -xz -C "$DEST" --strip-components=1

# 3. Dependencies
say "Installing dependencies (first run downloads a lot — give it a minute)…"
( cd "$DEST" && bun install )

# 4. Launcher
mkdir -p "$BIN"
cat > "$BIN/tzamuncode" <<LAUNCH
#!/usr/bin/env bash
# Absolute script path (NOT --cwd) so the user's cwd stays the project dir.
exec "$BUN" run "$DEST/packages/opencode/src/index.ts" "\$@"
LAUNCH
chmod +x "$BIN/tzamuncode"

# 5. Config (never clobber an existing one)
if [ ! -f "$CFG" ]; then
  mkdir -p "$CFG_DIR"
  cat > "$CFG" <<'JSON'
{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "tzamun": {
      "npm": "@ai-sdk/openai-compatible",
      "name": "TzamunAI Gateway",
      "options": { "baseURL": "https://code.tzamun.ai/api/v1" },
      "models": {
        "ILM:Coder":  { "name": "ILM Coder (30B)" },
        "ILM:Pro":    { "name": "ILM Pro" },
        "ILM:Vision": { "name": "ILM Vision" }
      }
    }
  },
  "model": "tzamun/ILM:Coder",
  "small_model": "tzamun/ILM:Pro"
}
JSON
  chmod 600 "$CFG"
  say "Wrote config → $CFG"
else
  warn "Existing config kept → $CFG (not overwritten)"
fi

echo
say "TzamunCode installed."
case ":$PATH:" in
  *":$BIN:"*) ;;
  *) warn "Add this to your shell profile so 'tzamuncode' is on PATH:"; echo "      export PATH=\"$BIN:\$PATH\"";;
esac
echo
say "Sign in with your mobile number, then start:"
echo "      tzamuncode login"
echo "      tzamuncode"
