#requires -Version 5
<#
.SYNOPSIS
    Read-only update checker. Diffs the locked Modrinth versions against the
    latest available on Modrinth. Prints a report. Does not change anything.

.DESCRIPTION
    Run this periodically to see what mod updates are available without
    committing to anything. Decide which to bump, then either edit pack.lock.json
    by hand or re-run Update-Pack.ps1 to refresh everything.

    CurseForge mods (FTB family) aren't auto-checked here -- CF requires an API
    key for proper version listing. Manually monitor those at:
      https://www.curseforge.com/minecraft/mc-mods/ftb-chunks-forge
      https://www.curseforge.com/minecraft/mc-mods/ftb-library-forge
      https://www.curseforge.com/minecraft/mc-mods/ftb-teams-forge
#>

[CmdletBinding()]
param()

$ErrorActionPreference = 'Stop'
$ProgressPreference    = 'SilentlyContinue'

$here     = Split-Path -Parent $MyInvocation.MyCommand.Path
$lockPath = Join-Path $here '..\pack\pack.lock.json'

if (-not (Test-Path $lockPath)) {
    throw "pack.lock.json not found. Run Update-Pack.ps1 first to bootstrap it."
}

$lock = Get-Content $lockPath -Raw | ConvertFrom-Json
$mc   = $lock.minecraft
$lt   = $lock.loader.type

Write-Host ""
Write-Host "Checking Modrinth for newer versions..."
Write-Host ("  Pack:   $($lock.name) v$($lock.version)")
Write-Host ("  MC:     $mc ($lt $($lock.loader.version))")
Write-Host ("  Locked: $($lock.lockedAt)")
Write-Host ""

Add-Type -AssemblyName System.Web

function Invoke-Modrinth {
    param([string]$Path)
    Invoke-RestMethod -Uri "https://api.modrinth.com/v2$Path" -Headers @{ 'User-Agent' = 'BrassAndSigil-Launcher/0.1 (matt@sijbers.uk)' }
}

$updatesAvailable = 0
$upToDate = 0
$skipped = 0

foreach ($mod in $lock.mods) {
    if ($mod.source -ne "modrinth") {
        Write-Host ("  [cforge]  $($mod.slug.PadRight(22)) $($mod.version.PadRight(34)) (manual check)")
        $skipped++
        continue
    }

    try {
        $encGv = [System.Web.HttpUtility]::UrlEncode('["' + $mc + '"]')
        $encL  = [System.Web.HttpUtility]::UrlEncode('["' + $lt + '"]')
        $versions = Invoke-Modrinth ("/project/$($mod.slug)/version?game_versions=$encGv" + "&" + "loaders=$encL")
    } catch {
        Write-Warning "  [error]   $($mod.slug) - $($_.Exception.Message)"
        continue
    }
    if (-not $versions -or $versions.Count -eq 0) {
        Write-Warning "  [gone]    $($mod.slug) - no versions found on Modrinth"
        continue
    }

    $latest = $versions[0]
    $latestVer = $latest.version_number
    $latestType = $latest.version_type

    if ($latest.id -eq $mod.versionId) {
        Write-Host ("  [ok]      $($mod.slug.PadRight(22)) $($mod.version.PadRight(34)) (current)")
        $upToDate++
    }
    else {
        $tag = if ($latestType -eq 'beta') { '[update*]' } else { '[update] ' }
        Write-Host ("  $tag $($mod.slug.PadRight(22)) $($mod.version.PadRight(34)) -> $latestVer") -ForegroundColor Yellow
        $updatesAvailable++
    }
}

Write-Host ""
Write-Host "Summary:"
Write-Host ("  Up to date:   $upToDate")
$updateColor = if ($updatesAvailable -gt 0) { 'Yellow' } else { 'White' }
Write-Host ("  Updates:      $updatesAvailable") -ForegroundColor $updateColor
Write-Host ("  Manual check: $skipped (CurseForge)")
Write-Host ""
if ($updatesAvailable -gt 0) {
    Write-Host "[update*] = beta release. Bump only if you specifically want it."
    Write-Host ""
    Write-Host "To take all updates: run Update-Pack.ps1 (then Build-Pack.ps1 + deploy server)."
    Write-Host "To pick selectively: edit pack.lock.json by hand, then run Build-Pack.ps1."
}
