#!/usr/bin/env bash
# South Star Daemon Installer
# Usage: curl -sSL https://southstar.app/install | bash -s YOUR_API_KEY [SERVICE_NAME] [ENVIRONMENT] [API_URL]
set -e

API_KEY="${1:-}"
SERVICE_NAME="${2:-server}"
ENVIRONMENT="${3:-production}"
API_URL="${4:-https://fortunate-upliftment-production-885d.up.railway.app/api/v1/ingest}"
INSTALL_DIR="/opt/southstar"
CONFIG_DIR="/etc/southstar"
DAEMON_VERSION="0.1.0"

RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; NC='\033[0m'

log()   { echo -e "${GREEN}[southstar]${NC} $1"; }
warn()  { echo -e "${YELLOW}[southstar]${NC} $1"; }
error() { echo -e "${RED}[southstar]${NC} $1"; exit 1; }

# --- Input validation ---
[ -z "$API_KEY" ] && error "API key required. Usage: curl -sSL https://southstar.app/install | bash -s YOUR_API_KEY"

# API key format: alphanumeric + hyphens + underscores only
if ! echo "$API_KEY" | grep -qE '^[A-Za-z0-9_-]+$'; then
    error "Invalid API key format. Keys must be alphanumeric (with hyphens/underscores)."
fi

# Service name: alphanumeric + hyphens + underscores, max 64 chars
if ! echo "$SERVICE_NAME" | grep -qE '^[A-Za-z0-9_-]{1,64}$'; then
    error "Invalid service name. Use 1-64 alphanumeric characters, hyphens, or underscores."
fi

# Environment: common values only
case "$ENVIRONMENT" in
    production|staging|development|testing|local) ;;
    *) error "Invalid environment '$ENVIRONMENT'. Use: production, staging, development, testing, or local." ;;
esac

# API URL: must be HTTPS
case "$API_URL" in
    https://*) ;;
    *) error "API URL must use HTTPS. Got: $API_URL" ;;
esac

# Detect OS
OS="unknown"
if [ -f /etc/os-release ]; then
    . /etc/os-release
    OS="${ID}"
elif [ "$(uname)" = "Darwin" ]; then
    OS="macos"
fi
log "Detected OS: $OS"

# Check Python 3.8+
PYTHON=""
for cmd in python3 python; do
    if command -v "$cmd" &>/dev/null; then
        VER=$("$cmd" -c "import sys; print(sys.version_info >= (3, 8))" 2>/dev/null)
        if [ "$VER" = "True" ]; then PYTHON="$cmd"; break; fi
    fi
done
[ -z "$PYTHON" ] && error "Python 3.8+ required. Please install Python first."
log "Using Python: $($PYTHON --version)"

# Create install dir and virtualenv
log "Installing to $INSTALL_DIR ..."
mkdir -p "$INSTALL_DIR" "$CONFIG_DIR"
"$PYTHON" -m venv "$INSTALL_DIR/venv"

# Install daemon from PyPI
log "Downloading southstar-daemon==${DAEMON_VERSION} from PyPI ..."
"$INSTALL_DIR/venv/bin/pip" install --quiet --upgrade "southstar-daemon==${DAEMON_VERSION}"
DAEMON_BIN="$INSTALL_DIR/venv/bin/southstar-daemon"

# Write config using Python to produce safe JSON (no shell interpolation issues)
"$INSTALL_DIR/venv/bin/python" -c "
import json, sys
config = {
    'api_key': sys.argv[1],
    'service_name': sys.argv[2],
    'environment': sys.argv[3],
    'api_url': sys.argv[4],
}
with open(sys.argv[5], 'w') as f:
    json.dump(config, f, indent=2)
" "$API_KEY" "$SERVICE_NAME" "$ENVIRONMENT" "$API_URL" "$CONFIG_DIR/config.json"

chmod 600 "$CONFIG_DIR/config.json"
log "Config written to $CONFIG_DIR/config.json"

# Register as background service
if [ "$OS" = "macos" ]; then
    PLIST="/Library/LaunchDaemons/app.southstar.daemon.plist"
    cat > "$PLIST" <<EOF
<?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>app.southstar.daemon</string>
    <key>ProgramArguments</key>
    <array>
        <string>$DAEMON_BIN</string>
    </array>
    <key>RunAtLoad</key><true/>
    <key>KeepAlive</key><true/>
    <key>StandardOutPath</key><string>/var/log/southstar.log</string>
    <key>StandardErrorPath</key><string>/var/log/southstar.log</string>
</dict>
</plist>
EOF
    launchctl load "$PLIST"
    log "Registered as launchd service."
else
    # Linux — systemd
    cat > /etc/systemd/system/southstar.service <<EOF
[Unit]
Description=South Star Monitoring Daemon
After=network.target

[Service]
Type=simple
ExecStart=$DAEMON_BIN
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
EOF
    systemctl daemon-reload
    systemctl enable southstar
    systemctl start southstar
    log "Registered as systemd service."
fi

log "South Star daemon installed and started successfully."
log "Service: $SERVICE_NAME | Environment: $ENVIRONMENT"
log "Dashboard should show 'Connected' within 30 seconds."
