#!/usr/bin/env bash
# PAK.sh Wrapper Script
# This script provides a unified interface for PAK.sh regardless of installation method

set -euo pipefail

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

# PAK.sh configuration
PAK_VERSION="2.0.0"
PAK_DOMAIN="pak.sh"
PAK_INSTALL_URL="https://pak.sh/install"
PAK_LATEST_URL="https://pak.sh/latest.tar.gz"

# Installation paths to check (in order of preference)
PAK_PATHS=(
    "/usr/local/bin/pak"
    "/opt/pak/bin/pak"
    "$HOME/.local/bin/pak"
    "$HOME/.pak/bin/pak"
    "./pak/pak.sh"
    "./node_modules/.bin/pak"
    "./venv/bin/pak"
    "./.cargo/bin/pak"
)

# Function to find PAK.sh installation
find_pak_installation() {
    for path in "${PAK_PATHS[@]}"; do
        if [[ -f "$path" && -x "$path" ]]; then
            echo "$path"
            return 0
        fi
    done
    return 1
}

# Function to install PAK.sh
install_pak() {
    echo -e "${BLUE}🚀 Installing PAK.sh...${NC}"
    
    # Create installation directory
    local install_dir="$HOME/.pak"
    mkdir -p "$install_dir/bin"
    
    # Download and install
    echo -e "${BLUE}📥 Downloading PAK.sh...${NC}"
    local temp_dir=$(mktemp -d)
    cd "$temp_dir"
    
    if command -v curl >/dev/null 2>&1; then
        curl -L -o pak.tar.gz "$PAK_LATEST_URL"
    elif command -v wget >/dev/null 2>&1; then
        wget -O pak.tar.gz "$PAK_LATEST_URL"
    else
        echo -e "${RED}❌ Error: Neither curl nor wget found${NC}"
        exit 1
    fi
    
    # Extract and install
    echo -e "${BLUE}📦 Extracting PAK.sh...${NC}"
    tar -xzf pak.tar.gz
    
    # Find extracted directory
    local extracted_dir=""
    if [[ -d "pak.sh-main" ]]; then
        extracted_dir="pak.sh-main"
    elif [[ -d "pak.sh-*" ]]; then
        extracted_dir=$(ls -d pak.sh-* | head -1)
    else
        echo -e "${RED}❌ Error: Could not find extracted directory${NC}"
        exit 1
    fi
    
    cd "$extracted_dir"
    
    # Set permissions
    echo -e "${BLUE}🔐 Setting permissions...${NC}"
    find . -name "*.sh" -type f -exec chmod +x {} \;
    find . -name "*.py" -type f -exec chmod +x {} \;
    
    # Run installer
    if [[ -f "install/install.sh" ]]; then
        echo -e "${BLUE}🔧 Running installer...${NC}"
        INSTALL_DIR="$install_dir/bin" ./install/install.sh
    else
        # Manual installation
        echo -e "${BLUE}📁 Installing to $install_dir/bin...${NC}"
        cp -r pak "$install_dir/bin/"
        chmod +x "$install_dir/bin/pak"
    fi
    
    # Cleanup
    cd /
    rm -rf "$temp_dir"
    
    echo -e "${GREEN}✅ PAK.sh installed successfully!${NC}"
    echo -e "${CYAN}📁 Installation location: $install_dir/bin/pak${NC}"
    echo -e "${YELLOW}💡 Add to PATH: export PATH=\"$install_dir/bin:\$PATH\"${NC}"
}

# Function to show help
show_help() {
    cat << EOF
PAK.sh Wrapper Script v$PAK_VERSION

Usage: pak-sh [command] [options]

Commands:
  install                    Install PAK.sh locally
  run [command] [options]    Run PAK.sh command
  update                     Update PAK.sh installation
  status                     Check PAK.sh installation status
  help                       Show this help message

Examples:
  pak-sh install             # Install PAK.sh
  pak-sh run deploy          # Run: pak deploy
  pak-sh run init            # Run: pak init
  pak-sh status              # Check installation status

Installation Methods:
  1. Direct: curl -sSL https://pak.sh/install | bash
  2. Wrapper: pak-sh install
  3. Package Managers:
     - npm: npm install -g pak-sh
     - pip: pip install pak-sh
     - cargo: cargo install pak-sh
     - brew: brew install pak-sh

For more information, visit: https://pak.sh
EOF
}

# Function to check status
check_status() {
    echo -e "${BLUE}🔍 Checking PAK.sh installation status...${NC}"
    
    local pak_path=$(find_pak_installation)
    if [[ -n "$pak_path" ]]; then
        echo -e "${GREEN}✅ PAK.sh found at: $pak_path${NC}"
        
        # Get version
        if "$pak_path" version >/dev/null 2>&1; then
            local version=$("$pak_path" version 2>/dev/null | head -1)
            echo -e "${GREEN}📦 Version: $version${NC}"
        fi
        
        # Check if in PATH
        if command -v pak >/dev/null 2>&1; then
            echo -e "${GREEN}✅ 'pak' command available in PATH${NC}"
        else
            echo -e "${YELLOW}⚠️  'pak' command not in PATH${NC}"
            echo -e "${CYAN}💡 Add to PATH: export PATH=\"$(dirname "$pak_path"):\$PATH\"${NC}"
        fi
    else
        echo -e "${RED}❌ PAK.sh not found${NC}"
        echo -e "${YELLOW}💡 Run 'pak-sh install' to install PAK.sh${NC}"
        return 1
    fi
}

# Function to update PAK.sh
update_pak() {
    echo -e "${BLUE}🔄 Updating PAK.sh...${NC}"
    
    local pak_path=$(find_pak_installation)
    if [[ -z "$pak_path" ]]; then
        echo -e "${RED}❌ PAK.sh not found. Run 'pak-sh install' first.${NC}"
        exit 1
    fi
    
    # Backup current installation
    local backup_dir="$HOME/.pak/backup/$(date +%Y%m%d_%H%M%S)"
    mkdir -p "$backup_dir"
    cp -r "$(dirname "$pak_path")" "$backup_dir/"
    
    echo -e "${BLUE}💾 Backup created at: $backup_dir${NC}"
    
    # Reinstall
    install_pak
    
    echo -e "${GREEN}✅ PAK.sh updated successfully!${NC}"
}

# Main function
main() {
    local command="${1:-help}"
    
    case "$command" in
        install)
            install_pak
            ;;
        run)
            shift
            local pak_path=$(find_pak_installation)
            if [[ -z "$pak_path" ]]; then
                echo -e "${RED}❌ PAK.sh not found. Run 'pak-sh install' first.${NC}"
                exit 1
            fi
            exec "$pak_path" "$@"
            ;;
        status)
            check_status
            ;;
        update)
            update_pak
            ;;
        help|--help|-h)
            show_help
            ;;
        *)
            echo -e "${RED}❌ Unknown command: $command${NC}"
            echo -e "${YELLOW}💡 Run 'pak-sh help' for usage information${NC}"
            exit 1
            ;;
    esac
}

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