#!/usr/bin/env bash
# task-2439 P2.5: pre-push hook — main direct push 거부 + cancelled task push 거부 + guard.sh 강제
# 설치: git config core.hooksPath scripts/git-hooks
set -e

WORKSPACE="$(git rev-parse --show-toplevel)"
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)

# 1) main direct push 자체 거부
if [[ "$CURRENT_BRANCH" == "main" ]]; then
    echo "[BLOCKED] main direct push 금지 — PR 경로 사용" >&2
    exit 1
fi

# 2) task branch 추출 + cancelled 차단 + guard.sh 강제
TASK_ID=$(echo "$CURRENT_BRANCH" | grep -oE 'task-[0-9]+' | head -n1 || true)
if [[ -n "$TASK_ID" ]]; then
    if [[ -f "$WORKSPACE/memory/events/${TASK_ID}.cancelled" ]]; then
        echo "[BLOCKED] task $TASK_ID cancelled — push 거부" >&2
        exit 1
    fi
    if ! bash "$WORKSPACE/scripts/guard.sh" pre-push "$TASK_ID"; then
        echo "[BLOCKED] guard.sh pre-push FAIL — push 거부 ($TASK_ID)" >&2
        exit 1
    fi
fi
exit 0
