Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"

$repoRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
Set-Location $repoRoot

$env:GOCACHE = Join-Path $repoRoot ".cache/go-build"
$outputPath = Join-Path $repoRoot "tools/sow-toolkit.exe"

function Test-ToolSourcesAreNewer {
    if (-not (Test-Path $outputPath)) {
        return $true
    }

    $outputTime = (Get-Item -LiteralPath $outputPath).LastWriteTimeUtc
    $sourcePaths = @("go.mod", "go.sum", "cmd", "internal")
    foreach ($sourcePath in $sourcePaths) {
        $fullPath = Join-Path $repoRoot $sourcePath
        if (-not (Test-Path $fullPath)) {
            continue
        }
        $newerSource = Get-ChildItem -LiteralPath $fullPath -Recurse -File |
            Where-Object { $_.LastWriteTimeUtc -gt $outputTime } |
            Select-Object -First 1
        if ($newerSource) {
            return $true
        }
    }

    return $false
}

New-Item -ItemType Directory -Force -Path (Join-Path $repoRoot "tools") | Out-Null
New-Item -ItemType Directory -Force -Path $env:GOCACHE | Out-Null
if (-not (Test-ToolSourcesAreNewer)) {
    Write-Host "sow-toolkit is up to date."
    exit 0
}

Write-Host "Building sow-toolkit..."
go build -o $outputPath ./cmd/nwn-tool
