#!/bin/bash
set -euo pipefail

#####################################################################
# PL SMS Sync — Intel Mac Setup
# Double-click this file. It handles everything automatically.
#####################################################################

BASE_URL="https://pure.purelocations.com.au/pl-sms-sync"
APP_DIR="$HOME/Library/Application Support/PLSmsSync"
VENV_DIR="$APP_DIR/venv"
SCRIPT_PATH="$APP_DIR/pl_sms_sync.py"
CONFIG_PATH="$APP_DIR/config.json"
EXAMPLE_CONFIG="$APP_DIR/config.example.json"
ICON_PATH="$APP_DIR/PLSmsSync.icns"
APP_BUNDLE="/Applications/PL SMS Sync.app"
LAUNCH_AGENT="$HOME/Library/LaunchAgents/au.com.purelocations.smssync.plist"
PYTHON_PKG="/tmp/python-3.12.7-universal2.pkg"
PYTHON_BIN="/Library/Frameworks/Python.framework/Versions/3.12/bin/python3.12"

echo ""
echo "========================================="
echo "  PL SMS Sync — Setup for Intel Mac"
echo "========================================="
echo ""

# ── Step 1: Kill any existing instances ──
echo "[1/7] Cleaning up old instances..."
killall -9 "PL SMS Sync" 2>/dev/null || true
rm -f "$APP_DIR/.instance.lock" 2>/dev/null || true
sleep 1
echo "  Done."
echo ""

# ── Step 2: Install Python if needed ──
echo "[2/7] Checking Python..."
if [ -f "$PYTHON_BIN" ]; then
    echo "  Python 3.12 already installed: $($PYTHON_BIN --version)"
else
    echo "  Python 3.12 not found. Downloading installer..."
    curl -L -o "$PYTHON_PKG" "$BASE_URL/python-3.12.7-universal2.pkg" 2>&1 | tail -1
    echo "  Downloaded. Installing (you may be asked for your password)..."
    
    # Use osascript for admin install so user gets a native password prompt
    osascript -e "do shell script \"installer -pkg '$PYTHON_PKG' -target /\" with administrator privileges" 2>&1
    
    if [ -f "$PYTHON_BIN" ]; then
        echo "  Python installed: $($PYTHON_BIN --version)"
    else
        echo ""
        echo "  ERROR: Python installation failed."
        echo "  Try double-clicking the installer manually:"
        echo "  $PYTHON_PKG"
        echo ""
        echo "Press Enter to close..."
        read
        exit 1
    fi
fi
echo ""

# ── Step 3: Create app directory and download files ──
echo "[3/7] Downloading app files..."
mkdir -p "$APP_DIR"

curl -sL "$BASE_URL/pl_sms_sync.py" -o "$SCRIPT_PATH"
curl -sL "$BASE_URL/config.example.json" -o "$EXAMPLE_CONFIG"
curl -sL "$BASE_URL/PLSmsSync.icns" -o "$ICON_PATH"

if [ ! -f "$CONFIG_PATH" ]; then
    cp "$EXAMPLE_CONFIG" "$CONFIG_PATH"
fi

echo "  App files downloaded to: $APP_DIR"
echo ""

# ── Step 4: Create virtual environment and install dependencies ──
echo "[4/7] Setting up Python environment (this may take a minute)..."
if [ -d "$VENV_DIR" ]; then
    rm -rf "$VENV_DIR"
fi

"$PYTHON_BIN" -m venv "$VENV_DIR" 2>&1
"$VENV_DIR/bin/pip" install --quiet --upgrade pip 2>&1
"$VENV_DIR/bin/pip" install --quiet rumps certifi 2>&1

# Verify
"$VENV_DIR/bin/python3" -c "import rumps; from Foundation import NSUnarchiver; print('All dependencies OK')" 2>&1
echo "  Python environment ready."
echo ""

# ── Step 5: Create .app wrapper ──
echo "[5/7] Creating application..."

# Remove old PyInstaller app if it exists
if [ -d "$APP_BUNDLE" ]; then
    rm -rf "$APP_BUNDLE"
fi

# Build a native .app bundle with a shell script launcher
mkdir -p "$APP_BUNDLE/Contents/MacOS"
mkdir -p "$APP_BUNDLE/Contents/Resources"

# Copy icon
if [ -f "$ICON_PATH" ]; then
    cp "$ICON_PATH" "$APP_BUNDLE/Contents/Resources/PLSmsSync.icns"
fi

# 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>PL SMS Sync</string>
    <key>CFBundleDisplayName</key>
    <string>PL SMS Sync</string>
    <key>CFBundleIdentifier</key>
    <string>au.com.purelocations.smssync</string>
    <key>CFBundleVersion</key>
    <string>1.2.0</string>
    <key>CFBundleShortVersionString</key>
    <string>1.2.0</string>
    <key>CFBundleExecutable</key>
    <string>PL SMS Sync</string>
    <key>CFBundleIconFile</key>
    <string>PLSmsSync</string>
    <key>LSUIElement</key>
    <true/>
    <key>NSHighResolutionCapable</key>
    <true/>
    <key>NSAppleEventsUsageDescription</key>
    <string>PL SMS Sync needs to send notifications.</string>
</dict>
</plist>
PLIST

# The launcher script — activates the venv and runs the app
cat > "$APP_BUNDLE/Contents/MacOS/PL SMS Sync" << LAUNCHER
#!/bin/bash
export PATH="$VENV_DIR/bin:\$PATH"
exec "$VENV_DIR/bin/python3" "$SCRIPT_PATH" "\$@"
LAUNCHER

chmod +x "$APP_BUNDLE/Contents/MacOS/PL SMS Sync"

echo "  Application created at: $APP_BUNDLE"
echo ""

# ── Step 6: Create LaunchAgent for auto-start ──
echo "[6/7] Setting up auto-start at login..."
mkdir -p "$HOME/Library/LaunchAgents"

cat > "$LAUNCH_AGENT" << 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>Label</key>
    <string>au.com.purelocations.smssync</string>
    <key>ProgramArguments</key>
    <array>
        <string>$VENV_DIR/bin/python3</string>
        <string>$SCRIPT_PATH</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <false/>
    <key>StandardOutPath</key>
    <string>$HOME/Library/Logs/pl-sms-sync-stdout.log</string>
    <key>StandardErrorPath</key>
    <string>$HOME/Library/Logs/pl-sms-sync-stderr.log</string>
</dict>
</plist>
PLIST

# Load the agent
launchctl unload "$LAUNCH_AGENT" 2>/dev/null || true
launchctl load "$LAUNCH_AGENT" 2>&1 || true
echo "  Auto-start configured."
echo ""

# ── Step 7: Launch the app ──
echo "[7/7] Launching PL SMS Sync..."
sleep 1
open "$APP_BUNDLE"
sleep 3

if pgrep -f "pl_sms_sync.py" > /dev/null 2>&1; then
    echo "  ✓ PL SMS Sync is running!"
    echo ""
    echo "========================================="
    echo "  Setup complete!"
    echo ""
    echo "  The 💬 icon should appear in your"
    echo "  menu bar (top-right of screen)."
    echo ""
    echo "  The app will start automatically"
    echo "  when you log in."
    echo "========================================="
else
    echo "  ⚠ App may still be starting..."
    echo "  Look for the 💬 icon in your menu bar."
    echo ""
    echo "  If nothing appears, check:"
    echo "  ~/Library/Logs/pl-sms-sync.log"
    echo "  ~/Library/Logs/pl-sms-sync-stderr.log"
fi

echo ""
echo "Press Enter to close this window..."
read
