#!/usr/bin/env bash
# RIRD Desktop Agent - Mac Installer
# Usage: bash install-desktop-mac.sh

set -e

BOLD='\033[1m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
DIM='\033[2m'
RESET='\033[0m'

INSTALL_DIR="$HOME/.rird-agent"
APP_BUNDLE="$HOME/Applications/RIRD.app"
DOWNLOAD_URL="https://rird.ai/downloads/rird-agent/RIRD-Agent-Mac.zip"
VERSION="3.1.2"

print_step() { echo -e "${YELLOW}[$1/5]${RESET} $2"; }
print_ok()   { echo -e "      ${GREEN}done${RESET}"; }
print_err()  { echo -e "      ${RED}error: $1${RESET}"; exit 1; }

echo ""
echo -e "${BOLD}RIRD Desktop Agent v${VERSION} - Mac Installer${RESET}"
echo -e "${DIM}rird.ai${RESET}"
echo ""

# ---- Step 1: Python -------------------------------------------------------
print_step 1 "Checking Python 3.10+..."

PYTHON=""
for cmd in python3.12 python3.11 python3.10 python3; do
    if command -v "$cmd" &>/dev/null; then
        ver=$("$cmd" -c "import sys; print(sys.version_info[:2])" 2>/dev/null)
        if "$cmd" -c "import sys; assert sys.version_info >= (3,10)" 2>/dev/null; then
            PYTHON="$cmd"
            echo -e "      ${DIM}found: $("$cmd" --version)${RESET}"
            break
        fi
    fi
done

if [ -z "$PYTHON" ]; then
    echo -e "      ${DIM}not found - installing via Homebrew...${RESET}"
    if ! command -v brew &>/dev/null; then
        echo -e "      ${DIM}installing Homebrew...${RESET}"
        /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
        eval "$(/opt/homebrew/bin/brew shellenv 2>/dev/null || /usr/local/bin/brew shellenv)"
    fi
    brew install python@3.12 --quiet
    PYTHON=$(brew --prefix python@3.12)/bin/python3
    if ! command -v "$PYTHON" &>/dev/null; then
        PYTHON=$(command -v python3.12 || command -v python3)
    fi
fi

[ -z "$PYTHON" ] && print_err "Python 3.10+ required. Install from https://www.python.org/downloads/"
print_ok

# ---- Step 2: Download & extract ------------------------------------------
print_step 2 "Downloading..."

TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT

curl -fsSL --progress-bar "$DOWNLOAD_URL" -o "$TMP/rird.zip" 2>&1 | \
    grep -E "^[[:space:]]*[0-9]" || true

unzip -q "$TMP/rird.zip" -d "$TMP/extracted"

mkdir -p "$INSTALL_DIR"
EXTRACTED_CORE=$(find "$TMP/extracted" -name "core" -type d | head -1)
[ -z "$EXTRACTED_CORE" ] && print_err "Could not find core/ in downloaded archive."

rsync -a --delete "$EXTRACTED_CORE/" "$INSTALL_DIR/core/"
print_ok

# ---- Step 3: Python dependencies -----------------------------------------
print_step 3 "Installing Python dependencies..."

"$PYTHON" -m pip install --quiet --upgrade pip
"$PYTHON" -m pip install --quiet --upgrade playwright "pywebview>=4.0"
print_ok

# ---- Step 4: Chromium browser --------------------------------------------
print_step 4 "Installing Chromium (one-time download ~150MB)..."

"$PYTHON" -m playwright install chromium 2>/dev/null
print_ok

# ---- Step 5: App bundle + launcher ---------------------------------------
print_step 5 "Creating RIRD.app..."

# Remove old bundle
rm -rf "$APP_BUNDLE"
mkdir -p "$APP_BUNDLE/Contents/MacOS"
mkdir -p "$APP_BUNDLE/Contents/Resources"

# Copy icon if available
ICON_SRC="$INSTALL_DIR/core/favicon.png"
if [ -f "$ICON_SRC" ]; then
    cp "$ICON_SRC" "$APP_BUNDLE/Contents/Resources/icon.png"
fi

# Launcher script inside .app
cat > "$APP_BUNDLE/Contents/MacOS/RIRD" <<LAUNCHER
#!/usr/bin/env bash
cd "$INSTALL_DIR/core"
"$PYTHON" main.py
LAUNCHER
chmod +x "$APP_BUNDLE/Contents/MacOS/RIRD"

# Info.plist
cat > "$APP_BUNDLE/Contents/Info.plist" <<PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>CFBundleName</key><string>RIRD</string>
  <key>CFBundleDisplayName</key><string>RIRD</string>
  <key>CFBundleIdentifier</key><string>ai.rird.agent</string>
  <key>CFBundleExecutable</key><string>RIRD</string>
  <key>CFBundleVersion</key><string>${VERSION}</string>
  <key>CFBundleShortVersionString</key><string>${VERSION}</string>
  <key>CFBundleIconFile</key><string>icon</string>
  <key>LSMinimumSystemVersion</key><string>12.0</string>
  <key>LSUIElement</key><false/>
  <key>NSHighResolutionCapable</key><true/>
  <key>CFBundlePackageType</key><string>APPL</string>
</dict>
</plist>
PLIST

# Remove quarantine flag so macOS doesn't block it
xattr -cr "$APP_BUNDLE" 2>/dev/null || true

print_ok

echo ""
echo -e "${GREEN}${BOLD}Installation complete.${RESET}"
echo ""
echo -e "  App installed at:  ${DIM}~/Applications/RIRD.app${RESET}"
echo -e "  Data stored at:    ${DIM}~/.rird-agent/${RESET}"
echo ""
echo -e "  To uninstall:  rm -rf ~/Applications/RIRD.app ~/.rird-agent"
echo ""

# Launch
open "$APP_BUNDLE"
