#!/usr/bin/env bash

list-prompts() {
    local repo_path="${1:-.}"

    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."
        return 0
    fi

    local files=("$worktree_path"/*.md)

    if [[ ! -f "${files[0]}" ]]; then
        echo "No prompt files found."
        return 0
    fi

    local max_date_len=4
    local max_title_len=5
    local max_state_len=5
    local max_commit_len=6

    local -a rows

    for file in "${files[@]}"; do
        if [[ ! -f "$file" ]]; then
            continue
        fi

        local title
        title="$(grep -m1 '^title:' "$file" | sed 's/^title:[[:space:]]*//; s/^"\(.*\)"$/\1/; s/'"'"'\(.*\)'"'"'$/\1/')"

        local state
        state="$(grep -m1 '^state:' "$file" | sed 's/^state:[[:space:]]*//; s/^"\(.*\)"$/\1/; s/'"'"'\(.*\)'"'"'$/\1/')"

        local filename
        filename="$(basename "$file")"
        local date="${filename%%_*}"

        local commit_ref
        commit_ref="$(grep -m1 '^commit_ref:' "$file" | sed 's/^commit_ref:[[:space:]]*//; s/^"\(.*\)"$/\1/; s/'"'"'\(.*\)'"'"'$/\1/')"
        if [[ -n "$commit_ref" ]]; then
            commit_ref="${commit_ref:0:7}"
        fi

        rows+=("$date|$title|$state|$commit_ref")

        if [[ ${#date} -gt max_date_len ]]; then
            max_date_len=${#date}
        fi
        if [[ ${#title} -gt max_title_len ]]; then
            max_title_len=${#title}
        fi
        if [[ ${#state} -gt max_state_len ]]; then
            max_state_len=${#state}
        fi
        if [[ ${#commit_ref} -gt max_commit_len ]]; then
            max_commit_len=${#commit_ref}
        fi
    done

    printf "| %-${max_date_len}s | %-${max_title_len}s | %-${max_state_len}s | %-${max_commit_len}s |\n" "date" "title" "state" "commit"
    printf "|-%s-|-%s-|-%s-|-%s-|\n" \
        "$(printf '%*s' "$max_date_len" '' | tr ' ' '-')" \
        "$(printf '%*s' "$max_title_len" '' | tr ' ' '-')" \
        "$(printf '%*s' "$max_state_len" '' | tr ' ' '-')" \
        "$(printf '%*s' "$max_commit_len" '' | tr ' ' '-')"

    local -a sorted
    while IFS= read -r line; do
        sorted+=("$line")
    done < <(printf '%s\n' "${rows[@]}" | sort -t'|' -k1,1 -r)

    for row in "${sorted[@]}"; do
        IFS='|' read -r date title state commit <<< "$row"
        printf "| %-${max_date_len}s | %-${max_title_len}s | %-${max_state_len}s | %-${max_commit_len}s |\n" "$date" "$title" "$state" "$commit"
    done
}
lp() {
    list-prompts "$@"
}
