#!/bin/sh
# FateStar · 紫微斗數大模型：鄭大錢 — connect FateStar to Claude Code / Codex
#   curl -fsSL https://www.fatestar.top/install.sh | sh
# What it does (nothing else):
#   1. downloads the FateStar skill into ~/.claude/skills/fatestar and ~/.codex/skills/fatestar
#   2. registers the MCP server https://www.fatestar.top/mcp with the `claude` / `codex` CLIs if they are installed
# It never asks for a password; you sign in to FateStar in your browser afterwards.
set -eu

MCP_URL="https://www.fatestar.top/mcp"
SKILL_URL="https://www.fatestar.top/skills/fatestar/SKILL.md"

say() { printf '%s\n' "$*"; }

fetch() {
  if command -v curl >/dev/null 2>&1; then curl -fsSL "$1" -o "$2"
  elif command -v wget >/dev/null 2>&1; then wget -qO "$2" "$1"
  else say "Need curl or wget."; exit 1
  fi
}

install_skill() {
  dir="$1/skills/fatestar"
  mkdir -p "$dir"
  fetch "$SKILL_URL" "$dir/SKILL.md"
  say "  skill -> $dir/SKILL.md"
}

found=0
say "FateStar: installing..."

if command -v claude >/dev/null 2>&1 || [ -d "$HOME/.claude" ]; then
  install_skill "$HOME/.claude"
  if command -v claude >/dev/null 2>&1; then
    if claude mcp get fatestar >/dev/null 2>&1; then
      say "  Claude Code: MCP server 'fatestar' already registered"
    else
      claude mcp add --transport http --scope user fatestar "$MCP_URL" >/dev/null && say "  Claude Code: MCP server 'fatestar' added"
    fi
  fi
  found=1
fi

if command -v codex >/dev/null 2>&1 || [ -d "$HOME/.codex" ]; then
  install_skill "$HOME/.codex"
  if command -v codex >/dev/null 2>&1; then
    if codex mcp get fatestar >/dev/null 2>&1; then
      say "  Codex: MCP server 'fatestar' already registered"
    else
      codex mcp add fatestar --url "$MCP_URL" >/dev/null && say "  Codex: MCP server 'fatestar' added"
    fi
  fi
  found=1
fi

if [ "$found" -eq 0 ]; then
  say "Neither Claude Code nor Codex was found. See https://www.fatestar.top/agent.md for other apps."
  exit 0
fi

say ""
say "Last step - sign in to FateStar in your browser:"
say "  Claude Code: type /mcp, pick 'fatestar', choose Authenticate"
say "  Codex:       run  codex mcp login fatestar"
say "Charting is free; AI readings use your FateStar credits. Guide: https://www.fatestar.top/connect-ai"
