#!/usr/bin/env bash

# Install lazycommit
go install github.com/m7medvision/lazycommit@latest

# Add Go bin directory to PATH if it doesn't exist
if ! echo "$PATH" | grep -q "$(go env GOPATH)/bin"; then
  mkdir -p "${HOME}/.zshrc.d"

  # Write the PATH export with proper escaping
  cat >"${HOME}/.zshrc.d/008_lazycommit.zsh" <<'EOF'
  # Add Go binaries to PATH
  export PATH="${PATH}:${HOME}/go/bin"
EOF

  # Source the new file
  source "${HOME}/.zshrc.d/008_lazycommit.zsh"
fi

# Create the configuration directory
mkdir -p "${HOME}/.config/.lazycommit"

# Create the configuration file with default settings
cat >"${HOME}/.config/.lazycommit.yaml" <<'EOF'
active_provider: copilot
providers:
  copilot:
    api_key: "$GITHUB_TOKEN"
    model: "gpt-4o"
  openai:
    api_key: "$OPENAI_API_KEY"
    model: "gpt-4o"
EOF

# Add custom command to lazygit: ${HOME}/.config/lazygit/config.yml
#
# customCommands:
# - key: "<c-a>" # ctrl + a
# description: "Pick AI commit"
# command: 'echo "{{.Form.Msg}}" > .git/COMMIT_EDITMSG && nvim .git/COMMIT_EDITMSG && [ -s .git/COMMIT_EDITMSG ] && git commit -F .git/COMMIT_EDITMSG || echo "Commit message is empty, commit aborted."'
# context: "files"
# subprocess: true
# prompts:
# - type: "menuFromCommand"
# title: "AI Commits"
# key: "Msg"
# command: "bunx @m7medvision/lazycommit@latest"
# filter: '^(?P<number>\d+)\.\s(?P<message>.+)$'
# valueFormat: "{{ .message }}"
# labelFormat: "{{ .number }}: {{ .message | green }}"

yq e -i '.customCommands += [{"key": "<c-a>", "description": "Pick AI commit", "context": "files", "subprocess": true, "loadingText": "Generating commit message...", "prompts": [{"type": "menuFromCommand", "title": "AI Generated Commits", "key": "Msg", "command": "bunx @m7medvision/lazycommit@latest --list", "filter": "^(?P<number>\\d+)\\.\\s(?P<message>.+)$", "valueFormat": "{{ .message }}", "labelFormat": "{{ .number }}: {{ .message | green }}"}], "command": "echo \"{{index .PromptResponses 0}}\" > .git/COMMIT_EDITMSG && nvim .git/COMMIT_EDITMSG && if [ -s .git/COMMIT_EDITMSG ]; then git commit -F .git/COMMIT_EDITMSG; else echo \"Commit message is empty, commit aborted.\" && rm .git/COMMIT_EDITMSG; fi"}]' ${HOME}/.config/lazygit/config.yml

# Verify the installation
echo "Current PATH entries:"
echo "$PATH" | tr ':' '\n' | grep '/go/bin'

# Test lazycommit
lazycommit commit
