#!/usr/bin/env bash

convert-prompts-folder-to-prompt-log() {
    local repo_path="${1:-.}"

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

    local prompts_dir="$repo_path/prompts"

    if [[ ! -d "$prompts_dir" ]]; then
        echo "No prompts directory found at $prompts_dir."
        return 0
    fi

    local original_dir
    original_dir="$(pwd)"
    cd "$repo_path" || { echo "Cannot change to $repo_path"; return 1; }

    if [[ ! -d "tmp/prompt-log" ]] || ! git worktree list | grep -qF "$(pwd)/tmp/prompt-log"; then
        echo "Creating prompt-log worktree."
        if ! git show-ref --verify --quiet refs/heads/prompt-log; then
            local current_branch
            current_branch="$(git rev-parse --abbrev-ref HEAD)"
            if [[ "$current_branch" == "prompt-log" ]]; then
                echo "Error: Cannot create prompt-log worktree while on prompt-log branch."
                cd "$original_dir" || true
                return 1
            fi
            local empty_tree="4b825dc642cb6eb9a060e54bf8d69288fbee4904"
            local orphan_commit
            orphan_commit="$(echo "init: prompt-log branch" | git commit-tree "$empty_tree")"
            git branch prompt-log "$orphan_commit"
        fi
        mkdir -p tmp
        git worktree add "tmp/prompt-log" prompt-log
    fi

    local worktree_path="tmp/prompt-log"
    local -a skipped
    local converted=0

    for file in "$prompts_dir"/*.md; do
        if [[ ! -f "$file" ]]; then
            continue
        fi

        local filename
        filename="$(basename "$file")"

        local creation_date creation_commit_full
        creation_date="$(git log --follow --diff-filter=A --format="%ad" --date=format:"%Y-%m-%d" -- "$file" | tail -n 1)"
        creation_commit_full="$(git log --follow --diff-filter=A --format="%H" -- "$file" | tail -n 1)"

        if [[ -z "$creation_date" ]]; then
            skipped+=("$filename")
            continue
        fi

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

        if [[ -z "$title" ]]; then
            title="untitled"
        fi

        local slug
        slug=$(echo "$title" | tr '[:upper:]' '[:lower:]' | tr '.' '-' | tr ' ' '-' | tr -cd '[:alnum:]-')

        local target_filename="${creation_date}_${slug}.md"
        local target_path="$worktree_path/$target_filename"

        cp "$file" "$target_path"

        if grep -q '^commit_ref:' "$target_path"; then
            sed -i "s/^commit_ref:.*/commit_ref: $creation_commit_full/" "$target_path"
        else
            awk -v hash="$creation_commit_full" 'NR==1 && /^---$/ { print; print "commit_ref: " hash; next } { print }' "$target_path" > "$target_path.tmp"
            mv "$target_path.tmp" "$target_path"
        fi

        (
            cd "$worktree_path" || exit 1
            git add "$target_filename"
            git commit -m "feat: add prompt file" -m "$target_filename"
        ) || { echo "Error: Failed to commit $target_filename"; continue; }

        converted=$((converted + 1))
    done

    if [[ ${#skipped[@]} -gt 0 ]]; then
        echo "Skipped files with no discoverable creation commit:"
        printf '%s\n' "${skipped[@]}"
    fi

    echo "Converted $converted prompt file(s)."

    if [[ $converted -gt 0 ]]; then
        rm -rf "$prompts_dir"
        echo "Removed old $prompts_dir folder."
    fi

    cd "$original_dir" || true
}
cpfpl() {
    convert-prompts-folder-to-prompt-log "$@"
}
