#!/bin/bash
# FIXXR installer — fixxr.org/install.sh
# Sets up Maxx and the FIXXR platform on your Mac.
# Usage: curl -sSL https://fixxr.org/install.sh | bash

set -e

FIXXR_DIR="$HOME/.fixxr"
REPO="https://github.com/fixxr-org/fixxr.git"
MIN_PYTHON="3.11"

# ── Colour helpers ────────────────────────────────────────────────────────────
bold=$'\033[1m'
gold=$'\033[33m'
green=$'\033[32m'
red=$'\033[31m'
reset=$'\033[0m'

info()    { echo "  ${gold}→${reset} $*"; }
success() { echo "  ${green}✓${reset} $*"; }
error()   { echo "  ${red}✗${reset} $*" >&2; }
section() { echo ""; echo "${bold}$*${reset}"; }

# ── Welcome ───────────────────────────────────────────────────────────────────
echo ""
echo "${bold}${gold}  maxx fixxr${reset} — your software, tended."
echo "  Installing on $(sw_vers -productVersion) ($(uname -m))"
echo ""

# ── macOS version check ───────────────────────────────────────────────────────
MACOS_MAJOR=$(sw_vers -productVersion | cut -d. -f1)
if [ "$MACOS_MAJOR" -lt 13 ]; then
    error "FIXXR requires macOS 13 Ventura or later."
    error "Your version: $(sw_vers -productVersion)"
    exit 1
fi

# ── Homebrew ──────────────────────────────────────────────────────────────────
section "Step 1 of 4 — Homebrew"
if command -v brew &>/dev/null; then
    success "Homebrew already installed ($(brew --version | head -1))"
else
    info "Installing Homebrew..."
    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
    # Add Homebrew to PATH for Apple Silicon
    if [ -f /opt/homebrew/bin/brew ]; then
        eval "$(/opt/homebrew/bin/brew shellenv)"
    fi
    success "Homebrew installed"
fi

# Ensure brew is on PATH for the rest of this script
if [ -f /opt/homebrew/bin/brew ]; then
    eval "$(/opt/homebrew/bin/brew shellenv)"
elif [ -f /usr/local/bin/brew ]; then
    eval "$(/usr/local/bin/brew shellenv)"
fi

# ── Python ────────────────────────────────────────────────────────────────────
section "Step 2 of 4 — Python"
PYTHON=""
for candidate in python3.13 python3.12 python3.11 python3; do
    if command -v "$candidate" &>/dev/null; then
        VER=$("$candidate" -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')" 2>/dev/null)
        MAJOR=$(echo "$VER" | cut -d. -f1)
        MINOR=$(echo "$VER" | cut -d. -f2)
        if [ "$MAJOR" -ge 3 ] && [ "$MINOR" -ge 11 ]; then
            PYTHON="$candidate"
            break
        fi
    fi
done

if [ -z "$PYTHON" ]; then
    info "Installing Python 3.12 via Homebrew..."
    brew install python@3.12
    PYTHON="$(brew --prefix)/bin/python3.12"
    success "Python installed"
else
    success "Python found: $PYTHON ($VER)"
fi

# ── Dolt ──────────────────────────────────────────────────────────────────────
section "Step 3 of 4 — Dolt (version-controlled database)"
if command -v dolt &>/dev/null; then
    success "Dolt already installed ($(dolt version | head -1))"
else
    info "Installing Dolt..."
    brew install dolt
    success "Dolt installed"
fi

# ── FIXXR ─────────────────────────────────────────────────────────────────────
section "Step 4 of 4 — FIXXR platform"
mkdir -p "$FIXXR_DIR"

if [ -d "$FIXXR_DIR/.git" ]; then
    info "Updating existing installation..."
    git -C "$FIXXR_DIR" pull --quiet origin main
    success "Updated to latest"
else
    info "Cloning FIXXR repository..."
    git clone --quiet "$REPO" "$FIXXR_DIR"
    success "Cloned to $FIXXR_DIR"
fi

# Initialise Dolt database if first install
if [ ! -d "$FIXXR_DIR/.dolt" ]; then
    info "Initialising local database..."
    (cd "$FIXXR_DIR" && dolt init --quiet 2>/dev/null || true)

    # Apply schema migrations
    for sql in migrate_phase1.sql migrate_phase2_provenance.sql \
               migrate_phase3_transparency.sql migrate_phase3_community.sql \
               migrate_phase4_probe.sql migrate_phase5_safety_cve.sql; do
        SQL_FILE="$FIXXR_DIR/$sql"
        if [ -f "$SQL_FILE" ]; then
            while IFS= read -r line; do
                [[ "$line" =~ ^--.*$ ]] && continue
                [[ -z "$line" ]] && continue
                dolt --data-dir="$FIXXR_DIR" sql -q "$line" 2>/dev/null || true
            done < "$SQL_FILE"
        fi
    done
    success "Database initialised"
fi

# Create launcher alias
SHELL_RC="$HOME/.zshrc"
[ -n "$BASH_VERSION" ] && SHELL_RC="$HOME/.bashrc"

ALIAS_LINE="alias fixxr='$PYTHON $FIXXR_DIR/fixxr.py'"
if ! grep -q "alias fixxr=" "$SHELL_RC" 2>/dev/null; then
    echo "" >> "$SHELL_RC"
    echo "# FIXXR — your software, tended." >> "$SHELL_RC"
    echo "$ALIAS_LINE" >> "$SHELL_RC"
    info "Added 'fixxr' alias to $SHELL_RC"
fi

# ── Done ──────────────────────────────────────────────────────────────────────
echo ""
echo "${bold}${green}  Installation complete.${reset}"
echo ""
echo "  Restart your terminal or run:  ${gold}source $SHELL_RC${reset}"
echo ""
echo "  Then:"
echo "    ${bold}fixxr scan${reset}         discover updates across all mechanisms"
echo "    ${bold}fixxr list --risk${reset}  ranked by exposure score"
echo "    ${bold}fixxr setup${reset}        grant narrow sudo rights (one-time)"
echo "    ${bold}fixxr update${reset}       install updates with AI safety check"
echo "    ${bold}fixxr report${reset}       endpoint security posture"
echo ""
echo "  ${gold}maxx fixxr${reset} — your software, tended."
echo ""
