$templatesDir = "d:\gdfhbfgdbnbdfbdf\typogenie\src-tauri\templates"
$files = Get-ChildItem -Path $templatesDir -Recurse -Filter *.json

foreach ($file in $files) {
    try {
        $content = Get-Content -Path $file.FullName -Raw
        
        # 1. Extract Font Names using Regex
        $headingFont = "Unknown"
        $bodyFont = "Unknown"
        $codeFont = "Unknown"

        if ($content -match '"heading":\s*"([^"]+)"') { $headingFont = $matches[1] }
        if ($content -match '"body":\s*"([^"]+)"') { $bodyFont = $matches[1] }
        if ($content -match '"code":\s*"([^"]+)"') { $codeFont = $matches[1] }
        
        if ($headingFont -eq "Unknown" -or $bodyFont -eq "Unknown") {
            Write-Host "Skipping $($file.Name) - Could not parse fonts" -ForegroundColor Yellow
            continue
        }

        # 2. Build Google Fonts URL
        # Standard weights + italics: 300, 400, 500, 600, 700
        $weights = "ital,wght@0,300;0,400;0,500;0,600;0,700;1,300;1,400;1,500;1,600;1,700"
        
        $fonts = @($headingFont, $bodyFont, $codeFont) | Select-Object -Unique
        $urlParts = @()
        
        foreach ($font in $fonts) {
            # Handle fonts that might not be Google Fonts (e.g. system fonts)? 
            # Assuming all current templates use Google Fonts as per design.
            $encodedFont = $font -replace ' ', '+'
            $urlParts += "family=$encodedFont`:$weights"
        }
        
        $fullUrl = "https://fonts.googleapis.com/css2?" + ($urlParts -join "&") + "&display=swap"
        
        # 3. Repair the broken line
        # Look for "googleFontsImport": "https: OR "googleFontsImport": "https:\s*
        # The previous regex stripping might have left it as `"https:` (no closing quote) or `"https:""` if there was a quote after?
        # Inspecting previous output: `"googleFontsImport": "https:` 
        
        if ($content -match '"googleFontsImport":\s*"https:') {
            $newLine = '"googleFontsImport": "' + $fullUrl + '",'
            $newContent = $content -replace '"googleFontsImport":\s*"https:.*', $newLine
            
            # Double check we didn't add double commas or break structure
            # The original often had a comma after. The regex `.*` eats the rest of the line.
            # My replacement adds a comma.
            
            Set-Content -Path $file.FullName -Value $newContent -Force
            Write-Host "Restored: $($file.Name)" -ForegroundColor Green
        } else {
            Write-Host "No repair needed or pattern not found: $($file.Name)" -ForegroundColor Gray
        }
        
    } catch {
        Write-Host "Error processing $($file.Name): $($_.Exception.Message)" -ForegroundColor Red
    }
}
