# GitLink 科研辅助 — PowerShell 公共模块扩展
# 在 common.psm1 基础上增加科研计算函数

# -- Math helpers --
function Get-Normalized {
    param([double]$Value, [double]$Max)
    if ($Max -le 0) { return 0 }
    return [Math]::Round($Value / $Max, 4)
}
function Get-Clamped {
    param([double]$Value, [double]$Lo, [double]$Hi)
    return [Math]::Max($Lo, [Math]::Min($Value, $Hi))
}
function Get-WeightedSum {
    param([double[]]$Pairs)
    $sum = 0.0
    for ($i = 0; $i -lt $Pairs.Count; $i += 2) {
        $sum += $Pairs[$i] * $Pairs[$i + 1]
    }
    return [Math]::Round($sum, 4)
}
function Get-Jaccard {
    param([string[]]$ListA, [string[]]$ListB)
    $setA = @{}; foreach ($a in $ListA) { $setA[$a.Trim()] = 1 }
    $inter = 0; foreach ($b in $ListB) { if ($setA.ContainsKey($b.Trim())) { $inter++ } }
    $union = ($setA.Keys + ($ListB | ForEach-Object { $_.Trim() }) | Select-Object -Unique).Count
    if ($union -le 0) { return 0 }
    return [Math]::Round($inter / $union, 4)
}
function Get-DaysBetween {
    param([string]$Date1, [string]$Date2)
    try { return ([DateTime]$Date2 - [DateTime]$Date1).Days }
    catch { return 365 }
}
function Get-DateToday { return (Get-Date -Format "yyyy-MM-dd") }

# -- Citation helpers --
function Format-AuthorsBibtex {
    param([string[]]$Authors)
    $result = ""; $count = 0
    foreach ($a in $Authors) {
        if (-not $a) { continue }
        $count++
        if ($count -gt 5) { $result += " and others"; break }
        if ($count -gt 1) { $result += " and " }
        $parts = $a -split '\s+'
        $last = $parts[-1]; $first = $parts[0]
        $result += "$last, $first"
    }
    return $result
}
function Format-AuthorsAPA {
    param([string[]]$Authors)
    $result = ""; $count = 0; $total = ($Authors | Where-Object { $_ }).Count
    foreach ($a in $Authors) {
        if (-not $a) { continue }
        $count++
        if ($count -gt 5) { $result += ", et al."; break }
        if ($count -eq 1) { }
        elseif ($count -eq $total -or $count -eq 5) { $result += ", & " }
        else { $result += ", " }
        $parts = $a -split '\s+'
        $last = $parts[-1]; $first = $parts[0][0]
        $result += "$last, $first."
    }
    return $result
}

Export-ModuleMember -Function Get-Normalized, Get-Clamped, Get-WeightedSum, Get-Jaccard, Get-DaysBetween, Get-DateToday, Format-AuthorsBibtex, Format-AuthorsAPA
