#!/usr/bin/env bash
#
# pyenv-check-reqs — resolve a requirements file against every Python version
# installed with pyenv, so you know which interpreters your pin set supports.
#
# Copyright (c) 2026 Andre Neto (ags-neto)
# SPDX-License-Identifier: MIT

set -euo pipefail

PROGRAM="${0##*/}"
VERSION='1.0.0'

PYENV_BIN='pyenv'
DEFAULT_REQUIREMENTS='requirements.txt'

REQUIREMENTS_FILE=''
VERSION_SPEC=''
QUIET=0
VERBOSE=0

WORK_DIR=''
WORK_DIR_CREATED=0

# ---------------------------------------------------------------- utilities --

usage() {
    cat <<EOF
$PROGRAM $VERSION — check a requirements file against the Python versions of pyenv

Usage:
  $PROGRAM [options] [requirements-file]

Options:
  -f, --file PATH       requirements file to compile (default: $DEFAULT_REQUIREMENTS)
      --versions SPEC   comma-separated list of versions and/or ranges to test,
                        e.g. 3.11,3.12 or 3.8-3.14
                        (default: every base version pyenv knows about)
  -q, --quiet           print only the summary and the failures
  -v, --verbose         print every command and the full output of the tools
  -V, --version         print the version and exit
  -h, --help            print this help and exit

Exit status:
  0  every selected version resolved the requirements
  1  at least one selected version failed to resolve
  2  usage error: bad option, missing requirements file, no usable pyenv

Requirements:
  pyenv on PATH with at least one base interpreter installed
  (https://github.com/pyenv/pyenv#installation · Arch: pacman -S pyenv pyenv-virtualenv)

  pip-tools does not have to be installed in every interpreter: if it is missing,
  $PROGRAM installs it into a throwaway venv under \$TMPDIR and removes it on
  exit, so your pyenv installations are never modified.
EOF
}

log() {
    [ "$QUIET" -eq 1 ] && return 0
    printf '%s\n' "$*"
}

verbose() {
    [ "$VERBOSE" -eq 1 ] || return 0
    printf '%s\n' "$*" >&2
}

error() {
    printf '%s: %s\n' "$PROGRAM" "$*" >&2
}

die_usage() {
    error "$1"
    printf "Try '%s --help'.\n" "$PROGRAM" >&2
    exit 2
}

cleanup() {
    local rc=$?
    if [ "$WORK_DIR_CREATED" -eq 1 ] && [ -n "$WORK_DIR" ] && [ -d "$WORK_DIR" ]; then
        rm -rf -- "$WORK_DIR"
    fi
    exit "$rc"
}

# The scratch directory holds the generated outputs, the pip logs and the
# temporary virtualenvs; it always goes away, however we leave.
make_work_dir() {
    WORK_DIR=$(mktemp -d "${TMPDIR:-/tmp}/pyenv-check-reqs.XXXXXXXX") || {
        error "cannot create a temporary directory under ${TMPDIR:-/tmp}"
        exit 2
    }
    WORK_DIR_CREATED=1
    trap cleanup EXIT INT TERM HUP
}

# is_between LO MID HI — MID is inside the [LO, HI] range, compared version-wise.
is_between() {
    local mid
    mid=$(printf '%s\n' "$1" "$2" "$3" | sort -V | sed -n '2p')
    [ "$mid" = "$2" ]
}

# select_versions ALL_VERSIONS SPEC — SPEC is a comma-separated list of exact
# versions (3.11.13), minor series (3.11) and ranges (3.8-3.14). An empty SPEC
# selects everything. Returns 2 on a malformed SPEC.
select_versions() {
    local all=$1 spec=$2 v item lo hi mm
    local items=() want=''

    if [ -z "$spec" ]; then
        printf '%s\n' "$all"
        return 0
    fi

    IFS=',' read -r -a items <<< "$spec"
    for item in "${items[@]}"; do
        item=$(printf '%s' "$item" | tr -d '[:space:]')
        [ -n "$item" ] || continue

        if [[ $item =~ ^[0-9]+\.[0-9]+-[0-9]+\.[0-9]+$ ]]; then
            lo=${item%%-*}
            hi=${item##*-}
            while IFS= read -r v; do
                [ -n "$v" ] || continue
                mm=${v%.*}
                if is_between "$lo" "$mm" "$hi"; then
                    want+="$v"$'\n'
                fi
            done <<< "$all"
        elif [[ $item =~ ^[0-9]+\.[0-9]+(\.[0-9]+)?$ ]]; then
            while IFS= read -r v; do
                [ -n "$v" ] || continue
                if [ "$v" = "$item" ] || [[ $v == "$item".* ]]; then
                    want+="$v"$'\n'
                fi
            done <<< "$all"
        else
            return 2
        fi
    done

    printf '%s' "$want" | sed '/^$/d' | sort -V -u
}

# ------------------------------------------------------------ argument parse --

while [ $# -gt 0 ]; do
    case "$1" in
        -h | --help)
            usage
            exit 0
            ;;
        -V | --version)
            printf '%s %s\n' "$PROGRAM" "$VERSION"
            exit 0
            ;;
        -f | --file)
            [ $# -ge 2 ] || die_usage "option '$1' needs a path"
            REQUIREMENTS_FILE=$2
            shift 2
            ;;
        --file=*)
            REQUIREMENTS_FILE=${1#*=}
            shift
            ;;
        --versions)
            [ $# -ge 2 ] || die_usage "option '$1' needs a value"
            VERSION_SPEC=$2
            shift 2
            ;;
        --versions=*)
            VERSION_SPEC=${1#*=}
            shift
            ;;
        -q | --quiet)
            QUIET=1
            shift
            ;;
        -v | --verbose)
            VERBOSE=1
            shift
            ;;
        --)
            shift
            break
            ;;
        -*)
            die_usage "unknown option '$1'"
            ;;
        *)
            break
            ;;
    esac
done

if [ $# -gt 0 ]; then
    [ -z "$REQUIREMENTS_FILE" ] || die_usage "the requirements file was given more than once"
    REQUIREMENTS_FILE=$1
    shift
fi
[ $# -eq 0 ] || die_usage "unexpected argument '$1'"

REQUIREMENTS_FILE=${REQUIREMENTS_FILE:-$DEFAULT_REQUIREMENTS}

if [ -n "$VERSION_SPEC" ] && ! [[ $VERSION_SPEC =~ ^[0-9.,[:space:]-]+$ ]]; then
    die_usage "invalid --versions value '$VERSION_SPEC'"
fi

if [ ! -f "$REQUIREMENTS_FILE" ]; then
    error "requirements file not found: $REQUIREMENTS_FILE"
    exit 2
fi
if [ ! -r "$REQUIREMENTS_FILE" ]; then
    error "requirements file is not readable: $REQUIREMENTS_FILE"
    exit 2
fi

if ! command -v "$PYENV_BIN" > /dev/null 2>&1; then
    cat >&2 <<EOF
$PROGRAM: pyenv was not found on your PATH, so there is no interpreter to check against.

Install pyenv first:
  Arch Linux      sudo pacman -S pyenv pyenv-virtualenv
  Debian/Ubuntu   curl -fsSL https://pyenv.run | bash
  macOS           brew install pyenv

Then install at least one interpreter, e.g.  pyenv install 3.12
Documentation: https://github.com/pyenv/pyenv#installation
EOF
    exit 2
fi

if ! PYENV_RAW=$("$PYENV_BIN" versions --bare 2>&1); then
    error "pyenv is on PATH but 'pyenv versions --bare' failed:"
    printf '%s\n' "$PYENV_RAW" | sed 's/^/  /' >&2
    exit 2
fi

# Base interpreters only: virtualenvs ("3.12.11/envs/x") and aliases are skipped.
ALL_VERSIONS=$(printf '%s\n' "$PYENV_RAW" | grep -E '^[0-9]+\.[0-9]+\.[0-9]+$' || true)

if [ -z "$ALL_VERSIONS" ]; then
    error "pyenv has no base interpreter installed (found: $(printf '%s' "$PYENV_RAW" | tr '\n' ' '))"
    printf "Install one with 'pyenv install <version>' and run again.\n" >&2
    exit 2
fi

if ! SELECTED=$(select_versions "$ALL_VERSIONS" "$VERSION_SPEC"); then
    die_usage "invalid --versions value '$VERSION_SPEC' (use e.g. 3.11,3.12 or 3.8-3.14)"
fi

if [ -z "$SELECTED" ]; then
    error "no installed pyenv version matches '$VERSION_SPEC'"
    printf 'Installed base versions: %s\n' "$(printf '%s' "$ALL_VERSIONS" | tr '\n' ' ')" >&2
    exit 2
fi

VERSION_LIST=$(printf '%s' "$SELECTED" | tr '\n' ' ')
read -r -a VERSIONS <<< "$VERSION_LIST"

make_work_dir

# ------------------------------------------------------------------- checks --

SUCCESS=()
FAILED=()

log "$PROGRAM $VERSION"
log "Requirements file : $REQUIREMENTS_FILE"
log "Versions to test  : ${#VERSIONS[@]} (${VERSION_LIST% })"
log ''

if [ "$VERBOSE" -eq 1 ]; then
    printf '   %s\n' "work directory: $WORK_DIR" \
        "pip-tools is installed into a temporary venv when a version is missing it" >&2
fi

for version in "${VERSIONS[@]}"; do
    output_file="$WORK_DIR/$version.txt"
    compile_log="$WORK_DIR/$version.compile.log"
    pip_log="$WORK_DIR/$version.pip.log"
    venv_dir="$WORK_DIR/venv-$version"

    runner=("$PYENV_BIN" exec python)
    runner_desc="$PYENV_BIN exec python ($version)"
    used_venv=0

    log "==> $version"

    # Fast path: pip-tools is already importable in this interpreter.
    if PYENV_VERSION="$version" "${runner[@]}" -c 'import piptools' > /dev/null 2>&1; then
        verbose "    using the pip-tools already installed in $version"
    else
        # Slow path: throwaway venv with pip-tools inside.
        log "    pip-tools not found in $version, building a temporary venv"
        verbose "    PYENV_VERSION=$version $PYENV_BIN exec python -m venv $venv_dir"

        if ! PYENV_VERSION="$version" "${runner[@]}" -m venv "$venv_dir" > "$pip_log" 2>&1; then
            error "$version: could not create a virtualenv"
            sed 's/^/        /' "$pip_log" >&2
            FAILED+=("$version (venv creation failed)")
            log ''
            continue
        fi

        if ! PIP_DISABLE_PIP_VERSION_CHECK=1 PIP_NO_INPUT=1 \
            "$venv_dir/bin/python" -m pip install --quiet pip-tools > "$pip_log" 2>&1; then
            error "$version: could not install pip-tools into a temporary venv"
            sed 's/^/        /' "$pip_log" | tail -n 5 >&2
            if grep -qiE 'network is unreachable|temporary failure in name resolution|failed to establish a new connection|no matching distribution|proxy|timed out|could not find a version' "$pip_log"; then
                printf '        This looks like a network/DNS problem: PyPI is unreachable.\n' >&2
                printf '        Install pip-tools offline for this version, or set PIP_INDEX_URL to a mirror.\n' >&2
            fi
            FAILED+=("$version (pip-tools could not be installed)")
            log ''
            continue
        fi

        runner=("$venv_dir/bin/python")
        runner_desc="$venv_dir/bin/python (temporary venv)"
        used_venv=1
    fi

    verbose "    compile: $runner_desc -m piptools compile $REQUIREMENTS_FILE --output-file $output_file"

    if "${runner[@]}" -m piptools compile "$REQUIREMENTS_FILE" \
        --output-file "$output_file" > "$compile_log" 2>&1; then
        if [ "$used_venv" -eq 1 ]; then
            log "    resolved (pip-tools from a temporary venv)"
        else
            log "    resolved"
        fi
        SUCCESS+=("$version")
    else
        FAILED+=("$version (resolution failed)")
        error "    $version: pip-tools could not resolve $REQUIREMENTS_FILE"
        sed 's/^/        /' "$compile_log" | tail -n 3 >&2
        if [ "$VERBOSE" -eq 1 ]; then
            printf '        full output: %s\n' "$compile_log" >&2
        fi
    fi
    log ''
done

# ------------------------------------------------------------------ summary --

printf '\n--- Summary ---\n'
printf 'Requirements file : %s\n' "$REQUIREMENTS_FILE"
printf 'Versions tested   : %s\n' "${VERSION_LIST% }"
printf '\nSuccessfully resolved dependencies for:\n'
if [ ${#SUCCESS[@]} -eq 0 ]; then
    printf '  None\n'
else
    printf '  - %s\n' "${SUCCESS[@]}"
fi

printf '\nFailed to resolve dependencies for:\n'
if [ ${#FAILED[@]} -eq 0 ]; then
    printf '  None\n'
else
    printf '  - %s\n' "${FAILED[@]}"
fi
printf '\n'

if [ ${#FAILED[@]} -gt 0 ]; then
    exit 1
fi
exit 0
