#!/usr/bin/env bash
# ============================================================
# GitLink 科研辅助 — 场景 1：仓库级科研项目洞察
# ============================================================
# 对单个 GitLink 仓库深度分析：项目定位、技术栈、活动健康、
# 贡献者网络、热度评分，生成综合 HTML 报告 + Wiki 页面
# ============================================================

set -euo pipefail
trap '' PIPE

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

# ── Configuration ────────────────────────────────────────────────────
OUTPUT_DIR="${SCRIPT_DIR}/../../output"
OUTPUT_FILE=""
PUBLISH_WIKI="true"

usage() {
    cat <<'EOF'
Usage: 06-research-insights.sh --owner <owner> --repo <repo> [options]

Options:
  --owner <owner>       Repository owner (required)
  --repo <repo>         Repository name (required)
  --output <file>       Output HTML file path (default: output/research-insights-{repo}-{date}.html)
  --no-wiki             Skip publishing to Wiki
  --dry-run             Preview mode

Examples:
  06-research-insights.sh --owner zzx-coder --repo gitlink-cli
EOF
    exit 0
}

parse_common_args "$@"
while [[ $# -gt 0 ]]; do
    case "$1" in
        --output)    OUTPUT_FILE="$2"; shift 2 ;;
        --no-wiki)   PUBLISH_WIKI="false"; shift ;;
        *)           shift ;;
    esac
done

# ── Helper: count array elements in JSON ──────────────────────────────
json_count() {
    echo "$1" | jq -r "$2 | length" 2>/dev/null || echo "0"
}

# ── Helper: extract keywords from text ────────────────────────────────
extract_topics() {
    local text="$1"
    local topics=""
    for kw in "machine learning" "deep learning" "neural network" "NLP" "computer vision" \
              "reinforcement learning" "GAN" "transformer" "LLM" "RAG" "agent" \
              "bioinformatics" "genomics" "computational biology" "drug discovery" \
              "robotics" "autonomous" "simulation" "optimization" "benchmark" \
              "dataset" "pre-trained" "fine-tuning" "distributed" "federated" \
              "graph neural" "knowledge graph" "recommender" "anomaly detection" \
              "scientific computing" "high performance" "HPC" "quantum" \
              "climate" "weather" "physics" "chemistry" "materials" \
              "machine learning" "深度学习" "神经网络" "自然语言" "计算机视觉" \
              "机器学习" "强化学习" "大语言模型" "知识图谱" "推荐系统"; do
        if echo "$text" | grep -qi "$kw"; then
            topics="${topics}${kw}, "
        fi
    done
    echo "${topics%, }"
}

# ── Main ─────────────────────────────────────────────────────────────
main() {
    log_title "GitLink 科研辅助 — 仓库级项目洞察"

    check_auth
    require_owner_repo
    local today
    today=$(date_today)
    mkdir -p "$OUTPUT_DIR"

    local REPO_FULL="${OWNER}/${REPO}"
    OUTPUT_FILE="${OUTPUT_FILE:-${OUTPUT_DIR}/research-insights-${REPO}-${today}.html}"

    # ═══ Step 1: Repo Metadata ═══
    log_step "1/6 获取仓库元数据..."
    local repo_json
    repo_json=$(gl_check repo +info --owner "$OWNER" --repo "$REPO")
    local repo_name repo_desc repo_lang stars forks open_issues created_at updated_at
    repo_name=$(json_get "$repo_json" '.data.name // .data.full_name // "'"$REPO"' "')
    repo_desc=$(json_get "$repo_json" '.data.description // "No description"')
    repo_lang=$(json_get "$repo_json" '.data.language // "Unknown"')
    stars=$(json_get "$repo_json" '.data.stars_count // .data.stars // 0')
    forks=$(json_get "$repo_json" '.data.forks_count // .data.forks // 0')
    open_issues=$(json_get "$repo_json" '.data.open_issues_count // .data.open_issues // 0')
    created_at=$(json_get "$repo_json" '.data.created_at // ""')
    updated_at=$(json_get "$repo_json" '.data.updated_at // ""')

    log_info "  名称: $repo_name"
    log_info "  语言: $repo_lang"
    log_info "  Stars: $stars | Forks: $forks | Open Issues: $open_issues"

    # ═══ Step 2: Tech Stack Detection ═══
    log_step "2/6 检测技术栈..."
    local tech_stack="" file_count=0
    # Tech stack from repo language (API-based file listing not available on GitLink)
    tech_stack="$repo_lang"
    local research_features=""
    local names_list="" ext_counts="" file_count=0

    # Attempt to get file listing via repo info (limited info available)
    local sub_json
    sub_json=$(gl_run api GET "/v1/$OWNER/$REPO/sub_entries?ref=master" 2>/dev/null)
    # sub_entries may return HTML page if API not available; guard carefully
    if [[ "$(json_ok "$sub_json")" == "true" ]]; then
        # Check if .data is actually an array (not HTML string)
        local data_type
        data_type=$(echo "$sub_json" | jq -r '(.data | type) // "string"' 2>/dev/null)
        if [[ "$data_type" == "array" ]]; then
            file_count=$(json_count "$sub_json" '.data')
            ext_counts=$(echo "$sub_json" | jq -r '.data[].name // empty' 2>/dev/null | awk -F. '{if(NF>1) print $NF}' | sort | uniq -c | sort -rn | head -15)
            names_list=$(echo "$sub_json" | jq -r '.data[].name // empty' 2>/dev/null)

            local ecosystem=""
            if echo "$names_list" | grep -q "go.mod"; then ecosystem="$ecosystem Go"; fi
            if echo "$names_list" | grep -q "package.json"; then ecosystem="$ecosystem Node.js"; fi
            if echo "$names_list" | grep -qE "requirements.txt|pyproject.toml|setup.py|setup.cfg|Pipfile"; then ecosystem="$ecosystem Python"; fi
            if echo "$names_list" | grep -q "Cargo.toml"; then ecosystem="$ecosystem Rust"; fi
            if echo "$names_list" | grep -q "CMakeLists.txt"; then ecosystem="$ecosystem C/C++"; fi
            if echo "$names_list" | grep -qE "pom.xml|build.gradle"; then ecosystem="$ecosystem Java/Kotlin"; fi
            if echo "$names_list" | grep -q "CITATION.cff"; then ecosystem="$ecosystem +CITATION.cff"; fi
            tech_stack=$(echo "$ecosystem" | sed 's/^ *//')
            [[ -z "$tech_stack" ]] && tech_stack="$repo_lang"

            # Detect research features
            if echo "$names_list" | grep -qE "Dockerfile|docker-compose"; then research_features="$research_features Docker"; fi
            if echo "$names_list" | grep -qE "^data/|^datasets/"; then research_features="$research_features 数据集目录"; fi
            if echo "$names_list" | grep -q "\.ipynb"; then research_features="$research_features Jupyter"; fi
            if echo "$names_list" | grep -qE "^scripts/|^experiments/"; then research_features="$research_features 实验脚本"; fi
        fi
    fi
    log_info "  技术栈: ${tech_stack:-未知}"

    # ═══ Step 3: Project Positioning ═══
    log_step "3/6 提取项目定位..."
    local readme_text="" project_topics="" doi_found=""
    readme_text=$(gl_run api GET "raw/$OWNER/$REPO/master/README.md" 2>/dev/null)
    if [[ "$(json_ok "$readme_text")" == "true" ]]; then
        readme_text=$(echo "$readme_text" | jq -r '.data // ""' 2>/dev/null)
    else
        readme_text=""
    fi

    project_topics=$(extract_topics "$repo_desc $readme_text")
    doi_found=$(echo "$repo_desc $readme_text" | grep -oE '10\.[0-9]{4,}/[a-zA-Z0-9._\-/]+' | head -1 || echo "")

    log_info "  领域关键词: ${project_topics:-未检测到}"
    [[ -n "$doi_found" ]] && log_info "  DOI: $doi_found"

    # ═══ Step 4: Activity Health ═══
    log_step "4/6 计算活动健康指标..."

    # Issues
    local open_issues_json closed_issues_json
    open_issues_json=$(gl_run issue +list --owner "$OWNER" --repo "$REPO" --state open --limit 100)
    closed_issues_json=$(gl_run issue +list --owner "$OWNER" --repo "$REPO" --state closed --limit 100)

    local total_open total_closed
    total_open=0; total_closed=0
    if [[ "$(json_ok "$open_issues_json")" == "true" ]]; then
        total_open=$(json_count "$open_issues_json" '(.data.issues // .data)')
    fi
    if [[ "$(json_ok "$closed_issues_json")" == "true" ]]; then
        total_closed=$(json_count "$closed_issues_json" '(.data.issues // .data)')
    fi

    # PRs
    local merged_prs_json open_prs_json
    merged_prs_json=$(gl_run pr +list --owner "$OWNER" --repo "$REPO" --state merged --limit 100)
    open_prs_json=$(gl_run pr +list --owner "$OWNER" --repo "$REPO" --state open --limit 50)

    local total_merged=0 total_open_prs=0
    if [[ "$(json_ok "$merged_prs_json")" == "true" ]]; then
        total_merged=$(json_count "$merged_prs_json" '(.data.issues // .data.pulls // .data)')
    fi
    if [[ "$(json_ok "$open_prs_json")" == "true" ]]; then
        total_open_prs=$(json_count "$open_prs_json" '(.data.issues // .data.pulls // .data)')
    fi

    # Releases
    local releases_json release_count=0
    releases_json=$(gl_run release +list --owner "$OWNER" --repo "$REPO" --limit 20)
    if [[ "$(json_ok "$releases_json")" == "true" ]]; then
        release_count=$(json_count "$releases_json" '.data.releases')
    fi

    # CI
    local ci_json ci_builds=0 ci_success=0
    ci_json=$(gl_run ci +builds --owner "$OWNER" --repo "$REPO" --limit 20)
    if [[ "$(json_ok "$ci_json")" == "true" ]]; then
        ci_builds=$(json_count "$ci_json" '.data')
        ci_success=$(echo "$ci_json" | jq -r '[.data[] | select(.status == "success" or .status == "completed")] | length' 2>/dev/null || echo "0")
    fi

    local pr_merge_rate=0
    if [[ $((total_merged + total_open_prs)) -gt 0 ]]; then
        pr_merge_rate=$(awk "BEGIN { printf \"%.1f\", $total_merged / ($total_merged + $total_open_prs) * 100 }")
    fi

    local ci_pass_rate=0
    if [[ $ci_builds -gt 0 ]]; then
        ci_pass_rate=$(awk "BEGIN { printf \"%.1f\", $ci_success / $ci_builds * 100 }")
    fi

    log_info "  Issues: $total_open 开放 / $total_closed 已关闭"
    log_info "  PRs: $total_open_prs 开放 / $total_merged 已合并 (合并率: ${pr_merge_rate}%)"
    log_info "  Releases: $release_count | CI 通过率: ${ci_pass_rate}%"

    # ═══ Step 5: Contributor Network ═══
    log_step "5/6 构建贡献者网络..."
    local members_json member_count=0 members_list="[]"
    members_json=$(gl_run repo +members --owner "$OWNER" --repo "$REPO" --limit 50)
    if [[ "$(json_ok "$members_json")" == "true" ]]; then
        member_count=$(json_count "$members_json" '(.data.members // .data)')
        # Extract member logins as JSON array
        members_list=$(echo "$members_json" | jq -c '(.data.members // .data | if type == "array" then [.[].login // .[].user.login // empty] else [] end)' 2>/dev/null || echo "[]")
    fi
    log_info "  贡献者数: $member_count"

    # ═══ Step 6: Hotness Score ═══
    log_step "6/6 计算热度评分..."

    # Compute hotness
    local stars_norm forks_norm issues_active prs_active releases_active recency_factor
    local max_stars=1000 max_forks=200
    stars_norm=$(awk "BEGIN { printf \"%.1f\", ($stars / $max_stars > 1) ? 100 : ($stars / $max_stars * 100) }")
    forks_norm=$(awk "BEGIN { printf \"%.1f\", ($forks / $max_forks > 1) ? 100 : ($forks / $max_forks * 100) }")
    issues_active=$total_open
    [[ $issues_active -gt 50 ]] && issues_active=50
    issues_active=$(awk "BEGIN { printf \"%.1f\", $issues_active / 50 * 100 }")
    prs_active=$(awk "BEGIN { printf \"%.1f\", ($total_merged + $total_open_prs) / 30 * 100 }")
    [[ $(echo "$prs_active > 100" | bc 2>/dev/null || echo "0") -eq 1 ]] && prs_active=100
    releases_active=$(awk "BEGIN { printf \"%.1f\", $release_count / 10 * 100 }")
    [[ $(echo "$releases_active > 100" | bc 2>/dev/null || echo "0") -eq 1 ]] && releases_active=100

    # Recency: days since last update
    local days_since_update=365
    if [[ -n "$updated_at" ]]; then
        days_since_update=$(days_between "${updated_at:0:10}" "$today")
        [[ -z "$days_since_update" ]] && days_since_update=365
    fi
    if [[ $days_since_update -le 30 ]]; then recency_factor=100
    elif [[ $days_since_update -le 90 ]]; then recency_factor=50
    else recency_factor=10; fi

    local hotness
    hotness=$(weighted_sum "$stars_norm" 0.15 "$forks_norm" 0.10 "$issues_active" 0.20 "$prs_active" 0.20 "$releases_active" 0.15 0 0.10 "$recency_factor" 0.10)
    hotness=$(printf "%.1f" "$hotness")

    local hotness_label
    if awk "BEGIN { exit ($hotness >= 50) ? 0 : 1 }"; then hotness_label="Hot"
    elif awk "BEGIN { exit ($hotness >= 30) ? 0 : 1 }"; then hotness_label="Warm"
    else hotness_label="Cool"; fi

    log_ok "热度评分: ${hotness}/100 (${hotness_label})"

    # ═══ Generate Report ═══
    log_step "生成综合报告..."

    # JSON data for HTML embedding
    local json_data
    json_data=$(cat <<JSONEOF
{
  "repo": "${REPO_FULL}",
  "name": "$(echo "$repo_name" | sed 's/"/\\"/g')",
  "description": "$(echo "$repo_desc" | sed 's/"/\\"/g')",
  "language": "${repo_lang}",
  "tech_stack": "${tech_stack:-$repo_lang}",
  "stars": ${stars:-0},
  "forks": ${forks:-0},
  "open_issues": ${open_issues:-0},
  "created_at": "${created_at:0:10}",
  "updated_at": "${updated_at:0:10}",
  "hotness": ${hotness:-0},
  "hotness_label": "${hotness_label}",
  "total_open_issues": ${total_open:-0},
  "total_closed_issues": ${total_closed:-0},
  "total_merged_prs": ${total_merged:-0},
  "total_open_prs": ${total_open_prs:-0},
  "pr_merge_rate": ${pr_merge_rate:-0},
  "release_count": ${release_count:-0},
  "ci_builds": ${ci_builds:-0},
  "ci_pass_rate": ${ci_pass_rate:-0},
  "member_count": ${member_count:-0},
  "research_features": "$(echo "$research_features" | sed 's/^ *//')",
  "project_topics": "$(echo "$project_topics" | sed 's/"/\\"/g')",
  "doi": "${doi_found}",
  "days_since_update": ${days_since_update:-0},
  "report_date": "${today}"
}
JSONEOF
)

    # Generate HTML
    if [[ "${DRY_RUN:-false}" != "true" ]]; then
        cat > "$OUTPUT_FILE" <<HTMLEOF
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>${REPO_FULL} — 科研项目洞察报告</title>
<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f7fa; color: #333; }
.header { background: linear-gradient(135deg, #1a237e 0%, #283593 50%, #3949ab 100%); color: #fff; padding: 40px 30px; }
.header h1 { font-size: 28px; margin-bottom: 8px; }
.header .subtitle { opacity: 0.85; font-size: 14px; }
.container { max-width: 1200px; margin: 0 auto; padding: 20px; }
.cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px; margin-bottom: 24px; }
.card { background: #fff; border-radius: 12px; padding: 20px; box-shadow: 0 2px 8px rgba(0,0,0,.08); }
.card .label { font-size: 12px; color: #888; text-transform: uppercase; margin-bottom: 6px; }
.card .value { font-size: 28px; font-weight: 700; }
.card .value.hot { color: #e53935; }
.card .value.warm { color: #f57c00; }
.card .value.cool { color: #1565c0; }
.row { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 24px; }
.panel { background: #fff; border-radius: 12px; padding: 24px; box-shadow: 0 2px 8px rgba(0,0,0,.08); }
.panel h2 { font-size: 18px; margin-bottom: 16px; color: #1a237e; border-bottom: 2px solid #3949ab; padding-bottom: 8px; }
.chart { width: 100%; height: 350px; }
table { width: 100%; border-collapse: collapse; }
th, td { padding: 10px 14px; text-align: left; border-bottom: 1px solid #eee; font-size: 14px; }
th { background: #f5f7fa; color: #555; font-weight: 600; }
.tag { display: inline-block; padding: 2px 10px; border-radius: 12px; font-size: 12px; margin: 2px; }
.tag.lang { background: #e3f2fd; color: #1565c0; }
.tag.research { background: #e8f5e9; color: #2e7d32; }
.tag.warn { background: #fff3e0; color: #e65100; }
.footer { text-align: center; padding: 24px; color: #999; font-size: 12px; }
@media (max-width: 768px) { .row { grid-template-columns: 1fr; } }
</style>
</head>
<body>
<div class="header">
  <h1>${REPO_FULL}</h1>
  <div class="subtitle">科研项目洞察报告 &mdash; ${today}</div>
</div>
<div class="container">

<div class="cards">
  <div class="card">
    <div class="label">热度评分</div>
    <div class="value $(echo "$hotness_label" | tr '[:upper:]' '[:lower:]')">${hotness}</div>
    <div class="label">${hotness_label}</div>
  </div>
  <div class="card">
    <div class="label">Stars</div>
    <div class="value">${stars}</div>
  </div>
  <div class="card">
    <div class="label">Forks</div>
    <div class="value">${forks}</div>
  </div>
  <div class="card">
    <div class="label">贡献者</div>
    <div class="value">${member_count}</div>
  </div>
  <div class="card">
    <div class="label">开放 Issues</div>
    <div class="value">${total_open}</div>
  </div>
  <div class="card">
    <div class="label">PR 合并率</div>
    <div class="value">${pr_merge_rate}%</div>
  </div>
</div>

<div class="row">
  <div class="panel">
    <h2>项目概况</h2>
    <table>
      <tr><th>项目名称</th><td>${repo_name}</td></tr>
      <tr><th>描述</th><td>${repo_desc}</td></tr>
      <tr><th>主要语言</th><td><span class="tag lang">${repo_lang}</span></td></tr>
      <tr><th>技术栈</th><td>$(echo "$tech_stack" | sed 's/ /\n/g' | while read -r t; do [[ -n "$t" ]] && echo "<span class=\"tag lang\">$t</span>"; done)</td></tr>
      <tr><th>创建时间</th><td>${created_at:0:10}</td></tr>
      <tr><th>最后更新</th><td>${updated_at:0:10} (${days_since_update} 天前)</td></tr>
      <tr><th>科研特征</th><td>$(echo "$research_features" | sed 's/ /\n/g' | while read -r f; do [[ -n "$f" ]] && echo "<span class=\"tag research\">$f</span>"; done)</td></tr>
      $( [[ -n "$doi_found" ]] && echo "<tr><th>DOI</th><td><a href=\"https://doi.org/${doi_found}\">${doi_found}</a></td></tr>" )
      $( [[ -n "$project_topics" ]] && echo "<tr><th>领域主题</th><td>$(echo "$project_topics" | tr ',' '\n' | while read -r t; do [[ -n "$t" ]] && echo "<span class=\"tag lang\">$(echo $t | xargs)</span>"; done)</td></tr>" )
    </table>
  </div>

  <div class="panel">
    <h2>活动概览</h2>
    <div id="activityChart" class="chart"></div>
  </div>
</div>

<div class="row">
  <div class="panel">
    <h2>健康指标</h2>
    <table>
      <tr><th>指标</th><th>数值</th><th>状态</th></tr>
      <tr><td>Issue 总量</td><td>${total_open} 开放 / ${total_closed} 已关闭</td><td>$( [[ $total_open -gt 20 ]] && echo "<span class=\"tag warn\">需关注</span>" || echo "<span class=\"tag research\">正常</span>" )</td></tr>
      <tr><td>PR 合并率</td><td>${pr_merge_rate}%</td><td>$( awk "BEGIN { if(${pr_merge_rate} > 70) print \"<span class=\\\"tag research\\\">健康</span>\"; else print \"<span class=\\\"tag warn\\\">需改进</span>\" }" )</td></tr>
      <tr><td>Release 数</td><td>${release_count}</td><td>$( [[ $release_count -gt 0 ]] && echo "<span class=\"tag research\">已发布</span>" || echo "<span class=\"tag warn\">未发布</span>" )</td></tr>
      <tr><td>CI 通过率</td><td>${ci_pass_rate}% (${ci_builds} 次构建)</td><td>$( awk "BEGIN { if(${ci_pass_rate} > 80) print \"<span class=\\\"tag research\\\">稳定</span>\"; else print \"<span class=\\\"tag warn\\\">不稳定</span>\" }" )</td></tr>
      <tr><td>贡献者数</td><td>${member_count} 人</td><td>$( [[ $member_count -gt 3 ]] && echo "<span class=\"tag research\">活跃社区</span>" || echo "<span class=\"tag warn\">单人项目</span>" )</td></tr>
      <tr><td>活跃度</td><td>${days_since_update} 天前更新</td><td>$( [[ $days_since_update -le 30 ]] && echo "<span class=\"tag research\">活跃</span>" || echo "<span class=\"tag warn\">不活跃</span>" )</td></tr>
    </table>
  </div>

  <div class="panel">
    <h2>热度构成</h2>
    <div id="hotnessChart" class="chart"></div>
  </div>
</div>

</div>
<div class="footer">Generated by GitLink Research Assistant &mdash; ${today}</div>

<script>
var hotnessChart = echarts.init(document.getElementById('hotnessChart'));
hotnessChart.setOption({
  tooltip: { trigger: 'item' },
  legend: { bottom: 0 },
  series: [{
    type: 'pie',
    radius: ['45%', '75%'],
    label: { formatter: '{b}\n{d}%' },
    data: [
      { name: 'Stars', value: ${stars_norm:-0}, itemStyle: { color: '#5470c6' } },
      { name: 'Forks', value: ${forks_norm:-0}, itemStyle: { color: '#91cc75' } },
      { name: 'Issues', value: ${issues_active:-0}, itemStyle: { color: '#fac858' } },
      { name: 'PRs', value: ${prs_active:-0}, itemStyle: { color: '#ee6666' } },
      { name: 'Releases', value: ${releases_active:-0}, itemStyle: { color: '#73c0de' } },
      { name: 'Recency', value: ${recency_factor:-0}, itemStyle: { color: '#fc8452' } }
    ]
  }]
});

var activityChart = echarts.init(document.getElementById('activityChart'));
activityChart.setOption({
  tooltip: { trigger: 'axis' },
  xAxis: { type: 'category', data: ['Issues', 'PRs', 'Releases', 'CI Builds'] },
  yAxis: { type: 'value' },
  series: [
    { name: '开放/进行中', type: 'bar', data: [${total_open:-0}, ${total_open_prs:-0}, 0, 0], itemStyle: { color: '#fac858' } },
    { name: '已完成', type: 'bar', data: [${total_closed:-0}, ${total_merged:-0}, ${release_count:-0}, ${ci_builds:-0}], itemStyle: { color: '#91cc75' } }
  ]
});
</script>
</body>
</html>
HTMLEOF
        log_ok "HTML 报告已生成: $OUTPUT_FILE"
    else
        log_warn "[DRY RUN] Would generate: $OUTPUT_FILE"
    fi

    # ═══ Wiki Publishing ═══
    if [[ "$PUBLISH_WIKI" == "true" ]] && [[ "${DRY_RUN:-false}" != "true" ]]; then
        log_step "发布到 GitLink Wiki..."
        local wiki_content wiki_title
        wiki_title="[Research:Insights] ${REPO} 项目洞察 ${today}"
        wiki_content=$(cat <<WIKIEOF
## ${REPO_FULL} — 科研项目洞察

| 维度 | 数据 |
|------|------|
| 主要语言 | ${repo_lang} |
| 技术栈 | ${tech_stack:-$repo_lang} |
| Stars / Forks | ${stars} / ${forks} |
| 开放 Issues | ${total_open} |
| PR 合并率 | ${pr_merge_rate}% |
| Release 数量 | ${release_count} |
| 贡献者数 | ${member_count} |
| **热度评分** | **${hotness}/100 (${hotness_label})** |

### 科研特征
${research_features:-未检测到显著科研特征}

### 领域主题
${project_topics:-未检测到}

### DOI
${doi_found:-未检测到}

---
*报告生成时间：${today}*
WIKIEOF
)
        local wiki_json
        wiki_json=$(gl_run wiki +create --owner "$OWNER" --repo "$REPO" \
            --title "$wiki_title" --content "$wiki_content")
        if [[ "$(json_ok "$wiki_json")" == "true" ]]; then
            log_ok "Wiki 页面已发布"
        else
            log_warn "Wiki 发布失败（可手动创建）"
        fi
    fi

    # ═══ Summary ═══
    echo ""
    divider
    log_title "报告摘要"
    echo "  仓库:       ${REPO_FULL}"
    echo "  语言:       ${repo_lang}"
    echo "  技术栈:     ${tech_stack:-$repo_lang}"
    echo "  热度评分:   ${hotness}/100 (${hotness_label})"
    echo "  Issues:     ${total_open} 开放 / ${total_closed} 已关闭"
    echo "  PR 合并率:  ${pr_merge_rate}%"
    echo "  CI 通过率:  ${ci_pass_rate}%"
    echo "  贡献者:     ${member_count} 人"
    echo "  科研特征:   ${research_features:-无}"
    [[ -n "$doi_found" ]] && echo "  DOI:        ${doi_found}"
    divider
}

main "$@"
