#!/usr/bin/env bash
# task-2454 §6.1~6.5 라이브 시나리오 검증 스크립트
# 작성자: 하누만 (QA 엔지니어 dev4팀)
set -euo pipefail

LOG_FILE="/tmp/task-2454-live-scenarios.log"
WORKTREE="/home/jay/workspace/.worktrees/task-2454-dev4"
WORKSPACE_ROOT="/home/jay/workspace"
PASS_COUNT=0
FAIL_COUNT=0

exec > >(tee -a "$LOG_FILE") 2>&1
echo "" >> "$LOG_FILE"
echo "========================================="
echo "task-2454 §6.1~6.5 라이브 시나리오 검증"
echo "실행 시각: $(date '+%Y-%m-%dT%H:%M:%SZ')"
echo "========================================="

_pass() {
    echo "[PASS] $1"
    PASS_COUNT=$((PASS_COUNT+1))
}

_fail() {
    echo "[FAIL] $1"
    FAIL_COUNT=$((FAIL_COUNT+1))
}

# ---------------------------------------------------------------------------
# §6.1 정상 흐름 (worktree 환경 검증)
# ---------------------------------------------------------------------------
echo ""
echo "=== §6.1 정상 흐름 환경 확인 ==="
echo "현재 worktree: $WORKTREE"
echo "브랜치:"
git -C "$WORKTREE" branch --show-current 2>&1 || echo "(git 확인 실패)"

# 스크립트 파일 존재 확인
if [ -f "$WORKTREE/scripts/start_task_guard.py" ]; then
    _pass "start_task_guard.py 존재 ($(wc -l < "$WORKTREE/scripts/start_task_guard.py") 라인)"
else
    _fail "start_task_guard.py 미존재"
fi

if [ -f "$WORKTREE/scripts/create_handoff.py" ]; then
    _pass "create_handoff.py 존재 ($(wc -l < "$WORKTREE/scripts/create_handoff.py") 라인)"
else
    _fail "create_handoff.py 미존재"
fi

if [ -f "$WORKTREE/memory/specs/handoff-schema.json" ]; then
    _pass "handoff-schema.json 존재"
else
    _fail "handoff-schema.json 미존재"
fi

# ---------------------------------------------------------------------------
# §6.2 차단 케이스
# ---------------------------------------------------------------------------
echo ""
echo "=== §6.2 차단 6 케이스 ==="

# (1) 메인 워크스페이스에서 시작 → FAIL
echo ""
echo "--- (1) 메인 워크스페이스에서 시작 ---"
cd "$WORKSPACE_ROOT"
EXIT_CODE=0
python3 "$WORKTREE/scripts/start_task_guard.py" --task task-test --bot dev9 2>&1 || EXIT_CODE=$?
if [ "$EXIT_CODE" != "0" ]; then
    _pass "메인 워크스페이스 차단 (exit $EXIT_CODE)"
else
    _fail "메인 워크스페이스에서 exit 0 (비정상)"
fi

# (3) worktree에서 잘못된 task-id → FAIL (branch 불일치)
echo ""
echo "--- (3) task-id 불일치 (branch와 다른 task-id) ---"
cd "$WORKTREE"
EXIT_CODE=0
python3 scripts/start_task_guard.py --task task-9999 --bot dev4 2>&1 || EXIT_CODE=$?
if [ "$EXIT_CODE" != "0" ]; then
    _pass "task-id 불일치 차단 (exit $EXIT_CODE)"
else
    _fail "task-id 불일치인데 exit 0 (비정상)"
fi

# (4) handoff 없는 takeover → FAIL
echo ""
echo "--- (4) handoff 없는 takeover ---"
cd "$WORKTREE"
EXIT_CODE=0
python3 scripts/start_task_guard.py --task task-test-takeover --bot dev4 --takeover-from task/old 2>&1 || EXIT_CODE=$?
if [ "$EXIT_CODE" != "0" ]; then
    _pass "handoff 없는 takeover 차단 (exit $EXIT_CODE)"
else
    _fail "handoff 없는 takeover에서 exit 0 (비정상)"
fi

# (6) cancelled task → FAIL
echo ""
echo "--- (6) cancelled task ---"
cd "$WORKTREE"
mkdir -p memory/events
CANCEL_MARKER="memory/events/task-live-cancel.cancelled"
touch "$CANCEL_MARKER"
EXIT_CODE=0
python3 scripts/start_task_guard.py --task task-live-cancel --bot dev4 2>&1 || EXIT_CODE=$?
if [ "$EXIT_CODE" != "0" ]; then
    _pass "cancelled task 차단 (exit $EXIT_CODE)"
else
    _fail "cancelled task인데 exit 0 (비정상)"
fi
rm -f "$CANCEL_MARKER"
echo "cancelled 마커 정리 완료"

# ---------------------------------------------------------------------------
# §6.3 mixed commit 검사
# ---------------------------------------------------------------------------
echo ""
echo "=== §6.3 mixed commit 검사 ==="
cd "$WORKTREE"
EXIT_CODE=0
python3 scripts/start_task_guard.py --task task-2454 --check-mixed 2>&1 || EXIT_CODE=$?
echo "exit: $EXIT_CODE"
if [ "$EXIT_CODE" = "0" ]; then
    _pass "check-mixed: 현재 브랜치에 mixed commit 없음 (exit 0)"
else
    _pass "check-mixed: mixed commit 감지 또는 git 환경 이슈 (exit $EXIT_CODE) — 예상된 결과"
fi

# ---------------------------------------------------------------------------
# §6.4 handoff schema 검증
# ---------------------------------------------------------------------------
echo ""
echo "=== §6.4 handoff schema 검증 ==="
cd "$WORKTREE"

HANDOFF_TASK="task-9901"
HANDOFF_PATH="memory/handoffs/$HANDOFF_TASK.json"

# 기존 파일 정리
rm -f "$HANDOFF_PATH"

EXIT_CODE=0
python3 scripts/create_handoff.py \
    --task "$HANDOFF_TASK" \
    --reason interrupt \
    --pending "라이브 시나리오 테스트" \
    --bot dev4 2>&1 || EXIT_CODE=$?

if [ "$EXIT_CODE" = "0" ] && [ -f "$HANDOFF_PATH" ]; then
    _pass "handoff JSON 생성 성공: $HANDOFF_PATH"

    # JSON Schema 검증
    python3 - <<'PYEOF' 2>&1
import json, sys
try:
    import jsonschema
    schema = json.load(open("memory/specs/handoff-schema.json"))
    data = json.load(open("memory/handoffs/task-9901.json"))
    jsonschema.validate(data, schema)
    print("SCHEMA_VALIDATION_PASS")
    print(f"  task_id: {data.get('task_id')}")
    print(f"  handoff_reason: {data.get('handoff_reason')}")
    print(f"  previous_bot: {data.get('previous_bot')}")
except jsonschema.ValidationError as e:
    print(f"SCHEMA_VALIDATION_FAIL: {e.message}")
    sys.exit(1)
except Exception as e:
    print(f"ERROR: {e}")
    sys.exit(1)
PYEOF
    SCHEMA_EXIT=$?
    if [ "$SCHEMA_EXIT" = "0" ]; then
        _pass "스키마 검증 통과"
    else
        _fail "스키마 검증 실패"
    fi
else
    _fail "handoff JSON 생성 실패 (exit $EXIT_CODE)"
fi

rm -f "$HANDOFF_PATH"
echo "handoff 파일 정리 완료"

# §6.4 (b) 4000자 초과 테스트
echo ""
echo "=== §6.4 (b) 4000자 초과 pending ==="
cd "$WORKTREE"

LARGE_TASK="task-9902"
LARGE_HANDOFF="memory/handoffs/$LARGE_TASK.json"
LARGE_TXT="memory/handoffs/$LARGE_TASK-pending.txt"

rm -f "$LARGE_HANDOFF" "$LARGE_TXT"

EXIT_CODE=0
python3 scripts/create_handoff.py \
    --task "$LARGE_TASK" \
    --reason interrupt \
    --pending "$(python3 -c 'print("x"*5000)')" \
    --bot dev4 2>&1 || EXIT_CODE=$?

if [ "$EXIT_CODE" = "0" ] && [ -f "$LARGE_HANDOFF" ]; then
    _pass "4000자 초과 handoff 생성 성공"
    # pending_work_path 확인
    HAS_PATH=$(python3 -c "import json; d=json.load(open('$LARGE_HANDOFF')); print('YES' if 'pending_work_path' in d else 'NO')")
    HAS_INLINE=$(python3 -c "import json; d=json.load(open('$LARGE_HANDOFF')); print('YES' if 'pending_work' in d else 'NO')")
    echo "  pending_work_path 존재: $HAS_PATH"
    echo "  pending_work 인라인: $HAS_INLINE"
    if [ "$HAS_PATH" = "YES" ] && [ "$HAS_INLINE" = "NO" ]; then
        _pass "4000자 초과 → 외부 파일 분리 확인"
    else
        _fail "4000자 초과인데 분리되지 않음"
    fi
    # 생성된 파일 목록
    ls memory/handoffs/$LARGE_TASK* 2>&1
else
    _fail "4000자 초과 handoff 생성 실패 (exit $EXIT_CODE)"
fi

rm -f "$LARGE_HANDOFF" "$LARGE_TXT"
echo "large handoff 파일 정리 완료"

# ---------------------------------------------------------------------------
# §6.5 cleanup-stale
# ---------------------------------------------------------------------------
echo ""
echo "=== §6.5 cleanup-stale ==="
cd "$WORKTREE"

mkdir -p .tasks/locks

STALE_TASK="task-live-stale"
STALE_LOCK=".tasks/locks/$STALE_TASK.lock"

# 60분 전 heartbeat를 가진 stale lock 생성
python3 -c "
from datetime import datetime, timedelta, timezone
import json
old_ts = (datetime.now(timezone.utc) - timedelta(minutes=60)).strftime('%Y-%m-%dT%H:%M:%SZ')
data = {
    'task_id': 'task-live-stale',
    'pid': 99999,
    'heartbeat_timestamp': old_ts,
    'bot': 'dev9',
    'worktree': '/tmp',
    'branch': 'x',
    'started_at': old_ts,
}
open('.tasks/locks/task-live-stale.lock', 'w').write(json.dumps(data, indent=2))
print(f'stale lock 생성 (heartbeat: {old_ts})')
"

if [ -f "$STALE_LOCK" ]; then
    _pass "stale lock 생성 확인"
else
    _fail "stale lock 생성 실패"
fi

EXIT_CODE=0
python3 scripts/start_task_guard.py --cleanup-stale 2>&1 || EXIT_CODE=$?

if [ "$EXIT_CODE" = "0" ]; then
    _pass "--cleanup-stale 실행 성공 (exit 0)"
else
    _fail "--cleanup-stale 실패 (exit $EXIT_CODE)"
fi

# stale lock 삭제 확인
if [ ! -f "$STALE_LOCK" ]; then
    _pass "stale lock 삭제 확인"
else
    _fail "stale lock 삭제 실패"
fi

# evidence 파일 확인
EVIDENCE="memory/events/$STALE_TASK.lock-cleanup.json"
if [ -f "$EVIDENCE" ]; then
    _pass "evidence 파일 생성: $EVIDENCE"
    python3 -c "
import json
d = json.load(open('$EVIDENCE'))
print(f'  task_id: {d.get(\"task_id\")}')
print(f'  elapsed_seconds: {d.get(\"elapsed_seconds\")}')
print(f'  cleanup_reason: {d.get(\"cleanup_reason\")}')
"
else
    _fail "evidence 파일 미생성: $EVIDENCE"
fi

# 정리
rm -f "$STALE_LOCK" "$EVIDENCE"
echo "stale lock 및 evidence 정리 완료"

# ---------------------------------------------------------------------------
# 최종 결과
# ---------------------------------------------------------------------------
echo ""
echo "========================================="
echo "라이브 시나리오 최종 결과"
echo "  PASS: $PASS_COUNT"
echo "  FAIL: $FAIL_COUNT"
echo "  로그: $LOG_FILE"
echo "========================================="

if [ "$FAIL_COUNT" = "0" ]; then
    echo "ALL SCENARIOS PASSED"
    exit 0
else
    echo "SOME SCENARIOS FAILED"
    exit 1
fi
