#!/bin/bash

declare -A direnv_layout_dirs
direnv_layout_dir() {
    local hash dir
    echo "${direnv_layout_dirs[${PWD}]:=$(
        hash="$(sha1sum - <<< "${PWD}" | head -c40)"
        dir="$(basename "${PWD}")"
        echo "${XDG_CACHE_HOME:-${HOME}/.cache}/direnv/layouts/${dir}-${hash}"
    )}"
}

layout_python_uv() {
    local python python_path version
    python="${1:-python}"
    if [ "${#}" -gt 0 ]; then
        shift
    fi
    unset PYTHONHOME

    if [ ! -f "pyproject.toml" ]; then
        uv init -p "${python}" --bare
        rm hello.py
    fi

    python_path="$(uv python find "${python}")"
    version="$(${python_path} -V | cut -d' ' -f 2 | cut -d . -f 1-2)"

    if [ -z "${version}" ]; then
        log_error "Could not find python's version"
        return 1
    fi

    if [ -n "${VIRTUAL_ENV:-}" ]; then
        local REPLY
        realpath.absolute "${VIRTUAL_ENV}"
        VIRTUAL_ENV="${REPLY}"
    else
        VIRTUAL_ENV="$(direnv_layout_dir)/python-${version}"
        if [ ! -d "${VIRTUAL_ENV}" ]; then
            uv venv --prompt=" ${version}" -p "${python}" \
               "${@}" "${VIRTUAL_ENV}"
        fi
    fi

    export UV_PROJECT_ENVIRONMENT="${VIRTUAL_ENV}"
    export VIRTUAL_ENV
    PATH_add "${VIRTUAL_ENV}/bin"
}
