# GitLink Research - Scenario 1: Repository Project Insight (PowerShell)
param(
    [string]$Owner, [string]$Repo, [string]$Output = "",
    [switch]$NoWiki, [switch]$DryRun
)

$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
Import-Module "$ScriptDir\..\lib\common.psm1" -Force -WarningAction SilentlyContinue

$ErrorActionPreference = "Continue"
Check-Auth
$resolved = Resolve-OwnerRepo -Owner $Owner -Repo $Repo
$Owner = $resolved.Owner; $Repo = $resolved.Repo
$Today = Get-Date -Format "yyyy-MM-dd"
$OutputDir = Join-Path $ScriptDir "..\output"
if (-not (Test-Path $OutputDir)) { New-Item -ItemType Directory -Path $OutputDir -Force | Out-Null }
$OutputFile = if ($Output) { $Output } else { Join-Path $OutputDir "research-insights-${Repo}-${Today}.html" }

Log-Title "GitLink Research - Repository Project Insight"

# 1. Repo metadata
Log-Step "1/6 Fetching repo metadata..."
$repoJson = Invoke-GLCheck @("repo", "+info", "--owner", $Owner, "--repo", $Repo)
$repoName = if ($repoJson.data.name) { $repoJson.data.name } elseif ($repoJson.data.full_name) { $repoJson.data.full_name } else { $Repo }
$repoDesc = if ($repoJson.data.description) { $repoJson.data.description } else { "No description" }
$repoLang = if ($repoJson.data.language) { $repoJson.data.language } else { "Unknown" }
$stars = if ($repoJson.data.stars_count) { [int]$repoJson.data.stars_count } elseif ($repoJson.data.stars) { [int]$repoJson.data.stars } else { 0 }
$forks = if ($repoJson.data.forks_count) { [int]$repoJson.data.forks_count } elseif ($repoJson.data.forks) { [int]$repoJson.data.forks } else { 0 }
$openIssues = if ($repoJson.data.open_issues_count) { [int]$repoJson.data.open_issues_count } else { 0 }
$updatedAt = if ($repoJson.data.updated_at) { $repoJson.data.updated_at } else { "" }

Log-Info "  Name: $repoName | Lang: $repoLang | Stars: $stars"

# 2. Issues
Log-Step "2/6 Collecting Issue data..."
$openIssuesJson = Invoke-GLCheck @("issue", "+list", "--owner", $Owner, "--repo", $Repo, "--state", "open", "--limit", "100")
$closedIssuesJson = Invoke-GLCheck @("issue", "+list", "--owner", $Owner, "--repo", $Repo, "--state", "closed", "--limit", "100")
$totalOpen = if ($openIssuesJson.ok) { $d = if ($openIssuesJson.data.issues) { $openIssuesJson.data.issues } else { $openIssuesJson.data }; @($d).Count } else { 0 }
$totalClosed = if ($closedIssuesJson.ok) { $d = if ($closedIssuesJson.data.issues) { $closedIssuesJson.data.issues } else { $closedIssuesJson.data }; @($d).Count } else { 0 }

# 3. PRs
Log-Step "3/6 Collecting PR data..."
$mergedPrsJson = Invoke-GLCheck @("pr", "+list", "--owner", $Owner, "--repo", $Repo, "--state", "merged", "--limit", "100")
$openPrsJson = Invoke-GLCheck @("pr", "+list", "--owner", $Owner, "--repo", $Repo, "--state", "open", "--limit", "50")
$md = if ($mergedPrsJson.data.issues) { $mergedPrsJson.data.issues } elseif ($mergedPrsJson.data.pulls) { $mergedPrsJson.data.pulls } else { $mergedPrsJson.data }
$totalMerged = if ($mergedPrsJson.ok) { @($md).Count } else { 0 }
$od = if ($openPrsJson.data.issues) { $openPrsJson.data.issues } elseif ($openPrsJson.data.pulls) { $openPrsJson.data.pulls } else { $openPrsJson.data }
$totalOpenPrs = if ($openPrsJson.ok) { @($od).Count } else { 0 }

# 4. Releases
Log-Step "4/6 Collecting Release data..."
$releasesJson = Invoke-GLCheck @("release", "+list", "--owner", $Owner, "--repo", $Repo, "--limit", "20")
$releaseCount = if ($releasesJson.ok) { @($releasesJson.data).Count } else { 0 }

# 5. CI
Log-Step "5/6 Collecting CI data..."
$ciPipelines = Get-CIPipelines $Owner $Repo
$ciBuilds = $ciPipelines.Count

# 6. Members
Log-Step "6/6 Fetching contributors..."
$membersJson = Invoke-GLCheck @("repo", "+members", "--owner", $Owner, "--repo", $Repo, "--limit", "50")
$memberCount = if ($membersJson.ok) {
    $d = if ($membersJson.data.members) { $membersJson.data.members } else { $membersJson.data }
    if ($d -is [array]) { $d.Count } else { 0 }
} else { 0 }

# Hotness calculation
$starsNorm = [Math]::Min($stars / 1000 * 100, 100)
$forksNorm = [Math]::Min($forks / 200 * 100, 100)
$issuesScore = [Math]::Min($totalOpen / 50 * 100, 100)
$prsScore = [Math]::Min(($totalMerged + $totalOpenPrs) / 30 * 100, 100)
$relScore = [Math]::Min($releaseCount / 10 * 100, 100)
$daysSince = if ($updatedAt) { try { ((Get-Date) - [DateTime]$updatedAt.Substring(0, 10)).Days } catch { 365 } } else { 365 }
$recency = if ($daysSince -le 30) { 100 } elseif ($daysSince -le 90) { 50 } else { 10 }
$hotness = [Math]::Round($starsNorm * 0.15 + $forksNorm * 0.10 + $issuesScore * 0.20 + $prsScore * 0.20 + $relScore * 0.15 + $recency * 0.10, 1)

$prMergeRate = if (($totalMerged + $totalOpenPrs) -gt 0) { [Math]::Round($totalMerged / ($totalMerged + $totalOpenPrs) * 100, 1) } else { 0 }

Log-Ok "Hotness score: ${hotness}/100"
Log-Info "  Issues: $totalOpen open / $totalClosed closed"
Log-Info "  PR merge rate: ${prMergeRate}% | Releases: $releaseCount | Contributors: $memberCount"

# Additional data for HTML report
$ciPassRate = 0
if ($ciBuilds -gt 0) {
    $ciSuccess = 0
    foreach ($b in $ciPipelines) {
        if (Test-CISuccess $b) { $ciSuccess++ }
    }
    $ciPassRate = [Math]::Round($ciSuccess / $ciBuilds * 100, 1)
}

$daysSinceUpdate = 365
if ($updatedAt -and $updatedAt.Length -ge 10) {
    try { $daysSinceUpdate = ((Get-Date) - [DateTime]$updatedAt.Substring(0, 10)).Days } catch { $daysSinceUpdate = 365 }
}
$recencyFactor = if ($daysSinceUpdate -le 30) { 100 } elseif ($daysSinceUpdate -le 90) { 50 } else { 10 }

$hotnessLabel = if ($hotness -ge 50) { "Hot" } elseif ($hotness -ge 30) { "Warm" } else { "Cool" }

$starsNorm = [Math]::Round([Math]::Min($stars / 1000.0, 1.0) * 100, 1)
$forksNorm = [Math]::Round([Math]::Min($forks / 200.0, 1.0) * 100, 1)
$issuesActive = [Math]::Round([Math]::Min($totalOpen / 50.0, 1.0) * 100, 1)
$prsActive = [Math]::Round([Math]::Min(($totalMerged + $totalOpenPrs) / 30.0, 1.0) * 100, 1)
$releasesActive = [Math]::Round([Math]::Min($releaseCount / 10.0, 1.0) * 100, 1)

$createdAt = if ($repoJson.data.created_at) { $repoJson.data.created_at } else { "" }
$createdAtDisplay = if ($createdAt.Length -ge 10) { $createdAt.Substring(0, 10) } else { "Unknown" }
$updatedAtDisplay = if ($updatedAt.Length -ge 10) { $updatedAt.Substring(0, 10) } else { "Unknown" }

# Detect tech stack
Log-Step "Detecting tech stack..."
$techStack = $repoLang
$researchFeatures = ""
$hasCitationCff = $false
$subJson = try { Invoke-GLCheck @("api", "GET", "/v1/$Owner/$Repo/sub_entries?ref=master") } catch { $null }
if ($subJson -and $subJson.ok -and ($subJson.data -is [array])) {
    $names = @($subJson.data | ForEach-Object { if ($_.name) { $_.name } else { "" } })
    $ecosystem = @()
    if ($names -contains "go.mod") { $ecosystem += "Go" }
    if ($names -contains "package.json") { $ecosystem += "Node.js" }
    if ($names | Where-Object { $_ -match "requirements\.txt|pyproject\.toml|setup\.py|setup\.cfg|Pipfile" }) { $ecosystem += "Python" }
    if ($names -contains "Cargo.toml") { $ecosystem += "Rust" }
    if ($names -contains "CMakeLists.txt") { $ecosystem += "C/C++" }
    if ($names | Where-Object { $_ -match "pom\.xml|build\.gradle" }) { $ecosystem += "Java/Kotlin" }
    if ($names -contains "CITATION.cff") { $hasCitationCff = $true; $ecosystem += "+CITATION.cff" }
    if ($ecosystem.Count -gt 0) { $techStack = ($ecosystem -join " ") }
    if ($names | Where-Object { $_ -match "Dockerfile|docker-compose" }) { $researchFeatures += " Docker" }
    if ($names | Where-Object { $_ -match "^data/|^datasets/" }) { $researchFeatures += " dataset" }
    if ($names | Where-Object { $_ -match "\.ipynb$" }) { $researchFeatures += " Jupyter" }
    if ($names | Where-Object { $_ -match "^scripts/|^experiments/" }) { $researchFeatures += " experiment-scripts" }
}
Log-Info "  Tech stack: $techStack"

# Readme analysis
Log-Step "Reading README for project positioning..."
$readmeText = ""
try {
    $readmeResult = Invoke-GLCheck @("api", "GET", "raw/$Owner/$Repo/master/README.md")
    if ($readmeResult.ok) { $readmeText = if ($readmeResult.data) { $readmeResult.data } else { "" } }
} catch { $readmeText = "" }

$projectTopics = ""
$topicKeywords = @("machine learning","deep learning","neural network","NLP","computer vision",
    "reinforcement learning","GAN","transformer","LLM","RAG","agent","bioinformatics","genomics",
    "drug discovery","robotics","autonomous","simulation","optimization","benchmark","dataset",
    "pre-trained","fine-tuning","distributed","federated","graph neural","knowledge graph",
    "recommender","anomaly detection","scientific computing","HPC","quantum","climate","physics",
    "chemistry")
foreach ($kw in $topicKeywords) {
    if ($repoDesc -match [regex]::Escape($kw) -or $readmeText -match [regex]::Escape($kw)) {
        if ($projectTopics) { $projectTopics += ", " }
        $projectTopics += $kw
    }
}

$doiFound = ""
if ($repoDesc -match '10\.\d{4,}/[\w.\-/]+') { $doiFound = $Matches[0] }
elseif ($readmeText -match '10\.\d{4,}/[\w.\-/]+') { $doiFound = $Matches[0] }

# ===== Generate HTML Report =====
Log-Step "Generating HTML report..."
$hotnessClass = $hotnessLabel.ToLower()

# Build tech stack tags
$techStackTags = ""
foreach ($t in ($techStack -split '\s+')) {
    if ($t) { $techStackTags += "<span class=`"tag lang`">$t</span> " }
}

# Build research features tags
$researchTags = ""
foreach ($f in ($researchFeatures -split '\s+' | Where-Object { $_ })) {
    $researchTags += "<span class=`"tag research`">$f</span> "
}
if (-not $researchTags) { $researchTags = "<span class=`"tag lang`">None detected</span>" }

# Build topic tags
$topicTags = ""
foreach ($t in ($projectTopics -split ', ' | Where-Object { $_ })) {
    $topicTags += "<span class=`"tag lang`">$t</span> "
}
if (-not $topicTags) { $topicTags = "<span>None detected</span>" }

$issueStatus = if ($totalOpen -gt 20) { "<span class=`"tag warn`">Needs attention</span>" } else { "<span class=`"tag research`">Normal</span>" }
$prStatus = if ($prMergeRate -gt 70) { "<span class=`"tag research`">Healthy</span>" } else { "<span class=`"tag warn`">Needs improvement</span>" }
$releaseStatus = if ($releaseCount -gt 0) { "<span class=`"tag research`">Released</span>" } else { "<span class=`"tag warn`">No release</span>" }
$ciStatus = if ($ciPassRate -gt 80) { "<span class=`"tag research`">Stable</span>" } else { "<span class=`"tag warn`">Unstable</span>" }
$memberStatus = if ($memberCount -gt 3) { "<span class=`"tag research`">Active community</span>" } else { "<span class=`"tag warn`">Solo project</span>" }
$activityStatus = if ($daysSinceUpdate -le 30) { "<span class=`"tag research`">Active</span>" } else { "<span class=`"tag warn`">Inactive</span>" }

$doiRow = ""
if ($doiFound) { $doiRow = "<tr><th>DOI</th><td><a href=`"https://doi.org/$doiFound`">$doiFound</a></td></tr>" }

$htmlContent = @"
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>$Owner/$Repo &mdash; Research Project Insight Report</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>$Owner/$Repo</h1>
  <div class="subtitle">Research Project Insight Report &mdash; $Today</div>
</div>
<div class="container">

<div class="cards">
  <div class="card">
    <div class="label">Hotness Score</div>
    <div class="value $hotnessClass">$hotness</div>
    <div class="label">$hotnessLabel</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">Contributors</div>
    <div class="value">$memberCount</div>
  </div>
  <div class="card">
    <div class="label">Open Issues</div>
    <div class="value">$totalOpen</div>
  </div>
  <div class="card">
    <div class="label">PR Merge Rate</div>
    <div class="value">${prMergeRate}%</div>
  </div>
</div>

<div class="row">
  <div class="panel">
    <h2>Project Overview</h2>
    <table>
      <tr><th>Name</th><td>$repoName</td></tr>
      <tr><th>Description</th><td>$repoDesc</td></tr>
      <tr><th>Language</th><td><span class="tag lang">$repoLang</span></td></tr>
      <tr><th>Tech Stack</th><td>$techStackTags</td></tr>
      <tr><th>Created</th><td>$createdAtDisplay</td></tr>
      <tr><th>Updated</th><td>$updatedAtDisplay ($daysSinceUpdate days ago)</td></tr>
      <tr><th>Research Features</th><td>$researchTags</td></tr>
      $doiRow
      <tr><th>Topics</th><td>$topicTags</td></tr>
    </table>
  </div>

  <div class="panel">
    <h2>Activity Overview</h2>
    <div id="activityChart" class="chart"></div>
  </div>
</div>

<div class="row">
  <div class="panel">
    <h2>Health Indicators</h2>
    <table>
      <tr><th>Indicator</th><th>Value</th><th>Status</th></tr>
      <tr><td>Total Issues</td><td>$totalOpen open / $totalClosed closed</td><td>$issueStatus</td></tr>
      <tr><td>PR Merge Rate</td><td>${prMergeRate}%</td><td>$prStatus</td></tr>
      <tr><td>Releases</td><td>$releaseCount</td><td>$releaseStatus</td></tr>
      <tr><td>CI Pass Rate</td><td>${ciPassRate}% ($ciBuilds builds)</td><td>$ciStatus</td></tr>
      <tr><td>Contributors</td><td>$memberCount people</td><td>$memberStatus</td></tr>
      <tr><td>Activity</td><td>$daysSinceUpdate days since update</td><td>$activityStatus</td></tr>
    </table>
  </div>

  <div class="panel">
    <h2>Hotness Composition</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: $starsNorm, itemStyle: { color: '#5470c6' } },
      { name: 'Forks', value: $forksNorm, itemStyle: { color: '#91cc75' } },
      { name: 'Issues', value: $issuesActive, itemStyle: { color: '#fac858' } },
      { name: 'PRs', value: $prsActive, itemStyle: { color: '#ee6666' } },
      { name: 'Releases', value: $releasesActive, itemStyle: { color: '#73c0de' } },
      { name: 'Recency', value: $recencyFactor, 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: 'Open/In Progress', type: 'bar', data: [$totalOpen, $totalOpenPrs, 0, 0], itemStyle: { color: '#fac858' } },
    { name: 'Completed', type: 'bar', data: [$totalClosed, $totalMerged, $releaseCount, $ciBuilds], itemStyle: { color: '#91cc75' } }
  ]
});
</script>
</body>
</html>
"@

if (-not $DryRun) {
    $htmlContent | Out-File -FilePath $OutputFile -Encoding UTF8
    Log-Ok "HTML report generated: $OutputFile"
} else {
    Log-Warn "[DRY RUN] Would generate: $OutputFile"
}

# Summary output
Divider
Write-Host "====== Analysis Summary ======" -ForegroundColor White
Write-Host "  Repo:       $Owner/$Repo"
Write-Host "  Language:   $repoLang"
Write-Host "  Tech Stack: $techStack"
Write-Host "  Hotness:    $hotness/100 ($hotnessLabel)"
Write-Host "  Issues:     $totalOpen open / $totalClosed closed"
Write-Host "  PR merge:   ${prMergeRate}%"
Write-Host "  CI pass:    ${ciPassRate}%"
Write-Host "  Members:    $memberCount"
Write-Host "  Features:   $researchFeatures"
if ($doiFound) { Write-Host "  DOI:        $doiFound" }
Write-Host "  Report:     $OutputFile"
Divider
Log-Ok "Analysis complete"
