#!/usr/bin/env bash

show-prompt() {
    local commit=""
    local repo_path="${2:-.}"

    if [[ -n "$1" ]]; then
        if [[ -n "$2" ]]; then
            commit="$1"
        elif [[ "$1" == */* ]] || [[ "$1" == "." ]]; then
            repo_path="$1"
        else
            commit="$1"
        fi
    fi

    if [[ ! -d "$repo_path/.git" ]]; then
        echo "Error: No .git directory found in $repo_path."
        return 1
    fi

    local worktree_path="$repo_path/tmp/prompt-log"

    if [[ ! -d "$worktree_path" ]]; then
        echo "No prompt-log worktree found. Run init-prompt-log first."
        return 1
    fi

    local target_file

    if [[ -z "$commit" ]]; then
        if ! command -v fzf &> /dev/null; then
            echo "Error: fzf is required for interactive selection."
            return 1
        fi

        local selected
        selected="$(
            for f in "$worktree_path"/*.md; do
                if [[ -f "$f" ]]; then
                    local f_title f_date f_commit
                    f_title="$(grep -m1 '^title:' "$f" | sed 's/^title:[[:space:]]*//; s/^"\(.*\)"$/\1/; s/'"'"'\(.*\)'"'"'$/\1/')"
                    f_date="$(basename "$f")"
                    f_date="${f_date%%_*}"
                    echo "$f_date|$f_title|$(basename "$f")"
                fi
            done | sort -t'|' -k1,1 -r | while IFS='|' read -r _ title filename; do
                echo "$filename: $title"
            done | fzf | cut -d: -f1
        )"

        if [[ -z "$selected" ]]; then
            echo "No prompt selected."
            return 0
        fi

        target_file="$worktree_path/$selected"
    else
        local matching_files=()
        for f in "$worktree_path"/${commit}*.md; do
            if [[ -f "$f" ]]; then
                matching_files+=("$f")
            fi
        done

        if [[ ${#matching_files[@]} -eq 0 ]]; then
            echo "Error: No prompt file found starting with date prefix '$commit'."
            return 1
        elif [[ ${#matching_files[@]} -gt 1 ]]; then
            echo "Error: Ambiguous date prefix '$commit'. Matches:"
            printf '%s\n' "${matching_files[@]}"
            return 1
        fi

        target_file="${matching_files[0]}"
    fi

    cat "$target_file"
}
shp() {
    show-prompt "$@"
}
