#!/bin/bash

# Claude Code Notifications Installer
# https://github.com/dongzhenye/claude-code-notifications

set -e

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

# Configuration
REPO_URL="https://raw.githubusercontent.com/dongzhenye/claude-code-notifications/main"
CLAUDE_DIR="$HOME/.claude"
SETTINGS_FILE="$CLAUDE_DIR/settings.json"
BACKUP_SUFFIX=".backup.$(date +%Y%m%d_%H%M%S)"

# Detect execution mode (local vs remote)
IS_REMOTE=false
SCRIPT_DIR=""

# Check if script is being piped from curl/wget
if [ -z "${BASH_SOURCE[0]}" ] || [ ! -f "${BASH_SOURCE[0]}" ]; then
    IS_REMOTE=true
else
    SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
    # Additional check: verify local files exist
    if [ ! -d "$SCRIPT_DIR/recommended" ]; then
        IS_REMOTE=true
    fi
fi

# Default values
TIER=""
SKIP_CONFIRM=false
NO_BACKUP=false
PLATFORM=""

# Detect platform
detect_platform() {
    if [[ "$OSTYPE" == "darwin"* ]]; then
        PLATFORM="macos"
    elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
        PLATFORM="linux"
    elif [[ "$OSTYPE" == "msys" ]] || [[ "$OSTYPE" == "cygwin" ]]; then
        PLATFORM="windows"
    else
        echo -e "${YELLOW}⚠ Unknown platform: $OSTYPE${NC}"
        PLATFORM="unknown"
    fi
}

# Print banner
print_banner() {
    echo
    echo "╭─────────────────────────────────────────╮"
    echo "│   Claude Code Notifications Installer   │"
    echo "│        Never miss a response!           │"
    echo "╰─────────────────────────────────────────╯"
    echo
}

# Print usage
print_usage() {
    echo "Usage: $0 [OPTIONS]"
    echo
    echo "Options:"
    echo "  -t, --tier <tier>    Specify tier: minimal, recommended, custom"
    echo "  -y, --yes            Skip confirmation prompts"
    echo "  --no-backup          Don't backup existing configuration"
    echo "  -h, --help           Show this help message"
    echo
    echo "Examples:"
    echo "  $0                   # Interactive installation"
    echo "  $0 -t recommended -y # Quick recommended setup"
    echo "  $0 -t minimal        # Install minimal tier"
}

# Parse arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        -t|--tier)
            TIER="$2"
            shift 2
            ;;
        -y|--yes)
            SKIP_CONFIRM=true
            shift
            ;;
        --no-backup)
            NO_BACKUP=true
            shift
            ;;
        -h|--help)
            print_banner
            print_usage
            exit 0
            ;;
        *)
            echo -e "${RED}Unknown option: $1${NC}"
            print_usage
            exit 1
            ;;
    esac
done

# Check environment
check_environment() {
    echo "Detecting environment..."
    
    # Detect platform
    detect_platform
    echo -e "✓ Platform: ${GREEN}$PLATFORM${NC}"
    
    # Check Claude Code
    if command -v claude &> /dev/null; then
        echo -e "✓ Claude Code: ${GREEN}Found${NC}"
    else
        echo -e "${YELLOW}⚠ Claude Code: Not found in PATH${NC}"
        echo "  Please install Claude Code first:"
        echo "  https://docs.anthropic.com/claude-code/install"
    fi
    
    # Check existing config
    if [[ -f "$SETTINGS_FILE" ]]; then
        echo -e "${YELLOW}⚠ Existing config: $SETTINGS_FILE${NC}"
    else
        echo -e "✓ Config: ${GREEN}No existing configuration${NC}"
    fi
    
    echo
}

# Check if we can interact with user
can_interact() {
    if [ "$IS_REMOTE" = true ]; then
        # For remote execution, check if /dev/tty is available for input
        # Don't check tty command as it may return "not a tty" even when interaction is possible
        if [ -c /dev/tty ] 2>/dev/null; then
            return 0
        else
            return 1
        fi
    else
        # For local execution, check if stdin is a terminal
        if [ -t 0 ]; then
            return 0
        else
            return 1
        fi
    fi
}

# Read user input safely
safe_read() {
    local prompt="$1"
    local var_name="$2"
    local default_value="$3"
    local input_value=""
    
    # Temporarily disable set -e for read command
    set +e
    if [ "$IS_REMOTE" = true ] && [ -c /dev/tty ]; then
        read -r -p "$prompt" input_value < /dev/tty
    else
        read -r -p "$prompt" input_value
    fi
    local read_status=$?
    set -e
    
    # Handle read failure (EOF, timeout, etc.)
    if [ $read_status -ne 0 ]; then
        eval "$var_name='$default_value'"
        return 0
    fi
    
    # Use default if empty
    if [ -z "$input_value" ]; then
        eval "$var_name='$default_value'"
    else
        eval "$var_name='$input_value'"
    fi
}

# Interactive tier selection
select_tier_interactive() {
    # If tier already specified via CLI, skip selection
    if [ -n "$TIER" ]; then
        return
    fi
    
    # Check if we can interact
    if ! can_interact; then
        echo
        echo "═══════════════════════════════════════════════════════════"
        echo "Running in non-interactive mode (no terminal available)"
        echo "═══════════════════════════════════════════════════════════"
        echo
        echo "Using default: Recommended tier ⭐"
        echo
        echo "To choose a different tier, run with --tier option:"
        echo "  curl ... | bash -s -- --tier minimal"
        echo "  curl ... | bash -s -- --tier recommended"
        echo "  curl ... | bash -s -- --tier custom"
        echo
        TIER="recommended"
        return
    fi
    
    echo "Notification style:"
    echo "1) Minimal     - Terminal bell"
    echo "2) Recommended - Sound alerts ⭐"
    echo "3) Custom      - Advanced options"
    echo "4) Exit"
    echo
    
    safe_read "Enter choice [2]: " choice "2"
    
    case $choice in
        1)
            TIER="minimal"
            ;;
        2)
            TIER="recommended"
            ;;
        3)
            TIER="custom"
            ;;
        4)
            echo "Installation cancelled"
            exit 0
            ;;
        *)
            echo -e "${RED}Invalid choice${NC}"
            select_tier_interactive
            ;;
    esac
}

# Handle backup
handle_backup() {
    if [[ -f "$SETTINGS_FILE" ]] && [[ "$NO_BACKUP" != true ]]; then
        local backup_file="${SETTINGS_FILE}${BACKUP_SUFFIX}"
        
        if [[ "$SKIP_CONFIRM" != true ]]; then
            echo "Found existing configuration:"
            echo "  $SETTINGS_FILE"
            echo
            echo "Options:"
            echo "1) Backup and proceed ✓"
            echo "2) Overwrite (no backup)"
            echo "3) Cancel"
            echo
            
            safe_read "Your choice [1]: " choice "1"
            choice=${choice:-1}
            
            case $choice in
                1)
                    cp "$SETTINGS_FILE" "$backup_file"
                    echo -e "${GREEN}✓ Backed up to: $backup_file${NC}"
                    ;;
                2)
                    echo -e "${YELLOW}⚠ Proceeding without backup${NC}"
                    ;;
                3)
                    echo "Installation cancelled"
                    exit 0
                    ;;
                *)
                    echo -e "${RED}Invalid choice${NC}"
                    handle_backup
                    ;;
            esac
        else
            cp "$SETTINGS_FILE" "$backup_file"
            echo -e "${GREEN}✓ Backed up to: $backup_file${NC}"
        fi
    fi
}

# Install minimal tier
install_minimal() {
    # Show what will be installed
    echo "Installing:"
    echo "  Terminal bell notifications"
    echo
    
    if [[ "$SKIP_CONFIRM" != true ]]; then
        safe_read "Continue? [Y/n]: " confirm "Y"
        if [[ ! "$confirm" =~ ^[Yy]([Ee][Ss])?$|^$ ]]; then
            echo "Installation cancelled"
            exit 0
        fi
    fi
    
    # Handle backup if config file exists
    if [[ -f "$SETTINGS_FILE" ]]; then
        local backup_file="${SETTINGS_FILE}${BACKUP_SUFFIX}"
        cp "$SETTINGS_FILE" "$backup_file"
        echo -e "${GREEN}✓ Backup created${NC}"
    fi
    
    # Try claude config command first, but verify it actually worked
    if claude config set --global preferredNotifChannel terminal_bell >/dev/null 2>&1 && \
       claude config get preferredNotifChannel >/dev/null 2>&1; then
        echo -e "${GREEN}✓ Bell configured${NC}"
    else
        # Fallback: write directly to settings.json
        mkdir -p "$(dirname "$SETTINGS_FILE")"
        cat > "$SETTINGS_FILE" << 'EOF'
{
  "preferredNotifChannel": "terminal_bell"
}
EOF
        echo -e "${GREEN}✓ Bell configured${NC}"
    fi
}

# Get configuration file (local or remote)
get_config_file() {
    local platform=$1
    local config_content=""
    
    if [ "$IS_REMOTE" = true ]; then
        # Download from GitHub
        local config_url="$REPO_URL/recommended/recommended.$platform.json"
        echo "  Downloading configuration from GitHub..."
        
        if command -v curl &> /dev/null; then
            config_content=$(curl -sSL "$config_url" 2>/dev/null)
        elif command -v wget &> /dev/null; then
            config_content=$(wget -qO- "$config_url" 2>/dev/null)
        else
            echo -e "${RED}Error: Neither curl nor wget found${NC}"
            exit 1
        fi
        
        if [ -z "$config_content" ]; then
            echo -e "${RED}Error: Failed to download configuration${NC}"
            exit 1
        fi
    else
        # Use local file
        local config_file="$SCRIPT_DIR/recommended/recommended.$platform.json"
        if [[ ! -f "$config_file" ]]; then
            echo -e "${RED}Error: Configuration file not found: $config_file${NC}"
            exit 1
        fi
        config_content=$(cat "$config_file")
    fi
    
    echo "$config_content"
}

# Install recommended tier
install_recommended() {
    # Show what will be installed
    echo "Installing:"
    echo "  Glass sound (input needed)"
    echo "  Tink sound (task complete)"
    echo
    
    if [[ "$SKIP_CONFIRM" != true ]]; then
        safe_read "Continue? [Y/n]: " confirm "Y"
        if [[ ! "$confirm" =~ ^[Yy]([Ee][Ss])?$|^$ ]]; then
            echo "Installation cancelled"
            exit 0
        fi
    fi
    
    # Handle backup if config file exists
    if [[ -f "$SETTINGS_FILE" ]]; then
        local backup_file="${SETTINGS_FILE}${BACKUP_SUFFIX}"
        cp "$SETTINGS_FILE" "$backup_file"
        echo -e "${GREEN}✓ Backup created${NC}"
    fi
    
    # Ensure .claude directory exists
    mkdir -p "$CLAUDE_DIR"
    
    # Get configuration content and install
    local config_content
    config_content=$(get_config_file "$PLATFORM")
    echo "$config_content" > "$SETTINGS_FILE"
    echo -e "${GREEN}✓ Sounds configured${NC}"
}

# Install custom tier
install_custom() {
    echo "Custom tier:"
    echo "1) Desktop notifications"
    echo "2) Manual setup"
    echo "3) Exit"
    echo
    
    safe_read "Your choice [1]: " choice "1"
    
    case $choice in
        1)
            if [[ "$PLATFORM" != "macos" ]]; then
                echo -e "${YELLOW}⚠ Desktop notifications are currently only available for macOS${NC}"
                echo "Please choose manual configuration for other platforms"
                install_custom
                return
            fi
            
            # Confirm desktop notifications choice
            echo "Installing:"
            echo "  ~/.claude/system-notify.macos.sh"
            if [[ -f "$SETTINGS_FILE" ]]; then
                echo "  Backup: settings.json"
            fi
            echo
            if [[ "$SKIP_CONFIRM" != true ]]; then
                safe_read "Continue? [Y/n]: " confirm "Y"
                if [[ ! "$confirm" =~ ^[Yy]([Ee][Ss])?$|^$ ]]; then
                    install_custom
                    return
                fi
            fi
            
            # Handle backup
            if [[ -f "$SETTINGS_FILE" ]]; then
                local backup_file="${SETTINGS_FILE}${BACKUP_SUFFIX}"
                cp "$SETTINGS_FILE" "$backup_file"
                echo -e "${GREEN}✓ Backup created${NC}"
            fi
            
            # Set feature type for summary
            CUSTOM_FEATURE="desktop"
            
            # Get or download notification script
            local notify_script="$CLAUDE_DIR/system-notify.macos.sh"
            
            if [ "$IS_REMOTE" = true ]; then
                # Download notification script
                echo "  Downloading notification script..."
                local script_url="$REPO_URL/custom/system-notify.macos.sh"
                
                if command -v curl &> /dev/null; then
                    curl -sSL "$script_url" -o "$notify_script"
                elif command -v wget &> /dev/null; then
                    wget -q "$script_url" -O "$notify_script"
                fi
                
                if [ ! -f "$notify_script" ]; then
                    echo -e "${RED}Error: Failed to download notification script${NC}"
                    exit 1
                fi
            else
                # Copy from local directory
                cp "$SCRIPT_DIR/custom/system-notify.macos.sh" "$notify_script"
            fi
            
            # Make script executable
            chmod +x "$notify_script"
            
            cat > "$SETTINGS_FILE" << EOF
{
  "hooks": {
    "Notification": [{
      "hooks": [{
        "type": "command",
        "command": "$notify_script notification"
      }]
    }],
    "Stop": [{
      "hooks": [{
        "type": "command",
        "command": "$notify_script stop"
      }]
    }]
  }
}
EOF
            echo -e "${GREEN}✓ Script installed${NC}"
            
            # Auto-test the notification system  
            if [[ -x "$notify_script" ]]; then
                "$notify_script" test >/dev/null 2>&1
                echo -e "${GREEN}✓ Test sent${NC}"
            fi
            
            # Check terminal-notifier (simplified)
            if ! command -v terminal-notifier &> /dev/null; then
                if [[ "$SKIP_CONFIRM" != true ]]; then
                    safe_read "Install terminal-notifier for reliable notifications? [Y/n]: " install_tn "Y"
                    
                    if [[ "$install_tn" =~ ^[Yy]([Ee][Ss])?$|^$ ]]; then
                        if command -v brew &> /dev/null; then
                            if brew install terminal-notifier >/dev/null 2>&1; then
                                echo -e "${GREEN}✓ Dependency installed${NC}"
                            fi
                        fi
                    fi
                fi
            fi
            ;;
        2)
            # Confirm manual configuration choice
            echo
            echo "Ready to show manual configuration guide:"
            echo "  • Feature: Manual configuration"  
            echo "  • You'll set up hooks yourself"
            echo "  • No automatic installation will occur"
            echo
            if [[ "$SKIP_CONFIRM" != true ]]; then
                safe_read "Continue? [Y/n]: " confirm "Y"
                if [[ ! "$confirm" =~ ^[Yy]([Ee][Ss])?$|^$ ]]; then
                    install_custom
                    return
                fi
            fi
            
            # Set feature type for summary
            CUSTOM_FEATURE="manual"
            
            echo
            echo "Manual configuration guide:"
            echo
            echo "1. Create or edit: ~/.claude/settings.json"
            echo "2. Available scripts:"
            if [ "$IS_REMOTE" = true ]; then
                echo "   • Download from: $REPO_URL/custom/system-notify.macos.sh"
            else
                echo "   • $SCRIPT_DIR/custom/system-notify.macos.sh"
            fi
            echo
            echo "Example configuration:"
            cat << 'EOF'
{
  "hooks": {
    "Notification": [{
      "hooks": [{
        "type": "command",
        "command": "/path/to/your/script notification"
      }]
    }]
  }
}
EOF
            echo
            echo "Documentation: https://github.com/dongzhenye/claude-code-notifications"
            ;;
        3)
            echo "Custom tier cancelled"
            exit 0
            ;;
        *)
            echo -e "${RED}Invalid choice${NC}"
            install_custom
            ;;
    esac
}

# Show installation summary
show_summary() {
    echo
    echo -e "${GREEN}✓ Complete${NC}"
}

# Main installation flow
main() {
    print_banner
    check_environment
    
    # Select tier if not provided
    if [[ -z "$TIER" ]]; then
        if [[ "$SKIP_CONFIRM" == true ]]; then
            TIER="recommended"
            echo "Using default tier: recommended"
        else
            select_tier_interactive
        fi
    fi
    
    # Validate tier
    if [[ "$TIER" != "minimal" ]] && [[ "$TIER" != "recommended" ]] && [[ "$TIER" != "custom" ]]; then
        echo -e "${RED}Error: Invalid tier '$TIER'${NC}"
        echo "Valid tiers: minimal, recommended, custom"
        exit 1
    fi
    
    # Individual tiers handle their own confirmation and backup now
    
    # Install based on tier
    case $TIER in
        minimal)
            install_minimal
            ;;
        recommended)
            install_recommended
            ;;
        custom)
            install_custom
            ;;
    esac
    
    # Show summary for all tiers
    show_summary
}

# Run main function
main