#!/usr/bin/env bash

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

    local current_branch
    current_branch="$(git rev-parse --abbrev-ref HEAD)"

    if [[ "$current_branch" == "prompt-log" ]]; then
        if [[ -d "tmp/prompt-log" ]] && git worktree list | grep -qF "$(pwd)/tmp/prompt-log"; then
            echo "prompt-log worktree already exists at tmp/prompt-log."
            cd "$original_dir" || true
            return 0
        fi
        echo "Error: Cannot create prompt-log worktree while on prompt-log branch. Switch to another branch first."
        cd "$original_dir" || true
        return 1
    fi

    if ! git show-ref --verify --quiet refs/heads/prompt-log; then
        # 4b825dc... is the SHA-1 of Git's empty tree object (constant across all repos)
        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

    if git rev-parse --abbrev-ref origin/prompt-log &>/dev/null; then
        echo "Remote branch origin/prompt-log already exists."
    elif git remote &>/dev/null; then
        git push -u origin prompt-log 2>/dev/null || echo "Warning: could not push prompt-log to remote."
    fi

    if [[ -d "tmp/prompt-log" ]] && git worktree list | grep -qF "$(pwd)/tmp/prompt-log"; then
        echo "prompt-log worktree already exists at tmp/prompt-log."
    else
        mkdir -p tmp
        git worktree add "tmp/prompt-log" prompt-log
        echo "Created prompt-log worktree at tmp/prompt-log."
    fi

    if git rev-parse --abbrev-ref origin/prompt-log &>/dev/null; then
        pull-prompt-log "$repo_path"
    fi

    cd "$original_dir" || true
}
ipl() {
    init-prompt-log "$@"
}
