"""
Download WOFF2 font files from Google Fonts and generate local @font-face CSS.
Usage: python scripts/download_fonts.py
"""
import urllib.request
import re
import os

UA = (
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
    "AppleWebKit/537.36 (KHTML, like Gecko) "
    "Chrome/124.0.0.0 Safari/537.36"
)

FONTS_DIR = os.path.join(os.path.dirname(__file__), "..", "site", "assets", "fonts")
CSS_OUT = os.path.join(os.path.dirname(__file__), "..", "site", "assets", "css", "fonts.css")

GOOGLE_FONT_URLS = [
    "https://fonts.googleapis.com/css2?family=Instrument+Serif:ital@0;1&display=swap",
    "https://fonts.googleapis.com/css2?family=DM+Mono:ital,wght@0,300;0,400;0,500;1,300;1,400;1,500&display=swap",
    "https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap",
]

# font-display strategy per family
DISPLAY = {
    "Instrument Serif": "swap",     # h1 LCP — system font visible immediately, web font swaps fast from local
    "DM Mono": "optional",          # monospace labels/code — skip swap → zero CLS
    "Inter": "swap",                # body text — must be readable immediately
}


def fetch_css(url):
    req = urllib.request.Request(url, headers={"User-Agent": UA})
    with urllib.request.urlopen(req, timeout=30) as r:
        return r.read().decode("utf-8")


def main():
    os.makedirs(FONTS_DIR, exist_ok=True)

    # Parse pairs of (comment, block) — the comment tells us the subset
    face_blocks_out = []

    for url in GOOGLE_FONT_URLS:
        css = fetch_css(url)

        # Split on @font-face boundaries; keep preceding comment
        # Pattern: optional comment, then @font-face { ... }
        pattern = re.compile(
            r"(/\*\s*([^*]+?)\s*\*/)?\s*(@font-face\s*\{[^}]+\})",
            re.DOTALL,
        )

        for m in pattern.finditer(css):
            comment_text = (m.group(2) or "").strip()   # e.g. "latin" or "latin-ext"
            block = m.group(3)

            # Only keep latin (not latin-ext, cyrillic, greek, etc.)
            if comment_text and comment_text != "latin":
                continue
            if not comment_text:
                # no comment — include anyway (fallback)
                pass

            m_url = re.search(r"url\(([^)]+\.woff2)\)", block)
            m_family = re.search(r"font-family:\s*'([^']+)'", block)
            m_weight = re.search(r"font-weight:\s*(\d+)", block)
            m_style = re.search(r"font-style:\s*(\w+)", block)

            if not (m_url and m_family):
                continue

            woff2_url = m_url.group(1)
            family = m_family.group(1)
            weight = m_weight.group(1) if m_weight else "400"
            style = m_style.group(1) if m_style else "normal"

            suffix = f"-{weight}-{style}" if style != "normal" else f"-{weight}"
            fname = family.replace(" ", "") + suffix + ".woff2"
            dest = os.path.join(FONTS_DIR, fname)

            req2 = urllib.request.Request(woff2_url, headers={"User-Agent": UA})
            with urllib.request.urlopen(req2, timeout=30) as r2:
                data = r2.read()
            with open(dest, "wb") as f:
                f.write(data)
            print(f"  {fname}  ({len(data) // 1024} KB)")

            display = DISPLAY.get(family, "swap")
            local_path = f"/assets/fonts/{fname}"

            # Rebuild block: replace src + font-display; remove unicode-range (not needed for single file)
            new_block = f"@font-face {{\n"
            new_block += f"  font-family: '{family}';\n"
            new_block += f"  font-style: {style};\n"
            new_block += f"  font-weight: {weight};\n"
            new_block += f"  font-display: {display};\n"
            new_block += f"  src: url('{local_path}') format('woff2');\n"
            new_block += f"}}"

            face_blocks_out.append(new_block)

    css_out = "/* Self-hosted web fonts — generated by scripts/download_fonts.py */\n\n"
    css_out += "\n\n".join(face_blocks_out) + "\n"

    with open(CSS_OUT, "w", encoding="utf-8") as f:
        f.write(css_out)

    print(f"\nWrote {len(face_blocks_out)} @font-face rules to {os.path.relpath(CSS_OUT)}")


if __name__ == "__main__":
    main()
