#!/usr/bin/env bash
# ================================================================
# Scenario 2a: Real-Time PR Gatekeeper (Webhook 触发)
# Flow: Webhook 推送 PR → 拉取详情 → AI Review → 查 CI → 发评论 → 达标自动合并
# ================================================================
set -eo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
source "$SCRIPT_DIR/lib/common.sh"

PR_ID=""
OWNER=""
REPO=""
THRESHOLD=80
DRY_RUN=false

usage() {
    echo "Usage: $0 --pr-id N [--owner OWNER] [--repo REPO] [--threshold SCORE] [--dry-run]"
    exit 1
}

while [[ $# -gt 0 ]]; do
    case "$1" in
        --pr-id)      PR_ID="$2"; shift 2 ;;
        --owner)      OWNER="$2"; shift 2 ;;
        --repo)       REPO="$2"; shift 2 ;;
        --threshold)  THRESHOLD="$2"; shift 2 ;;
        --dry-run)    DRY_RUN="true"; shift ;;
        --help|-h)    usage ;;
        *)            log_err "Unknown arg: $1"; usage ;;
    esac
done

[[ -z "$PR_ID" ]] && { log_err "--pr-id is required"; usage; }

check_auth
require_owner_repo

# ================================================================
log_title "PR Gatekeeper: #$PR_ID ($OWNER/$REPO)"

# ── Step 1: 拉取 PR 详情 ─────────────────────────────────────────
log_step "Fetching PR details..."
PR_JSON=$(gl_check pr +view --owner "$OWNER" --repo "$REPO" --id "$PR_ID")
[[ -z "$PR_JSON" ]] && { log_err "Failed to fetch PR #$PR_ID"; exit 1; }

PR_TITLE=$(echo "$PR_JSON" | jq -r '.data.title // .data.subject // .data.issue.subject // "N/A"')
PR_STATE=$(echo "$PR_JSON" | jq -r '.data.state // .data.status // "N/A"')
PR_AUTHOR=$(echo "$PR_JSON" | jq -r '.data.author.login // .data.author.username // .data.issue.author.login // "N/A"')
ISSUE_ID=$(echo "$PR_JSON" | jq -r '.data.id // .data.issue.id // empty')
PR_HEAD=$(echo "$PR_JSON" | jq -r '.data.pull_request.head // empty')
log_ok "PR #$PR_ID: \"$PR_TITLE\" by @$PR_AUTHOR (state: $PR_STATE, branch: $PR_HEAD)"

# ── Step 2: 获取变更文件列表 ──────────────────────────────────────
log_step "Fetching changed files..."
FILES_JSON=$(gl_run pr +files --owner "$OWNER" --repo "$REPO" --id "$PR_ID")
FILE_COUNT=0
if echo "$FILES_JSON" | jq empty 2>/dev/null; then
    FILE_COUNT=$(echo "$FILES_JSON" | jq '.data.files | length' 2>/dev/null || echo "0")
fi
log_ok "Changed files: $FILE_COUNT"

FILE_LIST=""
if [[ "$FILE_COUNT" -gt 0 ]] && [[ "$FILE_COUNT" != "null" ]]; then
    for i in $(seq 0 $((FILE_COUNT - 1))); do
        FNAME=$(echo "$FILES_JSON" | jq -r ".data.files[$i].name // .data.files[$i].filename // \"unknown\"" 2>/dev/null || echo "unknown")
        echo "    $FNAME"
        FILE_LIST+="- $FNAME"$'\n'
    done
fi

# ── Step 3: 获取 diff ────────────────────────────────────────────
log_step "Fetching diff..."
DIFF_JSON=$(gl_run pr +diff --owner "$OWNER" --repo "$REPO" --id "$PR_ID")
DIFF_CONTENT=""
if echo "$DIFF_JSON" | jq empty 2>/dev/null; then
    DIFF_CONTENT=$(echo "$DIFF_JSON" | jq -r '
        [.data.files[]?.sections[]?.lines[]?.content // empty] | join("\n")
    ' 2>/dev/null | head -c 5000 || true)
fi
DIFF_LINES=$(echo "$DIFF_CONTENT" | wc -l)
log_ok "Diff: $DIFF_LINES lines"

# ── Step 4: AI 代码审查 ───────────────────────────────────────────
log_step "AI analyzing code quality..."

DIFF_TRUNCATED=$(echo "$DIFF_CONTENT" | head -c 4000)

# Load skill dimensions from SKILL.md
SKILL_DIR="$SCRIPT_DIR/../skills/gitlink-code-review"
SKILL_DIMENSIONS=""
if [[ -f "$SKILL_DIR/SKILL.md" ]]; then
    SKILL_DIMENSIONS=$(sed -n '/^## 📊 审查维度/,/^## 🔧 使用方式/p' "$SKILL_DIR/SKILL.md" | grep '^\- \*\*' | head -20)
fi

REVIEW_PROMPT="你是代码审查专家。请按 gitlink-code-review skill 的审查维度分析以下 PR。

## 审查维度与检查项

${SKILL_DIMENSIONS:-1. 代码质量: 复杂度、命名、注释、格式
2. 安全性: SQL注入、XSS、敏感信息、认证、输入验证
3. 性能: 循环效率、资源泄漏、N+1查询、内存
4. 可维护性: 代码重复、职责单一、依赖耦合、测试覆盖}

## 评分标准
- 90-100: 优秀，可直接合并
- 75-89: 良好，建议合并
- 60-74: 一般，需要改进
- <60: 较差，不建议合并

## 问题严重级别
- CRITICAL: 阻止合并
- HIGH: 强烈建议修复
- MEDIUM: 建议修复
- LOW: 可选修复

## PR 数据

PR 标题: $PR_TITLE
变更文件:
$FILE_LIST
代码差异:
$DIFF_TRUNCATED

## 输出要求

请严格按以下 JSON 格式输出，不要输出其他内容:
{\"total\": <0-100>, \"quality\": <0-25>, \"security\": <0-25>, \"performance\": <0-25>, \"maintainability\": <0-25>, \"issues\": [{\"severity\": \"HIGH/MEDIUM/LOW\", \"category\": \"quality/security/performance/maintainability\", \"file\": \"文件路径\", \"rule\": \"规则名\", \"description\": \"问题描述\", \"suggestion\": \"修复建议\"}], \"positive_notes\": [{\"description\": \"优秀实践描述\"}], \"recommendations\": [\"改进建议1\"], \"verdict\": \"PASS或FAIL\"}"

AI_AVAILABLE=false
SCORE_QUALITY=25
SCORE_SECURITY=25
SCORE_PERFORMANCE=25
SCORE_MAINTAINABILITY=25
ISSUES_FOUND=()
AI_POSITIVE=()
AI_RECOMMENDATIONS=()
TOTAL_SCORE=0

if command -v claude &>/dev/null; then
    log_info "Calling AI agent for code review (may take 30-60s)..."
    PROMPT_FILE=$(mktemp)
    AI_OUT_FILE=$(mktemp)
    echo "$REVIEW_PROMPT" > "$PROMPT_FILE"

    if [[ -z "${CLAUDE_CODE_GIT_BASH_PATH:-}" ]] && command -v cygpath &>/dev/null; then
        export CLAUDE_CODE_GIT_BASH_PATH="$(cygpath -w "$(which bash)")"
    fi

    AI_EXIT=0
    (cat "$PROMPT_FILE" | timeout 300 claude -p --output-format json > "$AI_OUT_FILE" 2>/dev/null) || AI_EXIT=$?

    if [[ $AI_EXIT -eq 0 ]] && [[ -s "$AI_OUT_FILE" ]]; then
        AI_RESULT=$(jq -r '.result // empty' "$AI_OUT_FILE" 2>/dev/null)
    else
        log_warn "AI call failed (exit: $AI_EXIT), falling back to keyword-based"
        AI_RESULT=""
    fi
    rm -f "$PROMPT_FILE" "$AI_OUT_FILE"

    if [[ -n "$AI_RESULT" ]]; then
        AI_JSON=""
        if command -v python3 &>/dev/null; then
            AI_JSON=$(python3 -c "
import sys, json
text = sys.stdin.read()
depth = 0
start = -1
results = []
for i, c in enumerate(text):
    if c == '{':
        if depth == 0: start = i
        depth += 1
    elif c == '}':
        depth -= 1
        if depth == 0 and start >= 0:
            results.append(text[start:i+1])
            start = -1
for m in reversed(results):
    try:
        obj = json.loads(m)
        if 'total' in obj and 'verdict' in obj:
            print(json.dumps(obj))
            break
    except: pass
" <<< "$AI_RESULT" 2>/dev/null)
        fi
        if [[ -z "$AI_JSON" ]]; then
            AI_JSON=$(echo "$AI_RESULT" | grep -oP '\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}' | tail -1)
        fi

        if [[ -n "$AI_JSON" ]] && echo "$AI_JSON" | jq empty 2>/dev/null; then
            TOTAL_SCORE=$(echo "$AI_JSON" | jq -r '.total // 0' 2>/dev/null)
            SCORE_QUALITY=$(echo "$AI_JSON" | jq -r '.quality // 0' 2>/dev/null)
            SCORE_SECURITY=$(echo "$AI_JSON" | jq -r '.security // 0' 2>/dev/null)
            SCORE_PERFORMANCE=$(echo "$AI_JSON" | jq -r '.performance // 0' 2>/dev/null)
            SCORE_MAINTAINABILITY=$(echo "$AI_JSON" | jq -r '.maintainability // 0' 2>/dev/null)
            AI_VERDICT=$(echo "$AI_JSON" | jq -r '.verdict // "PASS"' 2>/dev/null)

            ISSUE_COUNT=$(echo "$AI_JSON" | jq '.issues | length' 2>/dev/null || echo "0")
            if [[ "$ISSUE_COUNT" -gt 0 ]] && [[ "$ISSUE_COUNT" != "null" ]]; then
                for idx in $(seq 0 $((ISSUE_COUNT - 1))); do
                    issue=$(echo "$AI_JSON" | jq -r '
                        if .issues['"$idx"'] | type == "object" then
                            "[" + (.issues['"$idx"'].severity // "?") + "] " +
                            (.issues['"$idx"'].category // "?") + ": " +
                            (.issues['"$idx"'].description // .issues['"$idx"'].rule // "unknown") +
                            (if .issues['"$idx"'].file then " (" + .issues['"$idx"'].file + ")" else "" end) +
                            (if .issues['"$idx"'].suggestion then " -> " + .issues['"$idx"'].suggestion else "" end)
                        else .issues['"$idx"'] // empty end' 2>/dev/null)
                    [[ -n "$issue" ]] && ISSUES_FOUND+=("$issue")
                done
            fi

            POS_COUNT=$(echo "$AI_JSON" | jq '.positive_notes | length' 2>/dev/null || echo "0")
            if [[ "$POS_COUNT" -gt 0 ]] && [[ "$POS_COUNT" != "null" ]]; then
                for idx in $(seq 0 $((POS_COUNT - 1))); do
                    note=$(echo "$AI_JSON" | jq -r '.positive_notes['"$idx"'].description // empty' 2>/dev/null)
                    [[ -n "$note" ]] && AI_POSITIVE+=("$note")
                done
            fi

            REC_COUNT=$(echo "$AI_JSON" | jq '.recommendations | length' 2>/dev/null || echo "0")
            if [[ "$REC_COUNT" -gt 0 ]] && [[ "$REC_COUNT" != "null" ]]; then
                for idx in $(seq 0 $((REC_COUNT - 1))); do
                    rec=$(echo "$AI_JSON" | jq -r '.recommendations['"$idx"'] // empty' 2>/dev/null)
                    [[ -n "$rec" ]] && AI_RECOMMENDATIONS+=("$rec")
                done
            fi

            AI_AVAILABLE=true
            log_ok "AI review complete (verdict: $AI_VERDICT)"
        else
            log_warn "Could not parse AI response JSON, falling back to keyword-based"
        fi
    fi
fi

# Fallback: keyword-based heuristics
if [[ "$AI_AVAILABLE" != "true" ]]; then
    log_warn "AI not available, falling back to keyword-based analysis"

    SCORE_QUALITY=25
    SCORE_SECURITY=25
    SCORE_PERFORMANCE=25
    SCORE_MAINTAINABILITY=25
    ISSUES_FOUND=()

    if echo "$DIFF_CONTENT" | grep -qiE 'password|secret|token|api_key|apikey|private_key'; then
        SCORE_SECURITY=$((SCORE_SECURITY - 15))
        ISSUES_FOUND+=("SECURITY: 检测到可能的硬编码凭证")
    fi
    if echo "$DIFF_CONTENT" | grep -qiE 'eval\(|exec\(|system\(|shell_exec|os\.system|subprocess\.call'; then
        SCORE_SECURITY=$((SCORE_SECURITY - 10))
        ISSUES_FOUND+=("SECURITY: 检测到危险函数调用")
    fi
    if echo "$DIFF_CONTENT" | grep -qiE 'TODO|FIXME|HACK|XXX'; then
        SCORE_QUALITY=$((SCORE_QUALITY - 5))
        ISSUES_FOUND+=("QUALITY: 存在 TODO/FIXME/HACK 注释")
    fi
    if echo "$DIFF_CONTENT" | grep -qiE 'SELECT \*|\.findAll\(\)|\.all\(\)'; then
        SCORE_PERFORMANCE=$((SCORE_PERFORMANCE - 10))
        ISSUES_FOUND+=("PERFORMANCE: 可能的全表查询")
    fi
    if echo "$DIFF_CONTENT" | grep -qiE 'sleep\(|time\.sleep|Thread\.sleep'; then
        SCORE_PERFORMANCE=$((SCORE_PERFORMANCE - 5))
        ISSUES_FOUND+=("PERFORMANCE: 检测到阻塞式 sleep")
    fi
    if [[ "$FILE_COUNT" -gt 20 ]]; then
        SCORE_MAINTAINABILITY=$((SCORE_MAINTAINABILITY - 10))
        ISSUES_FOUND+=("MAINTAINABILITY: 变更文件数量过多 ($FILE_COUNT)")
    fi

    TOTAL_SCORE=$((SCORE_QUALITY + SCORE_SECURITY + SCORE_PERFORMANCE + SCORE_MAINTAINABILITY))
    TOTAL_SCORE=$((TOTAL_SCORE < 0 ? 0 : TOTAL_SCORE))
fi

# ── 打印审查报告 ──────────────────────────────────────────────────
divider
if [[ "$AI_AVAILABLE" == "true" ]]; then
    log_info "AI Review Report for PR #$PR_ID"
else
    log_info "Review Report for PR #$PR_ID (keyword-based)"
fi
echo ""
echo "  Overall Score:        $TOTAL_SCORE / 100"
echo "  Code Quality:         $SCORE_QUALITY / 25"
echo "  Security:             $SCORE_SECURITY / 25"
echo "  Performance:          $SCORE_PERFORMANCE / 25"
echo "  Maintainability:      $SCORE_MAINTAINABILITY / 25"
echo ""

if [[ ${#ISSUES_FOUND[@]} -gt 0 ]]; then
    echo "  Issues Found:"
    for issue in "${ISSUES_FOUND[@]}"; do
        echo "    - $issue"
    done
    echo ""
fi

if [[ "${#AI_POSITIVE[@]}" -gt 0 ]]; then
    echo "  Positive Notes:"
    for note in "${AI_POSITIVE[@]}"; do
        echo "    + $note"
    done
    echo ""
fi

if [[ "${#AI_RECOMMENDATIONS[@]}" -gt 0 ]]; then
    echo "  Recommendations:"
    for rec in "${AI_RECOMMENDATIONS[@]}"; do
        echo "    > $rec"
    done
    echo ""
fi

# ── Step 5: 发布审查评论 ──────────────────────────────────────────
if [[ "$AI_AVAILABLE" == "true" ]]; then
    REVIEW_HEADER="## AI Code Quality Review - PR #$PR_ID"
else
    REVIEW_HEADER="## Code Quality Review - PR #$PR_ID (keyword-based)"
fi

REVIEW_BODY="$REVIEW_HEADER

### Scores
| Dimension | Score | Max |
|-----------|-------|-----|
| Code Quality | $SCORE_QUALITY | 25 |
| Security | $SCORE_SECURITY | 25 |
| Performance | $SCORE_PERFORMANCE | 25 |
| Maintainability | $SCORE_MAINTAINABILITY | 25 |
| **Total** | **$TOTAL_SCORE** | **100** |

### Issues Found"

if [[ ${#ISSUES_FOUND[@]} -gt 0 ]]; then
    for issue in "${ISSUES_FOUND[@]}"; do
        REVIEW_BODY+=$'\n'"- $issue"
    done
else
    REVIEW_BODY+=$'\n'"No issues found."
fi

if [[ "${#AI_POSITIVE[@]}" -gt 0 ]]; then
    REVIEW_BODY+=$'\n'$'\n'"### Positive Notes"
    for note in "${AI_POSITIVE[@]}"; do
        REVIEW_BODY+=$'\n'"- $note"
    done
fi

if [[ "${#AI_RECOMMENDATIONS[@]}" -gt 0 ]]; then
    REVIEW_BODY+=$'\n'$'\n'"### Recommendations"
    for rec in "${AI_RECOMMENDATIONS[@]}"; do
        REVIEW_BODY+=$'\n'"- $rec"
    done
fi

REVIEW_BODY+="

### Verdict
$(if [[ $TOTAL_SCORE -ge $THRESHOLD ]]; then echo "**PASS** - Score $TOTAL_SCORE >= threshold $THRESHOLD. Ready to merge."; else echo "**FAIL** - Score $TOTAL_SCORE < threshold $THRESHOLD. Please address the issues above."; fi)

---
*Auto-reviewed by gitlink-cli code-quality-gatekeeper workflow (skill: gitlink-code-review)*"

log_step "Posting review comment..."
REVIEW_JSON=$(jq -n --arg notes "$REVIEW_BODY" '{notes: $notes}')
REVIEW_RESULT=$(gl_run api POST "/v1/$OWNER/$REPO/issues/$ISSUE_ID/journals" \
    --body "$REVIEW_JSON" 2>&1) || true

if [[ "$(json_ok "$REVIEW_RESULT")" == "true" ]]; then
    log_ok "Review comment posted"
else
    log_warn "Review comment may have failed"
fi

# ── Step 6: 本地 CI (编译 + 测试) ─────────────────────────────────
log_step "Running local CI: build & test..."

REPOS_DIR="/opt/gitlink-webhook/repos"
REPO_CLONE_DIR="$REPOS_DIR/$REPO"
GIT_URL="https://www.gitlink.org.cn/${OWNER}/${REPO}.git"

BUILD_LOG=$(mktemp)
TEST_LOG=$(mktemp)
CI_BUILD_PASSED=false
CI_TEST_PASSED=false
CI_PASSED=false

if [[ -z "$PR_HEAD" ]]; then
    log_warn "Cannot determine PR head branch, skipping CI"
    CI_BUILD_OUTPUT="CI skipped: unknown PR branch"
    CI_TEST_OUTPUT="CI skipped: unknown PR branch"
else
    # Clone repo if not exists, otherwise fetch latest
    if [[ ! -d "$REPO_CLONE_DIR/.git" ]]; then
        mkdir -p "$REPOS_DIR"
        log_info "Cloning $GIT_URL..."
        git clone "$GIT_URL" "$REPO_CLONE_DIR" 2>&1 || true
    fi

    {
        cd "$REPO_CLONE_DIR"
        log_info "Fetching and checking out branch '$PR_HEAD'..."
        git fetch origin 2>&1 || true
        git checkout "$PR_HEAD" 2>&1 || true
        git pull origin "$PR_HEAD" 2>&1 || true

        log_info "Running: go build ./..."
        if go build ./... >> "$BUILD_LOG" 2>&1; then
            CI_BUILD_PASSED=true
            log_ok "Build passed"
        else
            log_err "Build failed"
        fi

        log_info "Running: go test ./..."
        if go test ./... >> "$TEST_LOG" 2>&1; then
            CI_TEST_PASSED=true
            log_ok "Tests passed"
        else
            log_err "Tests failed"
        fi
    }

    CI_BUILD_OUTPUT=$(tail -c 3000 "$BUILD_LOG" 2>/dev/null || echo "no output")
    CI_TEST_OUTPUT=$(tail -c 3000 "$TEST_LOG" 2>/dev/null || echo "no output")
fi

if $CI_BUILD_PASSED && $CI_TEST_PASSED; then
    CI_PASSED=true
    CI_SUMMARY="| Build | PASSED | | |\n| Tests | PASSED | | |"
elif $CI_BUILD_PASSED && ! $CI_TEST_PASSED; then
    CI_SUMMARY="| Build | PASSED | | |\n| Tests | **FAILED** | | |"
elif ! $CI_BUILD_PASSED && $CI_TEST_PASSED; then
    CI_SUMMARY="| Build | **FAILED** | | |\n| Tests | PASSED | | |"
else
    CI_SUMMARY="| Build | **FAILED** | | |\n| Tests | **FAILED** | | |"
fi

# Post CI results as a follow-up comment
log_step "Posting CI results..."
CI_BODY="## CI Results - PR #$PR_ID

### Build & Test
| Stage | Status |
|-------|--------|
$CI_SUMMARY

### Build Output
\`\`\`
$(echo "$CI_BUILD_OUTPUT" | tail -20)
\`\`\`

### Test Output
\`\`\`
$(echo "$CI_TEST_OUTPUT" | tail -20)
\`\`\`

---
*Local CI executed on server*"

CI_COMMENT_JSON=$(jq -n --arg notes "$CI_BODY" '{notes: $notes}')
CI_RESULT=$(gl_run api POST "/v1/$OWNER/$REPO/issues/$ISSUE_ID/journals" \
    --body "$CI_COMMENT_JSON" 2>&1) || true

if [[ "$(json_ok "$CI_RESULT")" == "true" ]]; then
    log_ok "CI results posted"
else
    log_warn "CI results post may have failed"
fi

rm -f "$BUILD_LOG" "$TEST_LOG"

# ── Step 7: 冲突检测 + 自动合并 ───────────────────────────────────
MERGED=false
MERGE_RESULT_MSG=""
CONFLICT_DETECTED=false

# Build merge summary: determine why merge can/cannot proceed
MERGE_BLOCK_REASONS=()
if [[ $TOTAL_SCORE -lt $THRESHOLD ]]; then
    MERGE_BLOCK_REASONS+=("score $TOTAL_SCORE < threshold $THRESHOLD")
fi
if [[ "$CI_PASSED" != "true" ]]; then
    MERGE_BLOCK_REASONS+=("CI not passed")
fi

if [[ ${#MERGE_BLOCK_REASONS[@]} -gt 0 ]]; then
    # Cannot merge: log reasons
    BLOCK_LIST=$(printf '; %s' "${MERGE_BLOCK_REASONS[@]}")
    BLOCK_LIST="${BLOCK_LIST:2}"
    log_warn "Merge blocked: $BLOCK_LIST"
else
    log_step "Score $TOTAL_SCORE >= $THRESHOLD and CI passed — checking mergeability..."

    # Check for merge conflicts
    if [[ -d "$REPO_CLONE_DIR/.git" ]]; then
        log_info "Checking merge conflicts with base branch..."
        (
            cd "$REPO_CLONE_DIR"
            # Ensure git identity is set for merge test
            git config user.email "gatekeeper@gitlink-cli.local" 2>&1 || true
            git config user.name "gitlink-gatekeeper" 2>&1 || true
            git fetch origin 2>&1 || true
            # Determine base branch from PR data
            BASE_BRANCH=$(echo "$PR_JSON" | jq -r '.data.pull_request.base // .data.base // "master"')
            git checkout "$BASE_BRANCH" 2>&1 || true
            git pull origin "$BASE_BRANCH" 2>&1 || true
            # Test merge without committing
            if git merge --no-commit --no-ff "$PR_HEAD" 2>&1; then
                log_ok "No merge conflicts detected"
                git merge --abort 2>&1 || true
                CONFLICT_DETECTED=false
            else
                CONFLICT_DETECTED=true
                CONFLICT_FILES=$(git diff --name-only --diff-filter=U 2>/dev/null || echo "unknown")
                log_err "Merge conflict detected in: $CONFLICT_FILES"
                git merge --abort 2>&1 || true
            fi
            git checkout "$PR_HEAD" 2>&1 || true
        )
    else
        log_info "Skipping conflict check (repo not cloned)"
    fi

    if [[ "$CONFLICT_DETECTED" == "true" ]]; then
        MERGE_RESULT_MSG="Merge blocked: conflicts detected"
        log_err "$MERGE_RESULT_MSG"
    elif [[ "$DRY_RUN" == "true" ]]; then
        MERGE_RESULT_MSG="[DRY RUN] Would auto-merge"
        log_warn "$MERGE_RESULT_MSG"
    else
        log_step "Auto-merging PR #$PR_ID..."
        MERGE_OUT=$(gl_run pr +merge --owner "$OWNER" --repo "$REPO" --id "$PR_ID" --method merge 2>&1) || true
        if [[ "$(json_ok "$MERGE_OUT")" == "true" ]]; then
            MERGED=true
            MERGE_RESULT_MSG="Merge succeeded"
            log_ok "PR #$PR_ID merged successfully!"
        else
            MERGE_RESULT_MSG="Merge failed: $(json_error "$MERGE_OUT")"
            log_err "$MERGE_RESULT_MSG"
        fi
    fi
fi

# ── Step 8: 发布最终汇总评论 ──────────────────────────────────────
log_step "Posting final summary..."

FINAL_BODY="## Gatekeeper Summary - PR #$PR_ID

| Item | Detail |
|------|--------|
| Score | **$TOTAL_SCORE / 100** (threshold: $THRESHOLD) |
| CI Build | $([[ "$CI_BUILD_PASSED" == "true" ]] && echo "PASSED" || echo "FAILED") |
| CI Test | $([[ "$CI_TEST_PASSED" == "true" ]] && echo "PASSED" || echo "FAILED") |
| Merge Conflict | $([[ "$CONFLICT_DETECTED" == "true" ]] && echo "**DETECTED**" || echo "None") |
| Result | $([[ "$MERGED" == "true" ]] && echo "**MERGED**" || echo "$MERGE_RESULT_MSG") |
"

if [[ ${#MERGE_BLOCK_REASONS[@]} -gt 0 ]]; then
    FINAL_BODY+="
### Blocked Reasons
"
    for reason in "${MERGE_BLOCK_REASONS[@]}"; do
        FINAL_BODY+="- $reason
"
    done
fi

if [[ "$CONFLICT_DETECTED" == "true" ]]; then
    FINAL_BODY+="
### Conflict Files
\`\`\`
$CONFLICT_FILES
\`\`\`
"
fi

FINAL_BODY+="
---
*Gatekeeper workflow completed at $(date '+%Y-%m-%d %H:%M:%S')*"

FINAL_JSON=$(jq -n --arg notes "$FINAL_BODY" '{notes: $notes}')
FINAL_RESULT=$(gl_run api POST "/v1/$OWNER/$REPO/issues/$ISSUE_ID/journals" \
    --body "$FINAL_JSON" 2>&1) || true

if [[ "$(json_ok "$FINAL_RESULT")" == "true" ]]; then
    log_ok "Final summary posted"
else
    log_warn "Final summary post may have failed"
fi

# ── Complete ──────────────────────────────────────────────────────
log_title "Gatekeeper Complete"
echo -e "${GREEN}  PR:         #$PR_ID - $PR_TITLE${NC}"
echo -e "${GREEN}  Author:     @$PR_AUTHOR${NC}"
echo -e "${GREEN}  Score:      $TOTAL_SCORE / 100${NC}"
echo -e "${GREEN}  CI Passed:  $CI_PASSED${NC}"
echo -e "${GREEN}  Conflict:   $CONFLICT_DETECTED${NC}"
echo -e "${GREEN}  Merged:     $( [[ "$MERGED" == "true" ]] && echo 'YES' || echo 'NO')${NC}"
