#!/usr/bin/env bash
#
# Head of Product UI — install + run script for alpha-internal distribution.
#
# Usage:
#   bash scripts/install.sh        # installs deps, builds, then prints the start command
#   bash scripts/install.sh --run  # same, then starts the server and opens the browser
#
set -euo pipefail

cyan() { printf "\033[36m%s\033[0m\n" "$1"; }
red()  { printf "\033[31m%s\033[0m\n" "$1"; }
ok()   { printf "\033[32m✓\033[0m %s\n" "$1"; }

cyan "Head of Product UI — installer"
echo

# 1. Bun
if ! command -v bun >/dev/null 2>&1; then
  cyan "Installing Bun (https://bun.sh)…"
  curl -fsSL https://bun.sh/install | bash
  # Ensure bun is on PATH for the rest of this script.
  export BUN_INSTALL="$HOME/.bun"
  export PATH="$BUN_INSTALL/bin:$PATH"
else
  ok "Bun: $(bun --version)"
fi

# 2. Claude Code presence (warning only — the wizard handles this in-app)
if [ -d "$HOME/.claude" ]; then
  ok "Claude Code directory detected at ~/.claude"
else
  red "Claude Code not detected. You can either:"
  echo "    - Install it: https://docs.anthropic.com/en/docs/claude-code/quickstart"
  echo "    - Or set ANTHROPIC_API_KEY before starting the app."
  echo "  (The setup wizard inside the app will guide you through this.)"
fi

# 3. Project deps
cyan "Installing project dependencies…"
bun install

# 4. Production build — skipped when dist/ ships pre-built in a release zip.
#    Source-clone users (no dist/) get the build; zip-distribution users
#    save the ~2 min build step.
if [ ! -d "dist" ] || [ -z "$(ls -A dist 2>/dev/null)" ]; then
  cyan "Building the app…"
  bun run build
else
  ok "Using prebuilt dist/ (shipped in release zip)"
fi

echo
ok "Install complete."
echo
cyan "To start the app:"
echo "  bun start"
echo "Then open http://localhost:5181 in your browser."
echo

if [ "${1:-}" = "--run" ]; then
  cyan "Starting the app…"
  (sleep 2 && open http://localhost:5181) &
  bun run server/index.ts
fi
