"""
CSS generator for self-hosted font @font-face rules.

Generates complete CSS files with @font-face declarations and CSS custom
properties for downloaded Google Fonts. The output is designed to work
with any base URL configuration by using relative paths.

Output Structure:
The generated CSS includes:
1. Header comment identifying it as auto-generated
2. @font-face rules for each font variant (weight/style)
3. CSS custom properties mapping font roles to family names

Example Output::

/* Auto-generated by Bengal Font Helper */
/* See bengal.toml [fonts] section */

/* Inter */
@font-face {
  font-family: 'Inter';
  font-weight: 400;
  font-style: normal;
  font-display: swap;
  src: url('fonts/inter-400.woff2') format('woff2');
}

/* CSS Custom Properties */
:root {
  --font-primary: 'Inter';
}

Related:
- bengal/fonts/downloader.py: FontVariant data class
- bengal/fonts/__init__.py: FontHelper integration

"""

from bengal.fonts.downloader import FontVariant


class FontCSSGenerator:
    """
    Generates @font-face CSS for self-hosted fonts.

    Creates complete CSS files with @font-face rules for each font variant
    and CSS custom properties that map configuration role names (e.g.,
    "primary", "heading") to font family names.

    The generator uses relative paths for font URLs, ensuring compatibility
    with any site base URL configuration. Font files are referenced relative
    to the fonts.css location.

    Example:
            >>> from bengal.fonts.downloader import FontVariant
            >>> generator = FontCSSGenerator()
            >>> variants = {
            ...     "primary": [
            ...         FontVariant("Inter", 400, "normal", "https://..."),
            ...         FontVariant("Inter", 700, "normal", "https://...")
            ...     ]
            ... }
            >>> css = generator.generate(variants)
            >>> print(css[:50])
        /* Auto-generated by Bengal Font Helper */

    """

    def generate(
        self,
        font_mapping: dict[str, list[FontVariant]],
        font_path_prefix: str = "fonts",
    ) -> str:
        """
        Generate complete fonts.css content.

        Creates CSS with @font-face rules for each variant and CSS custom
        properties for easy font access in stylesheets.

        Args:
            font_mapping: Dictionary mapping font role names (from config) to
                lists of FontVariant objects. Example::

                    {
                        "primary": [FontVariant("Inter", 400, ...), ...],
                        "heading": [FontVariant("Playfair Display", 700, ...)]
                    }
            font_path_prefix: URL path prefix for font files, relative to the
                fonts.css location. Defaults to ``"fonts"`` since fonts.css is
                at ``assets/fonts.css`` and font files are in ``assets/fonts/``.

        Returns:
            Complete CSS content as a string. Returns empty string if
            font_mapping is empty or contains no variants.

        Example:
            >>> css = generator.generate({"primary": variants}, font_path_prefix="fonts")
            >>> # Access fonts via CSS custom properties:
            >>> # font-family: var(--font-primary);
        """
        if not font_mapping:
            return ""

        css_parts = [
            "/* Auto-generated by Bengal Font Helper */",
            "/* See bengal.toml [fonts] section */",
            "",
        ]

        # Generate @font-face rules for each variant
        for variants in font_mapping.values():
            if not variants:
                continue

            family = variants[0].family  # All variants share same family

            css_parts.append(f"/* {family} */")

            for variant in variants:
                url = f"{font_path_prefix}/{variant.filename}"

                # Determine format from file extension
                font_format = "woff2" if ".woff2" in url else "truetype"

                css_parts.append("@font-face {")
                css_parts.append(f"  font-family: '{variant.family}';")
                css_parts.append(f"  font-weight: {variant.weight};")
                css_parts.append(f"  font-style: {variant.style};")
                css_parts.append("  font-display: swap;")
                css_parts.append(f"  src: url('{url}') format('{font_format}');")
                css_parts.append("}")
                css_parts.append("")

        # Generate CSS custom properties
        css_parts.append("/* CSS Custom Properties */")
        css_parts.append(":root {")

        for font_name, variants in font_mapping.items():
            if variants:
                family = variants[0].family
                css_parts.append(f"  --font-{font_name}: '{family}';")

        css_parts.append("}")
        css_parts.append("")

        return "\n".join(css_parts)
