#!/usr/bin/env bash
# Station One-Liner Install Script
# Usage: curl -sSL https://get-station.dev | bash
# Alternative: curl -sSL https://raw.githubusercontent.com/your-org/station/main/install | bash

set -euo pipefail

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
MAGENTA='\033[0;35m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m' # No Color

# Configuration
REPO="cloudshipai/station"
BINARY_NAME="stn"
INSTALL_DIR="${INSTALL_DIR:-$HOME/.local/bin}"
CONFIG_DIR="$HOME/.config/station"

# Platform detection
OS="$(uname -s)"
ARCH="$(uname -m)"

case "$OS" in
    Linux*)     PLATFORM="linux";;
    Darwin*)    PLATFORM="darwin";;
    CYGWIN*)    PLATFORM="windows";;
    MINGW*)     PLATFORM="windows";;
    *)          echo -e "${RED}❌ Unsupported operating system: $OS${NC}"; exit 1;;
esac

case "$ARCH" in
    x86_64)     ARCH="amd64";;
    aarch64)    ARCH="arm64";;
    arm64)      ARCH="arm64";;
    armv7l)     ARCH="armv7";;
    *)          echo -e "${RED}❌ Unsupported architecture: $ARCH${NC}"; exit 1;;
esac

# Helper functions
log() {
    echo -e "${BLUE}ℹ️  $1${NC}"
}

success() {
    echo -e "${GREEN}✅ $1${NC}"
}

warn() {
    echo -e "${YELLOW}⚠️  $1${NC}"
}

error() {
    echo -e "${RED}❌ $1${NC}" >&2
    exit 1
}

print_banner() {
    echo -e "${MAGENTA}${BOLD}"
    echo "   _____ __        __  _            "
    echo "  / ___// /_____ _/ /_(_)___  ____  "
    echo "  \\__ \\/ __/ __ \`/ __/ / __ \\/ __ \\ "
    echo " ___/ / /_/ /_/ / /_/ / /_/ / / / / "
    echo "/____/\\__/\\__,_/\\__/_/\\____/_/ /_/  "
    echo "                                   "
    echo -e "${NC}${CYAN}🚂 Station - Secure AI Background Agents ${NC}"
    echo -e "${CYAN}   Making MCP servers as easy as 'npm install'${NC}"
    echo
}

# Check dependencies
check_dependencies() {
    log "Checking dependencies..."
    
    if ! command -v curl >/dev/null 2>&1; then
        error "curl is required but not installed."
    fi
    
    if ! command -v tar >/dev/null 2>&1; then
        error "tar is required but not installed."
    fi
    
    success "Dependencies check passed"
}

# Get latest release version
get_latest_version() {
    log "Fetching latest release version..."
    
    local version
    version=$(curl -s "https://api.github.com/repos/$REPO/releases/latest" | \
              grep '"tag_name":' | \
              sed -E 's/.*"tag_name": "([^"]+)".*/\1/')
    
    if [[ -z "$version" ]]; then
        error "Failed to fetch latest version"
    fi
    
    echo "$version"
}

# Download and install binary
install_binary() {
    local version="$1"
    local filename="${BINARY_NAME}_${version#v}_${PLATFORM}_${ARCH}"
    
    if [[ "$PLATFORM" == "windows" ]]; then
        filename="${filename}.zip"
    else
        filename="${filename}.tar.gz"
    fi
    
    local download_url="https://github.com/$REPO/releases/download/$version/$filename"
    
    log "Downloading Station $version for $PLATFORM/$ARCH..."
    log "URL: $download_url"
    
    # Create install directory
    mkdir -p "$INSTALL_DIR"
    
    # Download to temporary directory
    local temp_dir
    temp_dir=$(mktemp -d)
    trap "rm -rf $temp_dir" EXIT
    
    if ! curl -sL "$download_url" -o "$temp_dir/$filename"; then
        error "Failed to download Station binary"
    fi
    
    # Extract binary
    log "Extracting binary..."
    cd "$temp_dir"
    
    if [[ "$PLATFORM" == "windows" ]]; then
        unzip -q "$filename"
    else
        tar -xzf "$filename"
    fi
    
    # Move binary to install directory
    if [[ -f "$BINARY_NAME" ]]; then
        mv "$BINARY_NAME" "$INSTALL_DIR/"
        chmod +x "$INSTALL_DIR/$BINARY_NAME"
    else
        error "Binary not found in archive"
    fi
    
    success "Station binary installed to $INSTALL_DIR/$BINARY_NAME"
}

# Update PATH in shell profiles
update_path() {
    local shell_profiles=(
        "$HOME/.bashrc"
        "$HOME/.zshrc"
        "$HOME/.profile"
        "$HOME/.bash_profile"
    )
    
    # Check if install directory is already in PATH
    if echo ":$PATH:" | grep -q ":$INSTALL_DIR:"; then
        success "Install directory already in PATH"
        return
    fi
    
    log "Adding $INSTALL_DIR to PATH..."
    
    # Add to existing shell profiles
    local updated_profiles=()
    for profile in "${shell_profiles[@]}"; do
        if [[ -f "$profile" ]] && ! grep -q "# Station PATH" "$profile"; then
            {
                echo ""
                echo "# Station PATH"
                echo "export PATH=\"$INSTALL_DIR:\$PATH\""
            } >> "$profile"
            updated_profiles+=("$(basename "$profile")")
        fi
    done
    
    if [[ ${#updated_profiles[@]} -gt 0 ]]; then
        success "Updated PATH in: ${updated_profiles[*]}"
        warn "Restart your shell or run: source ~/.bashrc (or appropriate profile)"
    else
        warn "No shell profiles found. Add $INSTALL_DIR to your PATH manually."
    fi
}

# Initialize Station configuration
init_station() {
    log "Initializing Station configuration..."
    
    # Create config directory
    mkdir -p "$CONFIG_DIR"
    
    # Initialize Station (this will create default config)
    if command -v "$INSTALL_DIR/$BINARY_NAME" >/dev/null 2>&1; then
        export PATH="$INSTALL_DIR:$PATH"
        if "$BINARY_NAME" init --quiet 2>/dev/null; then
            success "Station configuration initialized"
        else
            warn "Station initialization failed (this is normal for first-time setup)"
        fi
    else
        warn "Station binary not in PATH, skipping initialization"
    fi
}

# Offer to set up systemd service (Linux only)
setup_systemd_service() {
    if [[ "$PLATFORM" != "linux" ]] || [[ "$EUID" -eq 0 ]]; then
        return
    fi
    
    echo
    read -p "$(echo -e "${CYAN}Would you like to set up Station as a systemd service? [y/N]${NC} ")" -r
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        return
    fi
    
    log "Setting up systemd service..."
    
    # Create systemd user service
    local service_dir="$HOME/.config/systemd/user"
    mkdir -p "$service_dir"
    
    cat > "$service_dir/station.service" << EOF
[Unit]
Description=Station AI Infrastructure Platform
After=network.target

[Service]
Type=exec
ExecStart=$INSTALL_DIR/$BINARY_NAME serve --config $CONFIG_DIR/config.yaml
Restart=always
RestartSec=10
Environment=HOME=$HOME
WorkingDirectory=$HOME

[Install]
WantedBy=default.target
EOF
    
    # Reload systemd and optionally enable/start service
    systemctl --user daemon-reload
    
    read -p "$(echo -e "${CYAN}Enable Station to start automatically on login? [y/N]${NC} ")" -r
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        systemctl --user enable station.service
        success "Station service enabled (will start on next login)"
        
        read -p "$(echo -e "${CYAN}Start Station service now? [y/N]${NC} ")" -r
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            systemctl --user start station.service
            success "Station service started"
            log "Check status with: systemctl --user status station"
        fi
    fi
}

# Offer to set up launchd service (macOS only)
setup_launchd_service() {
    if [[ "$PLATFORM" != "darwin" ]]; then
        return
    fi
    
    echo
    read -p "$(echo -e "${CYAN}Would you like to set up Station as a launchd service? [y/N]${NC} ")" -r
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        return
    fi
    
    log "Setting up launchd service..."
    
    local plist_dir="$HOME/Library/LaunchAgents"
    mkdir -p "$plist_dir"
    
    cat > "$plist_dir/dev.station.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>dev.station</string>
    <key>ProgramArguments</key>
    <array>
        <string>$INSTALL_DIR/$BINARY_NAME</string>
        <string>serve</string>
        <string>--config</string>
        <string>$CONFIG_DIR/config.yaml</string>
    </array>
    <key>KeepAlive</key>
    <true/>
    <key>RunAtLoad</key>
    <true/>
    <key>WorkingDirectory</key>
    <string>$HOME</string>
    <key>StandardOutPath</key>
    <string>$HOME/Library/Logs/station.log</string>
    <key>StandardErrorPath</key>
    <string>$HOME/Library/Logs/station-error.log</string>
</dict>
</plist>
EOF
    
    read -p "$(echo -e "${CYAN}Load Station service now? [y/N]${NC} ")" -r
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        launchctl load "$plist_dir/dev.station.plist"
        success "Station service loaded"
        log "Check status with: launchctl list | grep station"
    fi
}

# Print next steps
print_next_steps() {
    echo
    echo -e "${BOLD}${GREEN}🎉 Station installation completed!${NC}"
    echo
    echo -e "${CYAN}Next steps:${NC}"
    echo -e "  1. Restart your shell or run: ${BOLD}source ~/.bashrc${NC}"
    echo -e "  2. Verify installation: ${BOLD}stn --version${NC}"
    echo -e "  3. Initialize Station: ${BOLD}stn init${NC}"
    echo -e "  4. Discover MCP servers: ${BOLD}stn load https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem${NC}"
    echo -e "  5. Access admin interface: ${BOLD}ssh admin@localhost -p 2222${NC}"
    echo
    echo -e "${CYAN}Documentation:${NC}"
    echo -e "  • README: ${BOLD}https://github.com/$REPO#readme${NC}"
    echo -e "  • Contributing: ${BOLD}https://github.com/$REPO/blob/main/CONTRIBUTING.md${NC}"
    echo
    echo -e "${CYAN}Support:${NC}"
    echo -e "  • Issues: ${BOLD}https://github.com/$REPO/issues${NC}"
    echo -e "  • Discussions: ${BOLD}https://github.com/$REPO/discussions${NC}"
    echo
}

# Main installation flow
main() {
    print_banner
    
    # Parse command line arguments
    local skip_init=false
    local skip_service=false
    
    while [[ $# -gt 0 ]]; do
        case $1 in
            --skip-init)
                skip_init=true
                shift
                ;;
            --skip-service)
                skip_service=true
                shift
                ;;
            --install-dir)
                INSTALL_DIR="$2"
                shift 2
                ;;
            -h|--help)
                echo "Station Install Script"
                echo
                echo "Options:"
                echo "  --skip-init       Skip Station initialization"
                echo "  --skip-service    Skip service setup"
                echo "  --install-dir     Custom installation directory (default: $HOME/.local/bin)"
                echo "  -h, --help        Show this help"
                exit 0
                ;;
            *)
                error "Unknown option: $1"
                ;;
        esac
    done
    
    # Installation steps
    check_dependencies
    
    local version
    version=$(get_latest_version)
    log "Latest version: $version"
    
    install_binary "$version"
    update_path
    
    if [[ "$skip_init" != true ]]; then
        init_station
    fi
    
    if [[ "$skip_service" != true ]]; then
        setup_systemd_service
        setup_launchd_service
    fi
    
    print_next_steps
}

# Run main function with all arguments
main "$@"