"""CSS-in-JS theme formatter."""

from tokens import _to_camel, classify_palette_tokens


def generate_css_in_js(result: dict, palette_tokens: dict) -> str:
    """Generate a CSS-in-JS theme object (ES module).

    Expects result to contain: recommended_palette, foundation (optional),
    palette_display (optional, for comment).
    """
    foundation = result.get("foundation") or {}
    palette = result["recommended_palette"]
    display_name = result.get("palette_display") or palette

    classified = classify_palette_tokens(palette_tokens)

    # Build a camelCase version of the color map, keyed by CSS var name
    colors_camel: dict = {}
    for group, values in classified["colors"].items():
        if isinstance(values, dict):
            colors_camel[group] = {
                _to_camel(name): f"--color-{group}-{name}"
                for name in values
            }
        else:
            colors_camel[group] = f"--color-{group}"

    lines = []
    lines.append("// Universal Design System — CSS-in-JS Theme")
    lines.append(f"// Palette: {display_name}")
    lines.append("// Generated by: python src/scripts/design_system.py")
    lines.append("//")
    lines.append("// Compatible with styled-components, Emotion, and any CSS-in-JS library.")
    lines.append("// Tokens reference CSS custom properties so themes can be swapped at runtime")
    lines.append("// by changing the data-theme attribute on the root element.")
    lines.append("")

    lines.append("export const theme = {")

    # --- colors ---
    lines.append("  colors: {")
    priority_groups = ["brand", "text", "bg", "border", "status"]
    sorted_groups = [g for g in priority_groups if g in colors_camel]
    sorted_groups += sorted(g for g in colors_camel if g not in priority_groups)

    for group in sorted_groups:
        values = colors_camel[group]
        if isinstance(values, dict):
            lines.append(f"    {group}: {{")
            for name, var_name in sorted(values.items()):
                lines.append(f"      {name}: 'var({var_name})',")
            lines.append("    },")
        else:
            lines.append(f"    {group}: 'var({values})',")
    lines.append("  },")

    # --- spacing ---
    spacing = foundation.get("spacing", {})
    if spacing:
        lines.append("  spacing: {")
        for name in sorted(spacing.keys(), key=lambda x: int(x) if x.isdigit() else 0):
            lines.append(f"    '{name}': 'var(--space-{name})',")
        lines.append("  },")

    # --- shadows (merge foundation + palette overrides) ---
    shadows = {**foundation.get("shadow", {}), **classified["shadows"]}
    if shadows:
        lines.append("  shadows: {")
        for name in sorted(shadows.keys()):
            lines.append(f"    {name}: 'var(--shadow-{name})',")
        lines.append("  },")

    # --- radii (merge foundation + palette overrides) ---
    radii = {**foundation.get("radius", {}), **classified["radii"]}
    if radii:
        lines.append("  radii: {")
        for name in sorted(radii.keys()):
            lines.append(f"    {name}: 'var(--radius-{name})',")
        lines.append("  },")

    # --- typography ---
    font_families = foundation.get("font_family", {})
    font_sizes = foundation.get("font_size", {})
    if font_families or font_sizes:
        lines.append("  typography: {")
        if font_families:
            lines.append("    fontFamily: {")
            for name in sorted(font_families.keys()):
                lines.append(f"      {name}: 'var(--font-family-{name})',")
            lines.append("    },")
        if font_sizes:
            lines.append("    fontSize: {")
            for name in sorted(font_sizes.keys()):
                lines.append(f"      '{name}': 'var(--font-size-{name})',")
            lines.append("    },")
        lines.append("  },")

    lines.append("};")

    # --- usage examples ---
    lines.append("""
// ---------------------------------------------------------------------------
// Usage with styled-components
// ---------------------------------------------------------------------------
//
// import styled from 'styled-components';
// import { theme } from './theme';
//
// const Button = styled.button`
//   background: ${theme.colors.brand.primary};
//   color: ${theme.colors.text.primary};
//   padding: ${theme.spacing['2']} ${theme.spacing['4']};
//   border-radius: ${theme.radii.md};
//   box-shadow: ${theme.shadows.sm};
//   font-family: ${theme.typography.fontFamily.body};
// `;
//
// ---------------------------------------------------------------------------
// Usage with Emotion
// ---------------------------------------------------------------------------
//
// /** @jsxImportSource @emotion/react */
// import { css } from '@emotion/react';
// import { theme } from './theme';
//
// const buttonStyle = css`
//   background: ${theme.colors.brand.primary};
//   color: ${theme.colors.text.primary};
//   padding: ${theme.spacing['2']} ${theme.spacing['4']};
//   border-radius: ${theme.radii.md};
// `;
//
// function Button({ children }) {
//   return <button css={buttonStyle}>{children}</button>;
// }""")

    return "\n".join(lines)
