#!/usr/bin/env bash
# ============================================================
# HalaVoice — commit + push SOURCE to GitHub
#
# Safety: refuses to push if a staged file matches a live-secret
# pattern (real OpenAI keys, private keys, the DB password, or any
# tracked .env). The database itself is NEVER pushed (it holds PII
# / KYC data) — GitHub is the source-of-truth for CODE only.
#
# Usage: ops/git-sync.sh ["commit message"]
# ============================================================
source "$(dirname "${BASH_SOURCE[0]}")/lib.sh"

cd "$REPO_ROOT"
[ -d .git ] || die "not a git repo — run ops/git-init.sh first"

MSG="${1:-"chore: automated sync $(date -u +%FT%TZ)"}"

git add -A

# --- secret guard: scan staged content before it can be pushed --------
STAGED="$(git diff --cached --name-only || true)"
if [ -n "$STAGED" ]; then
  # 1) no tracked .env / secret files
  if echo "$STAGED" | grep -qE '(^|/)\.env($|\.)|\.appointment-webhook-secret|license\.json|vendor-private\.pem'; then
    git reset -q
    die "secret file staged ($(echo "$STAGED" | grep -E '\.env|secret|private' | head -1)); aborting push"
  fi
  # 2) no live-secret patterns in staged blobs (placeholders like sk-xxxx are allowed).
  #    A DB URL with an inline password is detected generically so no real
  #    credential is ever hardcoded in this guard.
  BADHIT="$(git diff --cached -U0 | grep -E '^\+' \
     | grep -oE '(sk-(proj-)?[A-Za-z0-9_-]{30,}|AKIA[0-9A-Z]{16}|-----BEGIN (RSA|EC|OPENSSH) PRIVATE KEY|postgres(ql)?://[^:@/]+:[^@/]+@)' \
     | grep -vE 'sk-x{10,}|sk-\.\.\.|sk-your|://[^:@/]+:([^@/]*(password|pass|xxx+|user|change|your|example|here|placeholder)[^@/]*)@' | head -1 || true)"
  if [ -n "$BADHIT" ]; then
    git reset -q
    die "possible live secret in staged changes: ${BADHIT:0:12}… ; aborting push"
  fi
fi

if git diff --cached --quiet; then
  log "no changes to push"
  exit 0
fi

git -c user.name="HalaVoice Backup Bot" \
    -c user.email="ops@halavoice.store" \
    commit -q -m "$MSG"
ok "committed: $MSG"

BRANCH="$(git rev-parse --abbrev-ref HEAD)"
if git remote get-url origin >/dev/null 2>&1; then
  git push -q origin "$BRANCH" && ok "pushed to origin/$BRANCH" || warn "push failed (commit is saved locally)"
else
  warn "no 'origin' remote — commit saved locally only"
fi
