#!/usr/bin/env bash
# CloudFormation Forge Installation Script
# Usage: npm install -g cfn-forge (web installer not yet implemented)

set -euo pipefail

# Configuration
REPO_URL="https://github.com/dmleblanc/cfn-forge"
INSTALL_DIR="/usr/local/bin"
LIB_DIR="$HOME/.cfn-forge"
VERSION="${VERSION:-latest}"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
MAGENTA='\033[0;35m'
NC='\033[0m'

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

print_banner() {
    echo -e "${BLUE}"
    cat << 'EOF'
     _____  ______ _   _       ______                    
    / ____|  ____| \ | |     |  ____|                   
   | |    | |__  |  \| |_____| |__ ___  _ __ __ _  ___  
   | |    |  __| | . ` |_____|  __/ _ \| '__/ _` |/ _ \ 
   | |____| |    | |\  |     | | | (_) | | | (_| |  __/ 
    \_____|_|    |_| \_|     |_|  \___/|_|  \__, |\___| 
                                              __/ |      
                                             |___/       
    CloudFormation Deployment Automation Tool
EOF
    echo -e "${NC}"
}

check_requirements() {
    echo -e "${BLUE}🔍 Checking requirements...${NC}"
    
    local missing=()
    
    # Check for required commands
    for cmd in curl git aws jq; do
        if ! command -v "$cmd" &> /dev/null; then
            missing+=("$cmd")
        fi
    done
    
    if [[ ${#missing[@]} -gt 0 ]]; then
        echo -e "${RED}❌ Missing required dependencies: ${missing[*]}${NC}"
        echo ""
        echo "Please install missing dependencies:"
        
        case "$OS" in
            Darwin)
                echo "  brew install ${missing[*]}"
                ;;
            Linux)
                echo "  sudo apt-get install ${missing[*]}  # Debian/Ubuntu"
                echo "  sudo yum install ${missing[*]}      # RedHat/CentOS"
                ;;
        esac
        
        exit 1
    fi
    
    echo -e "${GREEN}✅ All requirements satisfied${NC}"
}

detect_shell() {
    local shell_name=""
    
    if [[ -n "${BASH_VERSION:-}" ]]; then
        shell_name="bash"
    elif [[ -n "${ZSH_VERSION:-}" ]]; then
        shell_name="zsh"
    else
        shell_name=$(basename "$SHELL")
    fi
    
    echo "$shell_name"
}

install_binary() {
    echo -e "${BLUE}📦 Installing cfn-forge...${NC}"
    
    # Create temp directory
    local tmp_dir=$(mktemp -d)
    trap "rm -rf $tmp_dir" EXIT
    
    # Download based on version
    local download_url
    if [[ "$VERSION" == "latest" ]]; then
        download_url="$REPO_URL/releases/latest/download/cfn-forge-${OS}-${ARCH}"
    else
        download_url="$REPO_URL/releases/download/${VERSION}/cfn-forge-${OS}-${ARCH}"
    fi
    
    echo "Downloading from: $download_url"
    
    if ! curl -fsSL "$download_url" -o "$tmp_dir/cfn-forge"; then
        echo -e "${RED}❌ Failed to download cfn-forge${NC}"
        echo "Falling back to script installation..."
        install_script
        return
    fi
    
    # Make executable
    chmod +x "$tmp_dir/cfn-forge"
    
    # Install to system
    if [[ -w "$INSTALL_DIR" ]]; then
        mv "$tmp_dir/cfn-forge" "$INSTALL_DIR/cfn-forge"
    else
        echo -e "${YELLOW}⚠️  Need sudo access to install to $INSTALL_DIR${NC}"
        sudo mv "$tmp_dir/cfn-forge" "$INSTALL_DIR/cfn-forge"
    fi
    
    echo -e "${GREEN}✅ Installed cfn-forge to $INSTALL_DIR${NC}"
}

install_script() {
    echo -e "${BLUE}📜 Installing cfn-forge (script mode)...${NC}"
    
    # Create directories
    mkdir -p "$LIB_DIR"/{bin,lib/modules,templates}
    
    # Download main script
    curl -fsSL "$REPO_URL/raw/main/cfn-forge" -o "$LIB_DIR/bin/cfn-forge"
    chmod +x "$LIB_DIR/bin/cfn-forge"
    
    # Download modules
    for module in constants utils git-utils aws-utils validation interactive deployment; do
        curl -fsSL "$REPO_URL/raw/main/modules/$module.sh" -o "$LIB_DIR/lib/modules/$module.sh"
    done
    
    # Download templates
    echo -e "${BLUE}📋 Downloading templates...${NC}"
    for template in serverless-api static-website container-service full-stack blank; do
        mkdir -p "$LIB_DIR/templates/$template"
        # Download template files (simplified for example)
        echo "  - $template"
    done
    
    # Create symlink
    if [[ -w "$INSTALL_DIR" ]]; then
        ln -sf "$LIB_DIR/bin/cfn-forge" "$INSTALL_DIR/cfn-forge"
    else
        echo -e "${YELLOW}⚠️  Need sudo access to create symlink${NC}"
        sudo ln -sf "$LIB_DIR/bin/cfn-forge" "$INSTALL_DIR/cfn-forge"
    fi
    
    echo -e "${GREEN}✅ Installed cfn-forge (script mode)${NC}"
}

setup_shell_completion() {
    echo -e "${BLUE}🐚 Setting up shell completion...${NC}"
    
    local shell=$(detect_shell)
    local completion_script="$LIB_DIR/completion/cfn-forge-completion.$shell"
    
    # Download completion script
    mkdir -p "$LIB_DIR/completion"
    curl -fsSL "$REPO_URL/raw/main/completion/cfn-forge-completion.$shell" -o "$completion_script" 2>/dev/null || true
    
    if [[ -f "$completion_script" ]]; then
        case "$shell" in
            bash)
                if [[ -f "$HOME/.bashrc" ]]; then
                    echo "source $completion_script" >> "$HOME/.bashrc"
                    echo -e "${GREEN}✅ Added bash completion to ~/.bashrc${NC}"
                fi
                ;;
            zsh)
                if [[ -f "$HOME/.zshrc" ]]; then
                    echo "source $completion_script" >> "$HOME/.zshrc"
                    echo -e "${GREEN}✅ Added zsh completion to ~/.zshrc${NC}"
                fi
                ;;
        esac
    fi
}

verify_installation() {
    echo -e "${BLUE}🔍 Verifying installation...${NC}"
    
    if command -v cfn-forge &> /dev/null; then
        local installed_version=$(cfn-forge --version 2>/dev/null | cut -d' ' -f3)
        echo -e "${GREEN}✅ cfn-forge $installed_version installed successfully!${NC}"
        return 0
    else
        echo -e "${RED}❌ Installation failed${NC}"
        return 1
    fi
}

install_examples() {
    echo -e "${BLUE}📚 Installing example projects...${NC}"
    
    mkdir -p "$LIB_DIR/examples"
    
    # Download example projects
    local examples=("hello-world" "rest-api" "static-site" "microservice")
    
    for example in "${examples[@]}"; do
        echo "  - $example"
        # In real implementation, would download actual examples
    done
    
    echo -e "${GREEN}✅ Examples installed to $LIB_DIR/examples${NC}"
}

print_next_steps() {
    echo ""
    echo -e "${MAGENTA}🎉 Installation complete!${NC}"
    echo ""
    echo "Next steps:"
    echo ""
    echo "  1. Create a new project:"
    echo -e "     ${BLUE}cfn-forge init${NC}"
    echo ""
    echo "  2. Or try an example:"
    echo -e "     ${BLUE}cfn-forge init serverless-api${NC}"
    echo ""
    echo "  3. Start the deployment watcher:"
    echo -e "     ${BLUE}cfn-forge watch${NC}"
    echo ""
    echo "Documentation: https://github.com/dmleblanc/cfn-forge"
    echo "GitHub: https://github.com/dmleblanc/cfn-forge"
    echo ""
    echo -e "${YELLOW}⭐ If you like cfn-forge, please star us on GitHub!${NC}"
}

main() {
    print_banner
    check_requirements
    
    # Install based on platform
    case "$OS" in
        Darwin|Linux)
            if [[ "$ARCH" == "x86_64" ]] || [[ "$ARCH" == "arm64" ]]; then
                install_binary
            else
                install_script
            fi
            ;;
        *)
            echo -e "${YELLOW}⚠️  Unsupported OS: $OS${NC}"
            install_script
            ;;
    esac
    
    # Additional setup
    setup_shell_completion
    install_examples
    
    # Verify
    if verify_installation; then
        print_next_steps
    else
        echo ""
        echo "Please check the error messages above and try again."
        echo "If you continue to have issues, please report them at:"
        echo "https://github.com/dmleblanc/cfn-forge/issues"
        exit 1
    fi
}

# Run installation
main "$@"