#!/bin/sh
# Intent Atlas — Universal Customer Agent Installer (POSIX sh)
# Installs atlas-client CLI + Zero-Theory Customer API Skill across:
# - Google Antigravity (agy): ~/.gemini/antigravity-cli/skills/intent-atlas/SKILL.md & ./.agents/skills/intent-atlas/SKILL.md
# - OpenAI Codex (codex):     ~/.codex/skills/intent-atlas/SKILL.md & ./.agents/skills/intent-atlas/SKILL.md
# - OpenCode (opencode):      ~/.config/opencode/skills/intent-atlas/SKILL.md & ./.opencode/skills/intent-atlas/SKILL.md
# - Claude Code (claude):     ~/.claude/skills/intent-atlas/SKILL.md & ./.claude/skills/intent-atlas/SKILL.md
# - Cursor / Windsurf:        ./.agents/skills/intent-atlas/SKILL.md

set -e

ATLAS_URL="${ATLAS_API_URL:-https://clients.intentatlas.ai}"
ATLAS_URL="$(printf '%s' "$ATLAS_URL" | sed 's:/*$::')"

BIN_DIR="$HOME/.intent-atlas/bin"
LOCAL_BIN="$HOME/.local/bin"
CONFIG_DIR="$HOME/.config/intent-atlas"

echo ""
echo "================================================================"
echo "  INTENT ATLAS — AI Agent CLI & Multi-Harness Skill Installer"
echo "================================================================"
echo ""

mkdir -p "$BIN_DIR" "$LOCAL_BIN" "$CONFIG_DIR"

echo "[1/3] Installing atlas-client CLI to $BIN_DIR/atlas-client.mjs ..."
curl -fsSL "$ATLAS_URL/agent-skill/atlas-client.mjs" -o "$BIN_DIR/atlas-client.mjs"
chmod +x "$BIN_DIR/atlas-client.mjs"
ln -sf "$BIN_DIR/atlas-client.mjs" "$LOCAL_BIN/atlas-client"

echo "[2/3] Installing Customer API Skill (SKILL.md) across agent harnesses..."
SKILL_TMP="$CONFIG_DIR/SKILL.md.tmp"
curl -fsSL "$ATLAS_URL/agent-skill/SKILL.md" -o "$SKILL_TMP"

# Global harness skill directories (Antigravity agy, Codex, OpenCode, Claude Code)
for TARGET_DIR in \
  "$HOME/.gemini/antigravity-cli/skills/intent-atlas" \
  "$HOME/.codex/skills/intent-atlas" \
  "$HOME/.config/opencode/skills/intent-atlas" \
  "$HOME/.claude/skills/intent-atlas"
do
  mkdir -p "$TARGET_DIR"
  cp "$SKILL_TMP" "$TARGET_DIR/SKILL.md"
  echo "      ✓ Installed $TARGET_DIR/SKILL.md"
done

# Workspace-local skill directories (.agents for agy/codex/cursor/windsurf, .opencode, .claude)
for LOCAL_DIR in \
  "./.agents/skills/intent-atlas" \
  "./.opencode/skills/intent-atlas" \
  "./.claude/skills/intent-atlas"
do
  if mkdir -p "$LOCAL_DIR" 2>/dev/null; then
    cp "$SKILL_TMP" "$LOCAL_DIR/SKILL.md"
    echo "      ✓ Installed $LOCAL_DIR/SKILL.md"
  fi
done

rm -f "$SKILL_TMP"

if [ "${ATLAS_SKIP_LOGIN:-0}" = "1" ]; then
  echo "[3/3] Skipping interactive device login (ATLAS_SKIP_LOGIN=1)."
  exit 0
fi

echo "[3/3] Starting Browser Device Approval Flow..."
ATLAS_API_URL="$ATLAS_URL" node "$BIN_DIR/atlas-client.mjs" login
