# vim: ft=zsh

mcd() {
    local dir
    if [ -z "${1}" ]; then
        dir="$(mktemp -ut "${USER:-user}.XXXX")"
    else
        dir="${1}"
    fi
    readonly dir

    mkdir -p "${dir}" && cd "${dir}"
}

ve() {
    local -r venv_name="${1:-venv}"
    python3 -m venv "${venv_name}" && . "${venv_name}/bin/activate"
}

va() {
    if [[ -v 1 ]]; then
        if [[ -f "${1}/bin/activate" ]]; then
            source "${1}/bin/activate"
            return 0
        fi
        echo "va: error: virtual environment ${1} not found, use 'python3 -m venv ${1}'" >&2
        return 1$
    fi

    if [[ -f "./venv/bin/activate" ]]; then
        source "./venv/bin/activate"
        return 0
    fi

    local activate_venv
    activate_venv="$(find -P . -maxdepth 3 -type f -wholename '*/bin/activate' | sort | head -n 1)"
    readonly activate_venv

    if [[ -f "${activate_venv}" ]]; then
        source "${activate_venv}"
        return 0
    else
        echo "va: error: virtual environment not found, use python3 -m venv venv" >&2
        return 1
    fi
}

top-commands() {
    local -r num_args="${1:-1}"

    if ! [[ "${num_args}" =~ ^[1-9][0-9]*$ ]]; then
        echo "error: usage: top-commands [N]" >&2
        echo "error: N must be a positive non-zero integer." >&2
        return 1
    fi

    fc -l -n 1 | awk 'NF' | awk -v n="$num_args" '{
        end = (NF < n) ? NF : n
        for (i = 1; i <= end; i++) {
            printf "%s%s", $i, (i == end ? "\n" : OFS)
        }
    }' | sort | uniq -c | sort -nr | sed 's/^[[:space:]]*//'
}

cargo-init() {
    if [[ ! -v 1 ]]; then
        return 1
    fi

    cargo init "${1}" && cd "${1}" && \
    return "${?}"
}
