#!/usr/bin/env nu
# Change the site font by updating all CSS config files and rebuilding.
#
# Usage:
#   nu scripts/build/change-font.nu Literata serif
#   nu scripts/build/change-font.nu Inter sans-serif
#   nu scripts/build/change-font.nu "Source Serif 4" serif
#   nu scripts/build/change-font.nu --list

def main [
    font?: string,               # Font family name (e.g. "Literata", "Inter")
    category?: string = "serif", # Font category: serif | sans-serif | monospace
    --list(-l),                  # List Google Fonts popular options
    --no-rebuild(-n),            # Skip pnpm css:build
] {
    if $list {
        print "Popular Google Fonts:"
        print "  Serif:      Literata | Merriweather | Lora | Playfair Display | Source Serif 4"
        print "  Sans-serif: Inter | Roboto | Open Sans | Nunito | DM Sans | Outfit"
        print "  Monospace:  JetBrains Mono | Fira Code | Source Code Pro"
        return
    }

    let font_name = $font | default ""
    if ($font_name | is-empty) {
        error make { msg: "Font name required. Run with --list to see options." }
    }

    let valid_categories = ["serif", "sans-serif", "monospace"]
    if not ($category in $valid_categories) {
        error make { msg: $"Category must be one of: ($valid_categories | str join ', ')" }
    }

    # Build fallback stack based on category
    let fallback = match $category {
        "serif"      => "ui-serif, Georgia, Cambria, 'Times New Roman', serif",
        "sans-serif" => "ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, sans-serif",
        "monospace"  => "ui-monospace, 'Cascadia Code', 'SF Mono', Consolas, monospace",
        _            => "ui-serif, Georgia, serif",
    }

    let font_stack = $"'($font_name)', ($fallback)"

    # Derive the camelCase key for presetWebFonts from the font name
    # "Source Serif 4" → "sourceSerif4", "JetBrains Mono" → "jetbrainsMono"
    let font_key = $font_name
        | str downcase
        | str replace --all " " "-"
        | split row "-"
        | enumerate
        | each { |it|
            if $it.index == 0 {
                $it.item
            } else {
                $it.item | str capitalize
            }
        }
        | str join ""

    print $"Changing site font to: ($font_name) \(($category)\)"

    # ─── 1. design-system.css ──────────────────────────────────────────────
    let ds_path = "works-pv/cache/assets/styles/design-system.css"
    let ds_content = open $ds_path
    let ds_new = $ds_content | str replace --regex "--font-sans:.*;" $"--font-sans: ($font_stack);"
    $ds_new | save --force $ds_path
    print $"  ✓ Updated ($ds_path)"

    # ─── 2. theme-default.css ──────────────────────────────────────────────
    let theme_path = "works-pv/cache/assets/styles/theme-default.css"
    let theme_content = open $theme_path
    let theme_new = $theme_content | str replace --regex "--font-family-sans:.*;" $"--font-family-sans: ($font_stack);"
    $theme_new | save --force $theme_path
    print $"  ✓ Updated ($theme_path)"

    # ─── 3. uno.config.ts ─ presetWebFonts entry ───────────────────────────
    let uno_path = "uno.config.ts"
    let uno_content = open $uno_path

    # Replace the entire fonts block inside presetWebFonts({ ... })
    let fonts_block = $"        ($font_key): [\n          \{\n            name: \"($font_name)\",\n            weights: [\"300\", \"400\", \"500\", \"600\", \"700\"],\n            italic: true,\n          \},\n        ],"

    let uno_fonts = $uno_content
        | str replace --regex '(?s)provider: "google",\s*fonts: \{[^}]*(?:\{[^}]*\}[^}]*)?\},' $"provider: \"google\",\n      fonts: \{\n($fonts_block)\n      \},"

    # Replace the body font-family in preflights
    let uno_body = $uno_fonts
        | str replace --regex "font-family: '[^']+',.*serif;" $"font-family: ($font_stack);"

    $uno_body | save --force $uno_path
    print $"  ✓ Updated ($uno_path)"

    # ─── 4. Rebuild CSS ────────────────────────────────────────────────────
    if not $no_rebuild {
        print "  ↻ Rebuilding CSS..."
        let result = do { pnpm run css:build } | complete
        if $result.exit_code == 0 {
            print "  ✓ CSS rebuilt"
        } else {
            print $"  ✗ CSS build failed:\n($result.stderr)"
        }
    } else {
        print "  ⚠ Skipped CSS rebuild (--no-rebuild)"
    }

    print $"\nFont changed to: ($font_name)"
    print "Restart the dev server or run `cargo leptos watch` to see changes."
}
