#!/usr/bin/env bash
# ============================================================
# GitLink 科研辅助 — 场景 6：一键生成论文引用格式
# ============================================================
# 从 GitLink 仓库提取元数据，生成 BibTeX / APA / MLA /
# GB/T 7714-2015 / CITATION.cff 格式的学术引用
# ============================================================

set -euo pipefail
trap '' PIPE

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

# ── Configuration ────────────────────────────────────────────────────
OUTPUT_FILE=""
CITE_FORMAT="all"

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

Options:
  --owner <owner>       Repository owner (required)
  --repo <repo>         Repository name (required)
  --format <format>     Citation format: bibtex|apa|mla|gbt7714|cff|all (default: all)
  --output <file>       Output file path (default: stdout)
  --dry-run             Preview mode (no file write)

Examples:
  11-research-citation.sh --owner zzx-coder --repo gitlink-cli
  11-research-citation.sh --owner zzx-coder --repo gitlink-cli --format bibtex
  11-research-citation.sh --owner zzx-coder --repo gitlink-cli --output citation.bib
EOF
    exit 0
}

# ── Parse Arguments ──────────────────────────────────────────────────
parse_common_args "$@"
while [[ $# -gt 0 ]]; do
    case "$1" in
        --format)  CITE_FORMAT="$2"; shift 2 ;;
        --output)  OUTPUT_FILE="$2"; shift 2 ;;
        *)         shift ;;
    esac
done

# ── Main ─────────────────────────────────────────────────────────────
main() {
    log_title "GitLink 科研辅助 — 论文引用格式生成"

    check_auth
    require_owner_repo
    local today
    today=$(date_today)

    # Step 1: Fetch repo metadata
    log_step "获取仓库元数据..."
    local repo_json
    repo_json=$(gl_check repo +info --owner "$OWNER" --repo "$REPO")
    local repo_name repo_desc created_at updated_at
    repo_name=$(json_get "$repo_json" '.data.name // .data.full_name // ""')
    repo_desc=$(json_get "$repo_json" '.data.description // ""')
    created_at=$(json_get "$repo_json" '.data.created_at // ""')
    updated_at=$(json_get "$repo_json" '.data.updated_at // ""')

    # Step 2: Get latest release
    log_step "获取最新版本..."
    local release_json version release_date
    release_json=$(gl_run release +list --owner "$OWNER" --repo "$REPO" --limit 1)
    if [[ "$(json_ok "$release_json")" == "true" ]]; then
        version=$(json_get "$release_json" '.data.releases[0].tag_name // .data.releases[0].name // ""')
        release_date=$(json_get "$release_json" '.data.releases[0].created_at // ""')
    fi
    # Fallback to "dev" if no release
    version="${version:-v0.0.0-dev}"
    release_date="${release_date:-$updated_at}"
    local release_year="${release_date:0:4}"
    local release_year_only="${release_year:-$(date +%Y)}"

    # Step 3: Get members (authors)
    log_step "获取贡献者列表..."
    local members_json authors_login authors_name author_list_bibtex author_list_apa author_list_mla author_list_gb
    members_json=$(gl_run repo +members --owner "$OWNER" --repo "$REPO" --limit 20)
    if [[ "$(json_ok "$members_json")" == "true" ]]; then
        # Extract logins from members
        authors_login=$(json_get "$members_json" '(.data.members // .data | if type == "array" then [.[].login // .[].user.login // empty] else [] end | join(", "))')
        authors_name=$(json_get "$members_json" '(.data.members // .data | if type == "array" then [.[].name // .[].full_name // .[].login // empty] else [] end | join(", "))')
    fi
    authors_login="${authors_login:-$OWNER}"
    authors_name="${authors_name:-$OWNER}"

    # Format authors for each citation style
    # Parse comma-separated names
    IFS=', ' read -r -a name_array <<< "$authors_name"
    local author_count=${#name_array[@]}

    # BibTeX: Last1, First1 and Last2, First2
    author_list_bibtex=""
    local i=0
    for name in "${name_array[@]}"; do
        [[ -z "$name" ]] && continue
        i=$((i + 1))
        [[ $i -gt 5 ]] && { author_list_bibtex="${author_list_bibtex} and others"; break; }
        [[ $i -gt 1 ]] && author_list_bibtex="${author_list_bibtex} and "
        # Simple: first word = first name, rest = last name
        local first="${name%% *}" last="${name##* }"
        [[ "$first" == "$last" ]] && author_list_bibtex="${author_list_bibtex}${last}" || author_list_bibtex="${author_list_bibtex}${last}, ${first}"
    done

    # APA: Last, F., & Last, F.
    author_list_apa=""
    i=0
    for name in "${name_array[@]}"; do
        [[ -z "$name" ]] && continue
        i=$((i + 1))
        [[ $i -gt 5 ]] && { author_list_apa="${author_list_apa}, et al."; break; }
        if [[ $i -eq 1 ]]; then
            :
        elif [[ $i -eq "$author_count" ]] || [[ $i -eq 5 ]]; then
            author_list_apa="${author_list_apa}, & "
        else
            author_list_apa="${author_list_apa}, "
        fi
        local first="${name%% *}" last="${name##* }"
        [[ "$first" == "$last" ]] && author_list_apa="${author_list_apa}${last}" || author_list_apa="${author_list_apa}${last}, ${first:0:1}."
    done

    # MLA: Last, First, et al. (2+ authors → et al.)
    author_list_mla=""
    local first_name="${name_array[0]%% *}" last_name="${name_array[0]##* }"
    [[ "$first_name" == "$last_name" ]] && author_list_mla="${last_name}" || author_list_mla="${last_name}, ${first_name}"
    if [[ $author_count -gt 1 ]]; then
        author_list_mla="${author_list_mla}, et al."
    fi

    # GB/T 7714: 作者1, 作者2
    author_list_gb=""
    i=0
    for name in "${name_array[@]}"; do
        [[ -z "$name" ]] && continue
        i=$((i + 1))
        [[ $i -gt 3 ]] && { author_list_gb="${author_list_gb}等"; break; }
        [[ $i -gt 1 ]] && author_list_gb="${author_list_gb}, "
        author_list_gb="${author_list_gb}${name}"
    done

    # Step 4: Get repo URL
    local repo_url
    repo_url=$(git remote get-url origin 2>/dev/null || echo "")
    if [[ -z "$repo_url" ]]; then
        repo_url="https://gitlink.org.cn/${OWNER}/${REPO}"
    fi
    # Normalize .git suffix
    repo_url="${repo_url%.git}"

    # Step 5: Try to detect DOI
    log_step "检测 DOI..."
    local doi=""
    if echo "$repo_desc" | grep -qoP '10\.\d{4,}/[\w.\-/]+'; then
        doi=$(echo "$repo_desc" | grep -oE '10\.[0-9]{4,}/[a-zA-Z0-9._\-/]+' | head -1)
    fi

    # Short name for BibTeX key
    local short_name
    short_name=$(echo "$REPO" | sed 's/[^a-zA-Z0-9_-]/_/g' | head -c 32)

    # ── Generate Citations ────────────────────────────────────────────
    local output=""
    log_step "生成引用格式..."

    # BibTeX
    if [[ "$CITE_FORMAT" == "bibtex" || "$CITE_FORMAT" == "all" ]]; then
        output+="@software{${short_name},
  author = {${author_list_bibtex}},
  title = {${repo_name}},
  version = {${version}},
  date = {${release_date}},
  publisher = {GitLink},
  url = {${repo_url}}"
        if [[ -n "$doi" ]]; then
            output+=",
  doi = {${doi}}"
        fi
        output+=",
  note = {${repo_desc}}
}
"
    fi

    # APA 7th
    if [[ "$CITE_FORMAT" == "apa" || "$CITE_FORMAT" == "all" ]]; then
        output+="
${author_list_apa} (${release_year_only}). ${repo_name} (Version ${version}) [Computer software].
  GitLink. ${repo_url}
"
    fi

    # MLA 9th
    if [[ "$CITE_FORMAT" == "mla" || "$CITE_FORMAT" == "all" ]]; then
        output+="
${author_list_mla}. ${repo_name}. Version ${version}, GitLink,
  ${release_date}, ${repo_url}.
"
    fi

    # GB/T 7714-2015
    if [[ "$CITE_FORMAT" == "gbt7714" || "$CITE_FORMAT" == "all" ]]; then
        output+="
[1] ${author_list_gb}. ${repo_name}[CP/OL]. ${version}. GitLink,
  ${release_date}[${today}]. ${repo_url}.
"
    fi

    # CITATION.cff
    if [[ "$CITE_FORMAT" == "cff" || "$CITE_FORMAT" == "all" ]]; then
        output+="
cff-version: 1.2.0
message: \"If you use this software, please cite it as below.\"
authors:
"
        for name in "${name_array[@]}"; do
            [[ -z "$name" ]] && continue
            local first="${name%% *}" last="${name##* }"
            output+="  - family-names: ${last}
    given-names: ${first}
"
        done
        output+="title: \"${repo_name}\"
version: ${version}
date-released: ${release_date:0:10}
url: \"${repo_url}\"
repository-code: \"${repo_url}.git\"
"
        if [[ -n "$doi" ]]; then
            output+="doi: ${doi}
"
        fi
    fi

    # ── Output ────────────────────────────────────────────────────────
    log_ok "引用格式生成完成"

    if [[ -n "$OUTPUT_FILE" ]]; then
        if [[ "${DRY_RUN:-false}" != "true" ]]; then
            echo "$output" > "$OUTPUT_FILE"
            log_ok "已写入: $OUTPUT_FILE"
        else
            log_warn "[DRY RUN] Would write to: $OUTPUT_FILE"
        fi
    fi

    # Always print to console
    divider
    echo "$output"
    divider

    # ── Summary ───────────────────────────────────────────────────────
    log_info "仓库: ${OWNER}/${REPO}"
    log_info "版本: ${version}"
    log_info "发布日期: ${release_date}"
    log_info "贡献者数: ${author_count}"
    [[ -n "$doi" ]] && log_info "DOI: ${doi}"
    log_info "格式: ${CITE_FORMAT}"

    # Offer to create CITATION.cff
    if [[ "${DRY_RUN:-false}" != "true" ]]; then
        echo ""
        log_info "提示: 可在仓库中创建 CITATION.cff 文件以便他人引用。"
    fi
}

main "$@"
