#!/usr/bin/env bash
set -euo pipefail

# Craft Agents installer (macOS)
# - Auto-detects CPU arch
# - Downloads matching ZIP
# - Installs into ~/Applications
# - Removes quarantine and launches app

if [[ "$(uname -s)" != "Darwin" ]]; then
  echo "❌ This installer is for macOS only."
  exit 1
fi

# ── Banner ──────────────────────────────────────────────────
cat << 'BANNER'

          ___           ___           ___           ___
         /\__\         /\  \         /\  \         /\__\
        /::|  |       /::\  \        \:\  \       /:/  /
       /:|:|  |      /:/\:\  \        \:\  \     /:/__/
      /:/|:|__|__   /::\~\:\  \       /::\  \   /::\__\____
     /:/ |::::\__\ /:/\:\ \:\__\     /:/\:\__\ /:/\:::::\__\
     \/__/~~/:/  / \:\~\:\ \/__/    /:/  \/__/ \/_|:|~~|~
           /:/  /   \:\ \:\__\     /:/  /         |:|  |
          /:/  /     \:\ \/__/     \/__/          |:|  |
         /:/  /       \:\__\                      |:|  |
         \/__/         \/__/                       \|__|

      Martin et Karczinski — Craft Agents Installer

BANNER

# Pretty helpers
step() { printf "\n👉 %s\n" "$1"; }
ok() { printf "✅ %s\n" "$1"; }
info() { printf "ℹ️  %s\n" "$1"; }

spinner() {
  # spinner <pid> <message>
  local pid="$1"
  local msg="$2"
  local marks='⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'
  local i=0
  while kill -0 "$pid" 2>/dev/null; do
    local c="${marks:i%${#marks}:1}"
    printf "\r%s %s" "$c" "$msg"
    i=$((i+1))
    sleep 0.08
  done
  printf "\r✔ %s\n" "$msg"
}

ARCH="$(uname -m)"
URL="https://releases.srv1066566.hstgr.cloud/Craft-Agent-arm64.zip"
[[ "$ARCH" == "x86_64" ]] && URL="https://releases.srv1066566.hstgr.cloud/Craft-Agent-x64.zip"

APP_HOME="$HOME/Applications"
TMP_DIR="$(mktemp -d)"
ZIP_PATH="$TMP_DIR/app.zip"
UNZIP_DIR="$TMP_DIR/unzipped"

step "Preparing installer magic 🪄"
info "Detected architecture: $ARCH"
info "Download source: $URL"

step "Downloading latest Craft Agents package 🚀"
curl -fL --progress-bar "$URL?ts=$(date +%s)" -o "$ZIP_PATH"
ok "Download complete"

step "Unpacking app bundle 📦"
(ditto -x -k "$ZIP_PATH" "$UNZIP_DIR") &
spinner $! "Extracting files"

APP_PATH="$(find "$UNZIP_DIR" -maxdepth 3 -name '*.app' | head -n 1 || true)"
if [[ -z "${APP_PATH}" ]]; then
  echo "❌ Could not find .app inside the downloaded archive."
  exit 1
fi

APP_NAME="$(basename "$APP_PATH")"
TARGET_PATH="$APP_HOME/$APP_NAME"

step "Installing into ~/Applications ✨"
mkdir -p "$APP_HOME"
rm -rf "$TARGET_PATH"
cp -R "$APP_PATH" "$APP_HOME/"
ok "Installed: $TARGET_PATH"

step "Removing Gatekeeper quarantine 🔓"
xattr -dr com.apple.quarantine "$TARGET_PATH" 2>/dev/null || true
ok "Security flag cleaned"

step "Version check 🧪"
VERSION="$(defaults read "$TARGET_PATH/Contents/Info" CFBundleVersion 2>/dev/null || echo 'unknown')"
ok "Installed version: $VERSION"

step "Launching app 🎉"
open "$TARGET_PATH"
ok "All done. Welcome to Craft Agents!"

echo
printf "Tip: You can drag '%s' to the Dock for quick access.\n" "$APP_NAME"
