#!/bin/bash

# Path: scripts/python.sh
set -e

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

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
source "$SCRIPT_DIR/lib/distro.sh"

# Install Build Dependencies
if is_arch_family; then
    echo -e "${BLUE}    LOG:${YELLOW} Installing Arch build dependencies...${NC}"
    PYTHON_BUILD_DEPS=(base-devel openssl zlib xz tk libffi bzip2 git)
elif is_debian_family; then
    echo -e "${BLUE}    LOG:${YELLOW} Installing Debian build dependencies...${NC}"
    PYTHON_BUILD_DEPS=(make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev xz-utils tk-dev libffi-dev liblzma-dev git)
elif is_fedora_family; then
    echo -e "${BLUE}    LOG:${YELLOW} Installing Fedora build dependencies...${NC}"
    PYTHON_BUILD_DEPS=(make gcc gcc-c++ patch zlib-devel bzip2 bzip2-devel readline-devel sqlite sqlite-devel openssl-devel tk-devel libffi-devel xz xz-devel ncurses-devel findutils git)
else
    echo -e "${RED}    ERROR:${NC} Unsupported OS: $OS"
    exit 1
fi

install_status=0
install_packages "${PYTHON_BUILD_DEPS[@]}" || install_status=$?

if [ "$install_status" -eq 42 ]; then
    exit 0
elif [ "$install_status" -ne 0 ]; then
    exit "$install_status"
fi

# Define the Black Box Location
export PYENV_ROOT="$HOME/.programming/python/pyenv"
export PATH="$PYENV_ROOT/bin:$PATH"

echo -e "${BLUE}    LOG:${YELLOW} Setting up Pyenv in ${PYENV_ROOT}...${NC}"

# Install Pyenv
if [ ! -d "$PYENV_ROOT" ]; then
    echo -e "${BLUE}    LOG:${YELLOW} Cloning Pyenv...${NC}"
    git clone https://github.com/pyenv/pyenv.git "$PYENV_ROOT"
    
    echo -e "${BLUE}    LOG:${YELLOW} Compiling Pyenv dynamic bash extension...${NC}"
    cd "$PYENV_ROOT" && src/configure && make -C src
    
    echo -e "${GREEN}    SUCCESS:${NC} Pyenv installed."
else
    echo -e "${GREEN}    SKIP:${NC} Pyenv already installed."
fi

# Initialize Pyenv for this script session
eval "$(pyenv init -)"

# Install Miniforge (The Community Standard)
TARGET_VER="miniforge3-latest"

if ! pyenv versions | grep -q "$TARGET_VER"; then
    echo -e "${BLUE}    LOG:${YELLOW} Installing ${TARGET_VER}...${NC}"
    echo -e "${YELLOW}    NOTE: This avoids Anaconda licensing issues and uses conda-forge default.${NC}"
    
    pyenv install "$TARGET_VER"
    
    echo -e "${GREEN}    SUCCESS:${NC} Miniforge installed."
else
    echo -e "${GREEN}    SKIP:${NC} Miniforge already installed."
fi

# Set Global Default
pyenv global "$TARGET_VER"

echo -e "${GREEN}    SUCCESS:${NC} Python setup completed. Default is now Miniforge (Conda)."
