$cssUrl = "https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&family=Space+Mono:wght@400;700&display=swap"
$userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36"

# Fetch the Google Fonts CSS containing the WOFF2 links
$cssContent = Invoke-RestMethod -Uri $cssUrl -Headers @{"User-Agent" = $userAgent}

$fontsDir = "site\assets\fonts"
if (-not (Test-Path $fontsDir)) { New-Item -ItemType Directory -Path $fontsDir | Out-Null }

$newCssContent = $cssContent
$matches = [regex]::Matches($cssContent, 'url\((https://fonts\.gstatic\.com/s/[^)]+)\)')

$downloaded = @{}

foreach ($match in $matches) {
    $url = $match.Groups[1].Value
    $filename = Split-Path $url -Leaf
    
    if (-not $downloaded.ContainsKey($url)) {
        Invoke-WebRequest -Uri $url -OutFile "$fontsDir\$filename"
        $downloaded[$url] = $true
    }
    
    $newCssContent = $newCssContent.Replace($url, "fonts/$filename")
}

# Prepend the new font declarations to the main style.css
$mainCssPath = "site\assets\style.css"
$mainCss = Get-Content $mainCssPath -Raw
$finalCss = $newCssContent + "`n" + $mainCss
Set-Content -Path $mainCssPath -Value $finalCss -Encoding UTF8

Write-Host "Fonts downloaded and style.css updated."
