#!/usr/bin/env bash

commit-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 original_dir
    original_dir="$(pwd)"
    cd "$repo_path" || { echo "Cannot change to $repo_path"; return 1; }

    local abs_prompt_path
    abs_prompt_path="$prompt_dir/$(basename "$prompt_path")"
    local prompt_file="${abs_prompt_path#"$repo_path"/}"
    if [[ "$prompt_file" == "$abs_prompt_path" ]]; then
        prompt_file="$prompt_path"
    fi

    if [[ ! -f "$prompt_file" ]]; then
        echo "Error: $prompt_file not found in $repo_path."
        cd "$original_dir" || true
        return 1
    fi

    if [[ ! -d "tmp/prompt-log" ]] || ! git worktree list | grep -qF "$(pwd)/tmp/prompt-log"; then
        echo "Error: prompt-log worktree not found. Run init-prompt-log first."
        cd "$original_dir" || true
        return 1
    fi

    local commit_hash_full
    commit_hash_full="$(git rev-parse HEAD)"

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

    if [[ -z "$title" ]]; then
        echo "Error: Could not read title from $prompt_file frontmatter."
        cd "$original_dir" || true
        return 1
    fi

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

    local worktree_path="tmp/prompt-log"
    local filename
    local target_path
    local commit_msg="feat: add prompt file"

    local existing_file=""
    for f in "$worktree_path"/*.md; do
        if [[ -f "$f" ]]; then
            local f_title
            f_title="$(grep -m1 '^title:' "$f" | sed 's/^title:[[:space:]]*//; s/^"\(.*\)"$/\1/; s/'"'"'\(.*\)'"'"'$/\1/')"
            if [[ "$f_title" == "$title" ]]; then
                existing_file="$f"
                break
            fi
        fi
    done

    if [[ -n "$existing_file" ]]; then
        target_path="$existing_file"
        filename="$(basename "$target_path")"
        commit_msg="feat: update prompt file"
        echo "Updating existing prompt file: $filename"
    else
        local datestamp
        datestamp="$(date +%Y-%m-%d)"
        filename="${datestamp}_${slug}.md"
        target_path="$worktree_path/$filename"
    fi

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

    cp "$prompt_file" "$target_path"

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

    (
        cd "$worktree_path" || exit 1
        git add "$filename"
        git commit -m "$commit_msg" -m "$filename"
        git branch --set-upstream-to=origin/prompt-log prompt-log 2>/dev/null || true
        git pull 2>/dev/null || true
        git push 2>/dev/null || echo "Warning: push failed."
    ) || { echo "Error: Failed to store prompt."; cd "$original_dir" || true; return 1; }

    cd "$original_dir" || true
}
cop() {
    commit-prompt "$@"
}
