#!/usr/bin/env bash
# task-2449 Fix 3: pre-push hook — taskctl 강제 + main direct push 거부
# 설치: git config core.hooksPath scripts/git-hooks
#
# 단계:
#   1) main direct push 거부 (회장 절대 기준)
#   2) refspec 검사 (다른 브랜치에서 main으로 push 시도 거부)
#   3) cancelled marker 차단
#   4) taskctl status 조회 → state=CANCELLED → 거부
#   5) guard.sh pre-push 강제
set -e

WORKSPACE="$(git rev-parse --show-toplevel)"
export WORKSPACE  # guard.sh / pre_push_guard.py가 본 worktree를 root로 인식
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
TASKCTL="$WORKSPACE/scripts/taskctl.py"

# 1) main direct push 자체 거부
if [[ "$CURRENT_BRANCH" == "main" ]]; then
    echo "[BLOCKED] main direct push prohibited. Use taskctl merge." >&2
    echo "[BLOCKED] 회장 절대 기준: taskctl을 거치지 않고는 main을 절대 변경할 수 없다." >&2
    exit 1
fi

# 2) refspec 검사: 어떤 브랜치에서든 origin/main 으로 push 시도 거부
# git push --hook 입력은 stdin으로 들어옴: <local_ref> <local_sha> <remote_ref> <remote_sha>
while read -r LOCAL_REF LOCAL_SHA REMOTE_REF REMOTE_SHA; do
    [[ -z "$REMOTE_REF" ]] && continue
    if [[ "$REMOTE_REF" == "refs/heads/main" ]]; then
        echo "[BLOCKED] main direct push prohibited (refspec=$REMOTE_REF). Use taskctl merge." >&2
        exit 1
    fi
done < /dev/stdin || true

# 3) task branch 추출 + cancelled marker
TASK_ID=$(echo "$CURRENT_BRANCH" | grep -oE 'task-[0-9]+' | head -n1 || true)
if [[ -z "$TASK_ID" ]]; then
    LAST_MSG=$(git log -1 --pretty=%B 2>/dev/null || true)
    TASK_ID=$(echo "$LAST_MSG" | grep -oE 'task-[0-9]+' | head -n1 || true)
fi

if [[ -n "$TASK_ID" ]]; then
    if [[ -f "$WORKSPACE/memory/events/${TASK_ID}.cancelled" ]]; then
        echo "[BLOCKED] task $TASK_ID cancelled (marker exists) — push 거부" >&2
        exit 1
    fi
    # 4) taskctl status 조회
    if [[ -f "$TASKCTL" ]]; then
        STATE_OUT=$(python3 "$TASKCTL" status "$TASK_ID" --machine 2>/dev/null || true)
        if [[ -n "$STATE_OUT" ]]; then
            CURRENT_STATE=$(echo "$STATE_OUT" | python3 -c "
import json, sys
try:
    d = json.loads(sys.stdin.read())
    print(d.get('current_state') or '')
except Exception:
    pass
" 2>/dev/null || true)
            if [[ "$CURRENT_STATE" == "CANCELLED" ]]; then
                echo "[BLOCKED] task $TASK_ID state=CANCELLED (taskctl) — push 거부" >&2
                exit 1
            fi
            # 미초기화/모름은 경고 없이 통과 (MVP 신뢰 모델)
        fi
    fi
    # 5) guard.sh pre-push 강제 (기존 거버넌스 보존)
    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
