#!/data/data/com.termux/files/usr/bin/bash

# terpi - Termux Python Package Management Tool
# Version: 0.2.0
# Default mirror: https://nsyhykui.github.io/python_wheels_for_termux/simple

VERSION="0.2.0"
DEFAULT_MIRROR="https://nsyhykui.github.io/python_wheels_for_termux/simple"
CONFIG_DIR="$HOME/.config/terpi"
CONFIG_FILE="$CONFIG_DIR/config"
BACKUP_MIRRORS=(
    "https://pypi.org/simple/"
    "https://mirrors.aliyun.com/pypi/simple/"
    "https://pypi.tuna.tsinghua.edu.cn/simple/"
    "https://mirrors.bfsu.edu.cn/pypi/web/simple/"
)

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

# Initialize configuration
init_config() {
    if [ ! -d "$CONFIG_DIR" ]; then
        mkdir -p "$CONFIG_DIR"
    fi
    
    if [ ! -f "$CONFIG_FILE" ]; then
        cat > "$CONFIG_FILE" << EOF
# terpi configuration file
# Default mirror source
primary_mirror=$DEFAULT_MIRROR
# Region setting (cn/global)
region=global
# Backup mirrors
backup_mirrors=${BACKUP_MIRRORS[@]}
# Timeout in seconds
timeout=30
EOF
    fi
}

# Read configuration
read_config() {
    if [ -f "$CONFIG_FILE" ]; then
        source "$CONFIG_FILE"
    else
        primary_mirror=$DEFAULT_MIRROR
        region="global"
        timeout=30
    fi
}

# Test mirror availability
test_mirror() {
    local mirror=$1
    echo -e "${BLUE}Testing mirror: $mirror${NC}"
    
    if curl --silent --connect-timeout $timeout "$mirror" > /dev/null; then
        echo -e "${GREEN}✓ Mirror available${NC}"
        return 0
    else
        echo -e "${RED}✗ Mirror unavailable${NC}"
        return 1
    fi
}

# Get best available mirror
get_best_mirror() {
    echo -e "${YELLOW}Detecting best mirror...${NC}"
    
    # Test default mirror first
    if test_mirror "$primary_mirror"; then
        echo "$primary_mirror"
        return 0
    fi
    
    # Test backup mirrors
    for mirror in "${BACKUP_MIRRORS[@]}"; do
        if test_mirror "$mirror"; then
            echo "$mirror"
            return 0
        fi
    done
    
    echo -e "${RED}Error: All mirrors are unavailable${NC}"
    return 1
}

# Install package
install_package() {
    local package=$1
    local mirror=$(get_best_mirror)
    
    if [ -z "$mirror" ]; then
        return 1
    fi
    
    echo -e "${GREEN}Using mirror: $mirror${NC}"
    echo -e "${BLUE}Installing package: $package${NC}"
    
    if pip install --index-url "$mirror" --trusted-host $(echo $mirror | sed 's|https://||' | sed 's|/.*||') "$package"; then
        echo -e "${GREEN}✓ Installation successful${NC}"
        return 0
    else
        echo -e "${RED}✗ Installation failed${NC}"
        return 1
    fi
}

# Uninstall package
uninstall_package() {
    local package=$1
    echo -e "${BLUE}Uninstalling package: $package${NC}"
    
    if pip uninstall -y "$package"; then
        echo -e "${GREEN}✓ Uninstallation successful${NC}"
        return 0
    else
        echo -e "${RED}✗ Uninstallation failed${NC}"
        return 1
    fi
}

# Search for package
search_package() {
    local package=$1
    local mirror=$(get_best_mirror)
    
    if [ -z "$mirror" ]; then
        return 1
    fi
    
    echo -e "${GREEN}Using mirror: $mirror${NC}"
    echo -e "${BLUE}Searching for package: $package${NC}"
    
    pip search --index "$mirror" "$package"
}

# Configuration setting
config_set() {
    local key=$1
    local value=$2
    
    case $key in
        "region")
            if [ "$value" = "cn" ] || [ "$value" = "global" ]; then
                sed -i "s/^region=.*/region=$value/" "$CONFIG_FILE"
                echo -e "${GREEN}Region set to: $value${NC}"
                
                # Update backup mirrors priority based on region
                if [ "$value" = "cn" ]; then
                    BACKUP_MIRRORS=(
                        "https://mirrors.aliyun.com/pypi/simple/"
                        "https://pypi.tuna.tsinghua.edu.cn/simple/"
                        "https://mirrors.bfsu.edu.cn/pypi/web/simple/"
                        "https://pypi.org/simple/"
                    )
                else
                    BACKUP_MIRRORS=(
                        "https://pypi.org/simple/"
                        "https://mirrors.aliyun.com/pypi/simple/"
                        "https://pypi.tuna.tsinghua.edu.cn/simple/"
                        "https://mirrors.bfsu.edu.cn/pypi/web/simple/"
                    )
                fi
                
                # Update backup mirrors in config
                local mirrors_str=$(printf "%s " "${BACKUP_MIRRORS[@]}")
                sed -i "s/^backup_mirrors=.*/backup_mirrors=$mirrors_str/" "$CONFIG_FILE"
            else
                echo -e "${RED}Error: Region can only be 'cn' or 'global'${NC}"
            fi
            ;;
        "timeout")
            if [[ "$value" =~ ^[0-9]+$ ]] && [ "$value" -gt 0 ]; then
                sed -i "s/^timeout=.*/timeout=$value/" "$CONFIG_FILE"
                echo -e "${GREEN}Timeout set to: ${value} seconds${NC}"
            else
                echo -e "${RED}Error: Timeout must be a positive integer${NC}"
            fi
            ;;
        *)
            echo -e "${RED}Error: Unknown configuration item '$key'${NC}"
            echo "Available items: region, timeout"
            ;;
    esac
}

# Show configuration
show_config() {
    if [ -f "$CONFIG_FILE" ]; then
        echo -e "${GREEN}Current configuration:${NC}"
        cat "$CONFIG_FILE"
    else
        echo -e "${YELLOW}Using default configuration${NC}"
        echo "primary_mirror=$DEFAULT_MIRROR"
        echo "region=global"
        echo "timeout=30"
    fi
}

# Show help
show_help() {
    cat << EOF
terpi - Termux Python Package Management Tool v$VERSION

Usage: terpi [command] [parameters]

Commands:
  install <package>    Install Python package
  uninstall <package>  Uninstall Python package  
  search <package>     Search for Python package
  config set <key> <value>  Set configuration
  config show         Show current configuration
  test                Test mirror availability
  help                Show this help message
  version             Show version information

Examples:
  terpi install requests
  terpi uninstall numpy
  terpi search flask
  terpi config set region cn
  terpi config set timeout 60

Configuration keys:
  region   Region setting (cn/global)
  timeout  Network timeout in seconds

Default mirror: $DEFAULT_MIRROR
EOF
}

# Show version
show_version() {
    echo "terpi v$VERSION"
    echo "Termux Python Package Management Tool"
}

# Main function
main() {
    init_config
    read_config
    
    case $1 in
        "install")
            if [ -z "$2" ]; then
                echo -e "${RED}Error: Please specify package name to install${NC}"
                exit 1
            fi
            install_package "$2"
            ;;
        "uninstall")
            if [ -z "$2" ]; then
                echo -e "${RED}Error: Please specify package name to uninstall${NC}"
                exit 1
            fi
            uninstall_package "$2"
            ;;
        "search")
            if [ -z "$2" ]; then
                echo -e "${RED}Error: Please specify package name to search${NC}"
                exit 1
            fi
            search_package "$2"
            ;;
        "config")
            case $2 in
                "set")
                    if [ -z "$3" ] || [ -z "$4" ]; then
                        echo -e "${RED}Error: Please specify configuration key and value${NC}"
                        exit 1
                    fi
                    config_set "$3" "$4"
                    ;;
                "show")
                    show_config
                    ;;
                *)
                    echo -e "${RED}Error: Unknown config subcommand${NC}"
                    show_help
                    ;;
            esac
            ;;
        "test")
            get_best_mirror > /dev/null
            ;;
        "help"|"--help"|"-h")
            show_help
            ;;
        "version"|"--version"|"-v")
            show_version
            ;;
        *)
            echo -e "${RED}Error: Unknown command '$1'${NC}"
            show_help
            exit 1
            ;;
    esac
}

# Check dependencies
check_dependencies() {
    if ! command -v pip &> /dev/null; then
        echo -e "${RED}Error: pip not found. Please install Python and pip first${NC}"
        exit 1
    fi
    
    if ! command -v curl &> /dev/null; then
        echo -e "${RED}Error: curl not found. Please install curl first${NC}"
        exit 1
    fi
}

# Script entry point
if [ $# -eq 0 ]; then
    show_help
    exit 0
fi

check_dependencies
main "$@"
