#!/usr/bin/env bash

DJB_LIB="${DJB_LIB:-./djb}"

djb_command_exists() {
    command -v "$1" >/dev/null 2>&1
}

djb_run() {
    if djb_command_exists djb; then
        djb "$@"
    else
        if ! djb_command_exists uv; then
            echo "Installing uv..."
            curl -LsSf https://astral.sh/uv/install.sh | sh || {
                echo "Failed to install uv" >&2
                exit 1
            }
        fi
        uv run --with "$DJB_LIB" --reinstall-package djb djb "$@"
    fi
}


# Create project.
DJB_PROJECT_PATH_FILE=$(mktemp --suffix "-djb-project-path.txt")
echo "Debug: DJB_PROJECT_PATH_FILE: $DJB_PROJECT_PATH_FILE"
djb_run create --write-project-path-file "$DJB_PROJECT_PATH_FILE" || exit 1
DJB_PROJECT_PATH=$(cat "$DJB_PROJECT_PATH_FILE")

# Configure project and install dependencies.
djb_run up --project-path "$DJB_PROJECT_PATH"

# Print next steps for when this script isn't sourced.
( return 0 2>/dev/null ) || {
    echo "✓ Success! Your project has been created in $DJB_PROJECT_PATH"
    echo "→ Next, to activate your project in the current shell, run:"
    echo "cd \"$DJB_PROJECT_PATH\" && source .djbrc"
    echo
    echo "* Tip: djb does this automatically when sourced:"
    echo "source <(curl -LsSf create.djb.sh)"
    exit 0
}

#
# The rest only applies when this script is sourced.
#

# Switch to project dir.
cd "$DJB_PROJECT_PATH" || {
    echo "Error: failed to switch to project directory '$DJB_PROJECT_PATH'."
}
echo "✓ Switched to $DJB_PROJECT_PATH"

# Configure shell.
source .djbrc

# Cleanup functions and variables.
unset djb_run
unset djb_command_exists
unset DJB_PROJECT_PATH_FILE
unset DJB_PROJECT_PATH

