#!/usr/bin/env bash
# git-commit-push: add, commit, and push changes
# Usage: git-commit-push "<commit message>" [repo_path]
#
# Defaults:
#   repo_path = DEFAPP env var or "defapp"
#   remote    = origin
#   branch    = current branch (uses upstream if set, else main/master)
#
# Example:
#   git-commit-push "Fix login bug"
#   git-commit-push "Update config" ./myrepo

set -euo pipefail

if [[ $# -lt 1 ]]; then
    echo "Usage: git-commit-push \"<commit message>\" [repo_path]" >&2
    exit 1
fi

MESSAGE="$1"
REPO_PATH="${2:-}"
DEFAPP="${DEFAPP:-defapp}"
REMOTE="${REMOTE_ORIGIN:-origin}"

if [[ -n "$REPO_PATH" ]]; then
    if [[ ! -d "$REPO_PATH" ]]; then
        echo "Error: directory not found: $REPO_PATH" >&2
        exit 1
    fi
    cd "$REPO_PATH"
elif [[ -d "$DEFAPP" ]]; then
    cd "$DEFAPP"
fi

git add .
git commit -m "$MESSAGE"

# Determine branch to push
BRANCH=$(git rev-parse --abbrev-ref HEAD)

# Try to use upstream if configured
if git rev-parse --abbrev-ref --symbolic-full-name "@{u}" >/dev/null 2>&1; then
    git push
else
    # Fallback: try main then master on remote
    if git rev-parse --verify --quiet "$REMOTE/main" >/dev/null 2>&1; then
        git push -u "$REMOTE" "$BRANCH"
    elif git rev-parse --verify --quiet "$REMOTE/master" >/dev/null 2>&1; then
        git push -u "$REMOTE" "$BRANCH"
    else
        echo "Warning: no upstream or remote main/master found. Pushing anyway." >&2
        git push -u "$REMOTE" "$BRANCH" || true
    fi
fi
