#!/usr/bin/env bash
# Claude Skills 360 — Authenticated Installer
# Usage: curl -fsSL https://claudeskills360.com/install.sh | bash -s -- YOUR-KEY
#    or: bash install.sh YOUR-KEY
#    or: bash install.sh  (interactive prompt)

set -euo pipefail

BOLD='\033[1m'
GREEN='\033[0;32m'
RED='\033[0;31m'
GOLD='\033[0;33m'
PEACH='\033[38;5;216m'
DIM='\033[2m'
NC='\033[0m'

API_URL="https://btnnefiqedgsurjfiurf.supabase.co/functions/v1/validate-license"
SUPABASE_ANON_KEY="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImJ0bm5lZmlxZWRnc3VyamZpdXJmIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzI5MDg3OTMsImV4cCI6MjA4ODQ4NDc5M30.3c53_Vj13oIDfereDHdGD5gSMbo8HTrogUYf59d_cJY"

echo ""
echo -e "${PEACH}╔═══════════════════════════════════════════╗${NC}"
echo -e "${PEACH}║     CLAUDE SKILLS 360 — INSTALLER         ║${NC}"
echo -e "${PEACH}╚═══════════════════════════════════════════╝${NC}"
echo ""

# ── Detect OS ──────────────────────────────────────────────────────────────────
OS="$(uname -s)"
case "$OS" in
  Darwin)          PLATFORM="macOS" ;;
  Linux)           PLATFORM="Linux" ;;
  MINGW*|MSYS*|CYGWIN*)  PLATFORM="Windows" ;;
  *)               PLATFORM="$OS" ;;
esac

# Windows: resolve HOME correctly (Git Bash sometimes has issues)
if [ "$PLATFORM" = "Windows" ]; then
  HOME="${HOME:-$USERPROFILE}"
  # Ensure forward slashes
  HOME="$(echo "$HOME" | sed 's|\\|/|g')"
fi

# ── Dependency checks ──────────────────────────────────────────────────────────
for cmd in curl python3; do
  if ! command -v "$cmd" &>/dev/null; then
    echo -e "${RED}Error: '$cmd' is required but not installed.${NC}"
    echo -e "Install it and try again. Contact hello@claudeskills360.com for help."
    exit 1
  fi
done

# ── Get license key ───────────────────────────────────────────────────────────
# Priority: 1) CLI argument  2) saved key  3) interactive prompt
SAVED_KEY_FILE="$HOME/.claude/.cs360-license"
mkdir -p "$HOME/.claude"

if [ -n "${1:-}" ]; then
  # Key passed as argument: curl ... | bash -s -- CS360-XXXX-...
  LICENSE_KEY="$1"
  echo -e "${DIM}Using provided license key: ${LICENSE_KEY:0:12}...${NC}"
elif [ -f "$SAVED_KEY_FILE" ]; then
  SAVED_KEY="$(cat "$SAVED_KEY_FILE")"
  echo -e "${DIM}Found saved license: ${SAVED_KEY:0:12}...${NC}"
  # When piped (stdin is not a terminal), use saved key without prompting
  if [ -t 0 ]; then
    echo -e "${GOLD}Press Enter to use saved key, or type a new key:${NC}"
    read -rp "> " INPUT_KEY
    LICENSE_KEY="${INPUT_KEY:-$SAVED_KEY}"
  else
    LICENSE_KEY="$SAVED_KEY"
    echo -e "${DIM}(non-interactive mode — using saved key)${NC}"
  fi
else
  # No key provided and no saved key — must prompt interactively
  if [ ! -t 0 ]; then
    echo -e "${RED}Error: No license key provided.${NC}"
    echo -e "${RED}Usage: curl -fsSL https://claudeskills360.com/install.sh | bash -s -- YOUR-KEY${NC}"
    echo -e "${RED}   or: bash install.sh YOUR-KEY${NC}"
    echo -e ""
    echo -e "${GOLD}Get your free key at: https://claudeskills360.com${NC}"
    exit 1
  fi
  echo -e "${GOLD}Enter your license key:${NC}"
  echo -e "${GOLD}(Format: CS360-XXXX-XXXX-XXXX-XXXX)${NC}"
  read -rp "> " LICENSE_KEY
fi

# ── Validate key format ────────────────────────────────────────────────────────
if ! echo "$LICENSE_KEY" | grep -qE '^CS360-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$'; then
  echo -e "${RED}Invalid key format. Expected: CS360-XXXX-XXXX-XXXX-XXXX (all caps)${NC}"
  exit 1
fi

# ── Generate device fingerprint ────────────────────────────────────────────────
# SHA256 of "hostname-username" — no personal data leaves the machine
HOSTNAME_VAL="$(hostname 2>/dev/null || echo 'unknown')"
USERNAME_VAL="$(whoami 2>/dev/null || echo 'user')"
DEVICE_RAW="${HOSTNAME_VAL}-${USERNAME_VAL}"

if command -v shasum &>/dev/null; then
  DEVICE_FP="$(printf '%s' "$DEVICE_RAW" | shasum -a 256 | cut -d' ' -f1)"
elif command -v sha256sum &>/dev/null; then
  DEVICE_FP="$(printf '%s' "$DEVICE_RAW" | sha256sum | cut -d' ' -f1)"
else
  # Fallback: use python3
  DEVICE_FP="$(python3 -c "import hashlib,sys; print(hashlib.sha256(sys.argv[1].encode()).hexdigest())" "$DEVICE_RAW")"
fi

DEVICE_NAME="${USERNAME_VAL}@${HOSTNAME_VAL} (${PLATFORM})"

echo ""
echo -e "${GOLD}Validating license...${NC}"

# ── Call the API ───────────────────────────────────────────────────────────────
# Safely build the JSON payload using python3 to avoid injection
JSON_BODY="$(python3 -c "
import json, sys
print(json.dumps({'key': sys.argv[1], 'device_fingerprint': sys.argv[2], 'device_name': sys.argv[3]}))
" "$LICENSE_KEY" "$DEVICE_FP" "$DEVICE_NAME")"

RESPONSE="$(curl -s -m 30 -X POST "$API_URL" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer ${SUPABASE_ANON_KEY}" \
  -d "$JSON_BODY" || true)"

if [ -z "$RESPONSE" ]; then
  echo -e "${RED}Could not reach the license server. Check your internet connection and try again.${NC}"
  exit 1
fi

# Parse response with python3
VALID="$(python3 -c "import sys,json; d=json.loads(sys.argv[1]); print('true' if d.get('valid') else 'false')" "$RESPONSE" 2>/dev/null || echo 'false')"
ERROR_MSG="$(python3 -c "import sys,json; d=json.loads(sys.argv[1]); print(d.get('error',''))" "$RESPONSE" 2>/dev/null || echo '')"
DOWNLOAD_URL="$(python3 -c "import sys,json; d=json.loads(sys.argv[1]); print(d.get('download_url',''))" "$RESPONSE" 2>/dev/null || echo '')"
REMAINING="$(python3 -c "import sys,json; d=json.loads(sys.argv[1]); print(d.get('remaining_activations','?'))" "$RESPONSE" 2>/dev/null || echo '?')"
TIER="$(python3 -c "import sys,json; d=json.loads(sys.argv[1]); p=d.get('plan','starter'); print('free' if p=='starter' else 'full')" "$RESPONSE" 2>/dev/null || echo 'free')"

if [ "$VALID" != "true" ]; then
  echo -e "${RED}License validation failed: ${ERROR_MSG:-Unknown error}${NC}"
  echo -e "${RED}Contact hello@claudeskills360.com for support.${NC}"
  exit 1
fi

echo -e "${GREEN}✓ License valid! Activations remaining: ${REMAINING}${NC}"
echo ""

# ── Download bundle ────────────────────────────────────────────────────────────
if [ -z "$DOWNLOAD_URL" ]; then
  echo -e "${RED}Error: No download URL returned. Contact hello@claudeskills360.com${NC}"
  exit 1
fi

echo -e "${GOLD}Downloading skills bundle...${NC}"
TEMP_DIR="$(mktemp -d)"
trap 'rm -rf "$TEMP_DIR"' EXIT

BUNDLE_FILE="$TEMP_DIR/cs360-bundle.tar.gz"
HTTP_CODE="$(curl -s -L -w '%{http_code}' -o "$BUNDLE_FILE" "$DOWNLOAD_URL")"

if [ "$HTTP_CODE" != "200" ] || [ ! -f "$BUNDLE_FILE" ]; then
  echo -e "${RED}Download failed (HTTP $HTTP_CODE). Contact support.${NC}"
  exit 1
fi

# ── Extract bundle ─────────────────────────────────────────────────────────────
echo -e "${GOLD}Installing skills...${NC}"
tar -xzf "$BUNDLE_FILE" -C "$TEMP_DIR"

# ── Install files ──────────────────────────────────────────────────────────────
INSTALL_DIR="$HOME/.claude"
mkdir -p "$INSTALL_DIR/skills" "$INSTALL_DIR/agents" "$INSTALL_DIR/swarms"

# Find the extracted content — tar may create a nested folder
# (e.g., cs360-bundle-v1.0/, starter-bundle/, etc.)
# Pick whatever subdir actually contains a skills/ folder.
EXTRACT_ROOT="$TEMP_DIR"
if [ ! -d "$TEMP_DIR/skills" ]; then
  for candidate in "$TEMP_DIR"/*/; do
    if [ -d "${candidate}skills" ] || [ -d "${candidate}agents" ] || [ -d "${candidate}swarms" ]; then
      EXTRACT_ROOT="${candidate%/}"
      break
    fi
  done
fi

SKILL_COUNT=0
if [ -d "$EXTRACT_ROOT/skills" ]; then
  find "$EXTRACT_ROOT/skills" -name '*.md' -type f | while IFS= read -r f; do
    cp "$f" "$INSTALL_DIR/skills/" && SKILL_COUNT=$((SKILL_COUNT + 1))
  done
  # Recount since the subshell can't update the parent var
  SKILL_COUNT=$(find "$INSTALL_DIR/skills" -name '*.md' -type f 2>/dev/null | wc -l | tr -d ' ')
fi

AGENT_COUNT=0
if [ -d "$EXTRACT_ROOT/agents" ]; then
  find "$EXTRACT_ROOT/agents" -name '*.md' -type f -exec cp {} "$INSTALL_DIR/agents/" \;
  AGENT_COUNT=$(find "$INSTALL_DIR/agents" -name '*.md' -type f 2>/dev/null | wc -l | tr -d ' ')
fi

SWARM_COUNT=0
if [ -d "$EXTRACT_ROOT/swarms" ]; then
  find "$EXTRACT_ROOT/swarms" -name '*.md' -type f -exec cp {} "$INSTALL_DIR/swarms/" \;
  SWARM_COUNT=$(find "$INSTALL_DIR/swarms" -name '*.md' -type f 2>/dev/null | wc -l | tr -d ' ')
fi

# ── Save license key for future re-installs ────────────────────────────────────
echo "$LICENSE_KEY" > "$SAVED_KEY_FILE"
chmod 600 "$SAVED_KEY_FILE"

# ── Done ───────────────────────────────────────────────────────────────────────
echo ""
echo -e "${GREEN}╔═══════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║     INSTALLATION COMPLETE                 ║${NC}"
echo -e "${GREEN}╚═══════════════════════════════════════════╝${NC}"
echo ""
echo -e "${GREEN}✓ Skills installed:  ${BOLD}${SKILL_COUNT}${NC}"
echo -e "${GREEN}✓ Agents installed:  ${BOLD}${AGENT_COUNT}${NC}"
echo -e "${GREEN}✓ Swarms installed:  ${BOLD}${SWARM_COUNT}${NC}"
echo -e "${GREEN}✓ License saved to:  ~/.claude/.cs360-license${NC}"
echo ""

if [ "$TIER" = "free" ]; then
  # ── Free tier completion ─────────────────────────────────────────────────────
  echo -e "${PEACH}Ready to use! Open Claude Code and try:${NC}"
  echo -e "${GOLD}  claude /seo-audit mysite.com${NC}"
  echo -e "${GOLD}  claude /find-bugs src/${NC}"
  echo -e "${GOLD}  claude /generate-tests app.ts${NC}"
  echo ""
  echo -e "${PEACH}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
  echo ""
  echo -e "${PEACH}  You're on the ${BOLD}Free Starter Kit${NC}${PEACH} (360 skills)${NC}"
  echo ""
  echo -e "${DIM}  Want the full arsenal?${NC}"
  echo ""
  echo -e "${BOLD}  ⚡ 2,350+ skills${NC}  ${DIM}(vs 360 free)${NC}"
  echo -e "${BOLD}  🤖 45+ autonomous agents${NC}"
  echo -e "${BOLD}  🔥 12 multi-swarm orchestrators${NC}"
  echo -e "${BOLD}  🧠 GraphRAG & knowledge tools${NC}"
  echo -e "${BOLD}  ∞  Lifetime updates${NC}"
  echo ""
  echo -e "${PEACH}  One-time \$39. No subscription.${NC}"
  echo -e "${GREEN}  → https://claudeskills360.com/#pricing${NC}"
  echo ""
  echo -e "${PEACH}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
else
  # ── Paid tier completion ─────────────────────────────────────────────────────
  echo -e "${PEACH}You have ${BOLD}Full Access${NC}${PEACH} — everything is unlocked.${NC}"
  echo ""
  echo -e "${PEACH}Try these to get started:${NC}"
  echo -e "${GOLD}  claude /seo-audit mysite.com${NC}        ${DIM}# Full SEO audit${NC}"
  echo -e "${GOLD}  claude /morning-brief${NC}               ${DIM}# Daily market brief${NC}"
  echo -e "${GOLD}  claude /find-bugs src/${NC}              ${DIM}# Security scan${NC}"
  echo -e "${GOLD}  claude /marketing-swarm \"launch\"${NC}    ${DIM}# Deploy a swarm${NC}"
  echo ""
  echo -e "${GREEN}  Library grows every week. Updates are automatic.${NC}"
fi

echo ""
echo -e "${DIM}Setup guide: https://claudeskills360.com/setup${NC}"
echo -e "${DIM}Support: hello@claudeskills360.com${NC}"
echo ""
