#!/usr/bin/env bash
# Commit and optionally push a completed feature
# Usage: ./scripts/commit_feature.sh <feature_id>

set -euo pipefail

FEATURE_ID="${1:-}"
if [ -z "$FEATURE_ID" ]; then
  echo "[FAIL] Usage: $0 <feature_id>" >&2
  exit 1
fi

# Check if git repo
if ! git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
  echo "[SKIP] Not a git repository, skipping commit"
  exit 0
fi

# Stage all changes (excluding node_modules, dist, .next, etc.)
git add -A

# Check if there are changes to commit
if git diff --cached --quiet; then
  echo "[SKIP] No changes to commit for $FEATURE_ID"
  exit 0
fi

# Create commit message
COMMIT_MSG="feat($FEATURE_ID): completed feature"

# Check if there's a description in the feature
if [ -f "work/current.md" ]; then
  # Extract first line of description if available
  DESC=$(grep -m1 "^## Description" work/current.md -A1 2>/dev/null | tail -1 | sed 's/^[[:space:]]*//' || true)
  if [ -n "$DESC" ]; then
    COMMIT_MSG="$COMMIT_MSG

$DESC"
  fi
fi

# Commit
git commit -m "$COMMIT_MSG"

echo "[OK] Committed $FEATURE_ID"

# Check if remote exists and push
if git remote get-url origin >/dev/null 2>&1; then
  BRANCH=$(git rev-parse --abbrev-ref HEAD)
  echo "[INFO] Pushing to origin/$BRANCH..."
  if git push origin "$BRANCH"; then
    echo "[OK] Pushed to origin/$BRANCH"
  else
    echo "[WARN] Push failed (you can push manually later)"
  fi
else
  echo "[SKIP] No remote 'origin' configured, skipping push"
fi
