#!/usr/bin/env bash

create-prompt() {
    local title="$1"
    local prompt_path="${2:-prompt.md}"

    if [[ -z "$title" ]]; then
        echo "Error: Title cannot be empty."
        echo "Usage: task create-prompt <title> [path]"
        return 1
    fi

    local dir
    dir="$(dirname "$prompt_path")"
    if [[ ! -d "$dir" ]]; then
        mkdir -p "$dir" || { echo "Error: Could not create directory $dir"; return 1; }
    fi

    local git_author git_email
    git_author="$(git config --get user.name 2>/dev/null || echo '')"
    git_email="$(git config --get user.email 2>/dev/null || echo '')"

    export PROMPT_TITLE="$title"

    local prompt_author
    if [[ -n "$git_email" ]]; then
        prompt_author="${git_author} <${git_email}>"
    else
        prompt_author="$git_author"
    fi
    export PROMPT_AUTHOR="$prompt_author"

    if [[ -f "$prompt_path" ]]; then
        commit-prompt "$prompt_path"
    fi

    envsubst < "$HOME/taskfile.build/prompt.md.template" > "$prompt_path"

    if [[ -n "$EDITOR" ]]; then
        "$EDITOR" "$prompt_path"
    fi

    echo "File created:"
    echo "$prompt_path"
}
crp() {
    create-prompt "$@"
}
