#!/bin/bash
# =============================================================================
# SubVault Installer
# Usage: curl -fsSL https://subvault.ai/install.sh | bash
#
# What this does:
#   1. Checks macOS 13+ (Ventura or later)
#   2. Downloads the latest SubVault.dmg
#   3. Mounts it, copies SubVault.app to /Applications
#   4. Cleans up and launches SubVault
#
# Task #397 — Phase 7
# =============================================================================

set -euo pipefail

APP_NAME="SubVault"
API_URL="https://api.subvault.ai"
MIN_MACOS_MAJOR=13
TMP_DIR=$(mktemp -d)

cleanup() {
    # Unmount DMG if mounted
    if [[ -n "${MOUNT_POINT:-}" ]] && mount | grep -q "$MOUNT_POINT"; then
        hdiutil detach "$MOUNT_POINT" -quiet 2>/dev/null || true
    fi
    rm -rf "$TMP_DIR"
}
trap cleanup EXIT

# --- Colors ---
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
BOLD='\033[1m'
NC='\033[0m'

echo ""
echo -e "${BOLD}  ╔═══════════════════════════════════╗${NC}"
echo -e "${BOLD}  ║       ${BLUE}SubVault${NC}${BOLD} Installer          ║${NC}"
echo -e "${BOLD}  ║   Your AI remembers everything.   ║${NC}"
echo -e "${BOLD}  ╚═══════════════════════════════════╝${NC}"
echo ""

# --- Step 1: Check macOS version ---------------------------------------------
echo -e "  ${BLUE}→${NC} Checking system requirements..."

if [[ "$(uname)" != "Darwin" ]]; then
    echo -e "  ${RED}✗${NC} SubVault requires macOS. This appears to be $(uname)."
    exit 1
fi

MACOS_VERSION=$(sw_vers -productVersion)
MACOS_MAJOR=$(echo "$MACOS_VERSION" | cut -d. -f1)

if [[ "$MACOS_MAJOR" -lt "$MIN_MACOS_MAJOR" ]]; then
    echo -e "  ${RED}✗${NC} macOS 13 (Ventura) or later required. You have macOS $MACOS_VERSION."
    exit 1
fi

ARCH=$(uname -m)
if [[ "$ARCH" != "arm64" && "$ARCH" != "x86_64" ]]; then
    echo -e "  ${RED}✗${NC} Unsupported architecture: $ARCH"
    exit 1
fi

echo -e "  ${GREEN}✓${NC} macOS $MACOS_VERSION ($ARCH)"

# --- Step 2: Get latest release URL ------------------------------------------
echo -e "  ${BLUE}→${NC} Fetching latest version..."

# Query the appcast for the latest release DMG URL
APPCAST=$(curl -fsSL "${API_URL}/updates/appcast.xml" 2>/dev/null || true)

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

# Parse DMG URL from appcast XML (latest = first enclosure)
DMG_URL=$(echo "$APPCAST" | grep -o 'url="[^"]*\.dmg"' | head -1 | sed 's/url="//;s/"//')
LATEST_VERSION=$(echo "$APPCAST" | grep -o 'sparkle:shortVersionString="[^"]*"' | head -1 | sed 's/sparkle:shortVersionString="//;s/"//')

if [[ -z "$DMG_URL" ]]; then
    echo -e "  ${YELLOW}⚠${NC}  No releases published yet. Check back soon!"
    echo -e "      Visit ${BOLD}https://subvault.ai${NC} for updates."
    exit 0
fi

echo -e "  ${GREEN}✓${NC} Latest version: ${BOLD}v${LATEST_VERSION}${NC}"

# --- Step 3: Check existing installation --------------------------------------
if [[ -d "/Applications/${APP_NAME}.app" ]]; then
    EXISTING_VERSION=$(/usr/libexec/PlistBuddy -c "Print :CFBundleShortVersionString" "/Applications/${APP_NAME}.app/Contents/Info.plist" 2>/dev/null || echo "unknown")
    echo -e "  ${YELLOW}⚠${NC}  Existing installation found (v${EXISTING_VERSION})"
    echo -e "      This will upgrade to v${LATEST_VERSION}."
    echo ""
    echo -n "  Continue? [Y/n] "
    read -r CONFIRM < /dev/tty || CONFIRM="n"
    if [[ "$CONFIRM" =~ ^[Nn] ]]; then
        echo -e "  ${YELLOW}→${NC} Installation cancelled."
        exit 0
    fi
fi

# --- Step 4: Download --------------------------------------------------------
echo -e "  ${BLUE}→${NC} Downloading SubVault v${LATEST_VERSION}..."

DMG_FILE="$TMP_DIR/${APP_NAME}-${LATEST_VERSION}.dmg"
curl -fSL --progress-bar "$DMG_URL" -o "$DMG_FILE"

if [[ ! -f "$DMG_FILE" ]] || [[ $(stat -f%z "$DMG_FILE") -lt 1000 ]]; then
    echo -e "  ${RED}✗${NC} Download failed or file is too small."
    exit 1
fi

echo -e "  ${GREEN}✓${NC} Downloaded ($(du -h "$DMG_FILE" | cut -f1))"

# --- Step 5: Mount & Install -------------------------------------------------
echo -e "  ${BLUE}→${NC} Installing..."

MOUNT_POINT=$(hdiutil attach "$DMG_FILE" -nobrowse -quiet | grep "/Volumes" | awk '{$1=$2=""; print $0}' | xargs)

if [[ -z "$MOUNT_POINT" ]] || [[ ! -d "$MOUNT_POINT" ]]; then
    echo -e "  ${RED}✗${NC} Failed to mount DMG."
    exit 1
fi

# Find the .app in the mounted volume
APP_SOURCE=$(find "$MOUNT_POINT" -maxdepth 1 -name "*.app" | head -1)
if [[ -z "$APP_SOURCE" ]]; then
    echo -e "  ${RED}✗${NC} No .app found in DMG."
    exit 1
fi

# Kill running instance if any
pkill -x "$APP_NAME" 2>/dev/null || true
sleep 0.5

# Copy to /Applications
rm -rf "/Applications/${APP_NAME}.app"
cp -R "$APP_SOURCE" "/Applications/${APP_NAME}.app"

# Clear quarantine flag
xattr -dr com.apple.quarantine "/Applications/${APP_NAME}.app" 2>/dev/null || true

echo -e "  ${GREEN}✓${NC} Installed to /Applications/${APP_NAME}.app"

# --- Step 6: Launch -----------------------------------------------------------
echo -e "  ${BLUE}→${NC} Launching SubVault..."
open "/Applications/${APP_NAME}.app"

# --- Done --------------------------------------------------------------------
echo ""
echo -e "  ${GREEN}${BOLD}✓ SubVault v${LATEST_VERSION} installed successfully!${NC}"
echo ""
echo -e "  ${BOLD}What happens next:${NC}"
echo -e "    1. SubVault will open and guide you through setup"
echo -e "    2. Sign in with Apple or Google"
echo -e "    3. Connect your documents (Google Drive, iCloud, etc.)"
echo -e "    4. SubVault configures Claude Desktop / Cursor automatically"
echo ""
echo -e "  ${BOLD}Quick start:${NC}"
echo -e "    Open Claude Desktop and type: ${BLUE}/remember${NC}"
echo ""
echo -e "  Need help? → ${BOLD}https://subvault.ai/docs${NC}"
echo ""
