#!/usr/bin/env bash

load-prompt() {
    local prompt_path="${1:-prompt.md}"

    local prompt_dir
    prompt_dir="$(cd "$(dirname "$prompt_path")" 2>/dev/null && pwd)" || prompt_dir="$(pwd)"
    local repo_path
    repo_path="$(cd "$prompt_dir" && git rev-parse --show-toplevel 2>/dev/null)" || {
        echo "Error: Could not find git repository for $prompt_path."
        return 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. Run init-prompt-log first."
        return 1
    fi

    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_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

    local target_file="$worktree_path/$selected"
    cp "$target_file" "$prompt_path"
    echo "Loaded '$selected' into $prompt_path."
}
lpm() {
    load-prompt "$@"
}
