#!/usr/bin/env python3
"""
Brand Preview Generator
Generates a visual HTML preview of font pairings and color palette
so users can see the brand direction before approving.

Usage:
    python3 generate_brand_preview.py \
        --output /path/to/brand-preview.html \
        --name "BrandName" \
        --tagline "Simple POS on your phone" \
        --primary "#2563EB" \
        --secondary "#EFF6FF" \
        --accent "#10B981" \
        --neutral-dark "#1E3A5F" \
        --neutral-light "#F8FAFC" \
        --options "Lexend+Atkinson Hyperlegible,Nunito+Nunito Sans,Figtree+Rubik"
"""

import argparse
import os
import sys

def parse_font_options(options_str):
    """Parse font options string into list of (heading, body) tuples."""
    options = []
    for pair in options_str.split(","):
        parts = pair.strip().split("+")
        if len(parts) == 2:
            options.append((parts[0].strip(), parts[1].strip()))
        elif len(parts) == 1:
            options.append((parts[0].strip(), parts[0].strip()))
    return options

def font_to_google_id(font_name):
    """Convert font name to Google Fonts URL parameter."""
    return font_name.replace(" ", "+")

def generate_html(name, tagline, primary, secondary, accent, neutral_dark, neutral_light, font_options):
    """Generate the brand preview HTML."""
    
    # Build Google Fonts imports for all font options
    all_fonts = set()
    for heading, body in font_options:
        all_fonts.add(font_to_google_id(heading))
        all_fonts.add(font_to_google_id(body))
    
    fonts_param = "&".join([f"family={f}:wght@400;600;700" for f in all_fonts])
    google_fonts_url = f"https://fonts.googleapis.com/css2?{fonts_param}&display=swap"

    # Build font option cards
    option_cards = ""
    for i, (heading_font, body_font) in enumerate(font_options, 1):
        label = ["A", "B", "C", "D", "E"][i - 1]
        heading_id = font_to_google_id(heading_font)
        body_id = font_to_google_id(body_font)
        gf_heading_url = f"https://fonts.google.com/specimen/{heading_id}"
        gf_body_url = f"https://fonts.google.com/specimen/{body_id}"

        option_cards += f"""
        <div class="font-option" id="option-{label}">
            <div class="option-label">Option {label}</div>
            <div class="font-meta">
                <span>Headlines: <a href="{gf_heading_url}" target="_blank"><strong>{heading_font}</strong></a></span>
                <span>Body: <a href="{gf_body_url}" target="_blank"><strong>{body_font}</strong></a></span>
            </div>
            <div class="font-preview-block">
                <div class="preview-headline" style="font-family: '{heading_font}', sans-serif;">
                    {name}
                </div>
                <div class="preview-subheadline" style="font-family: '{heading_font}', sans-serif;">
                    {tagline}
                </div>
                <div class="preview-body" style="font-family: '{body_font}', sans-serif;">
                    {name} helps you stay on top of your business — simple,
                    reliable, and built for the way you actually work.
                    Clear data. Smart decisions. Less guesswork.
                </div>
                <div class="preview-ui">
                    <button class="preview-btn-primary" style="font-family: '{body_font}', sans-serif; background: {primary};">
                        Get Started
                    </button>
                    <button class="preview-btn-secondary" style="font-family: '{body_font}', sans-serif; border-color: {primary}; color: {primary};">
                        Learn More
                    </button>
                </div>
                <div class="preview-ui-element" style="font-family: '{body_font}', sans-serif;">
                    <div class="ui-label">Form Label</div>
                    <div class="ui-input">Placeholder text here</div>
                    <div class="ui-helper">This is helper text explaining the field above.</div>
                </div>
                <div class="preview-sizes" style="font-family: '{heading_font}', sans-serif;">
                    <span style="font-size: 32px; font-weight: 700;">Aa</span>
                    <span style="font-size: 24px; font-weight: 600;">Aa</span>
                    <span style="font-size: 18px; font-weight: 500;">Aa</span>
                    <span style="font-family: '{body_font}', sans-serif; font-size: 14px;">Aa</span>
                    <span style="font-family: '{body_font}', sans-serif; font-size: 12px;">Aa</span>
                </div>
            </div>
            <div class="option-cta">
                <button class="select-btn" onclick="selectOption('{label}')">Select Option {label}</button>
            </div>
        </div>
        """

    # Build color swatches
    colors = [
        (primary, "Primary", "Main brand color — buttons, headers, CTAs"),
        (secondary, "Secondary", "Backgrounds, light sections"),
        (accent, "Accent", "Success states, highlights"),
        (neutral_dark, "Dark Neutral", "Body text, dark elements"),
        (neutral_light, "Light Neutral", "Light backgrounds, cards"),
    ]

    color_swatches = ""
    for hex_val, label, desc in colors:
        text_color = "#ffffff" if is_dark(hex_val) else "#1a1a1a"
        color_swatches += f"""
        <div class="color-swatch">
            <div class="swatch-block" style="background: {hex_val}; color: {text_color};">
                <span class="swatch-hex">{hex_val}</span>
            </div>
            <div class="swatch-info">
                <div class="swatch-label">{label}</div>
                <div class="swatch-desc">{desc}</div>
            </div>
        </div>
        """

    html = f"""<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{name} — Brand Preview</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="{google_fonts_url}" rel="stylesheet">
    <style>
        :root {{
            --primary: {primary};
            --secondary: {secondary};
            --accent: {accent};
            --neutral-dark: {neutral_dark};
            --neutral-light: {neutral_light};
        }}

        * {{ margin: 0; padding: 0; box-sizing: border-box; }}

        body {{
            font-family: system-ui, sans-serif;
            background: #f4f5f7;
            color: #111;
            padding: 40px 20px;
        }}

        .container {{
            max-width: 960px;
            margin: 0 auto;
        }}

        /* Header */
        .header {{
            text-align: center;
            margin-bottom: 48px;
        }}
        .header h1 {{
            font-size: 28px;
            font-weight: 700;
            color: #111;
        }}
        .header p {{
            color: #666;
            margin-top: 6px;
            font-size: 15px;
        }}
        .badge {{
            display: inline-block;
            background: {primary};
            color: white;
            font-size: 11px;
            font-weight: 600;
            padding: 3px 10px;
            border-radius: 999px;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            margin-bottom: 12px;
        }}

        /* Section */
        .section {{
            margin-bottom: 48px;
        }}
        .section-title {{
            font-size: 13px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.08em;
            color: #888;
            margin-bottom: 16px;
            padding-bottom: 8px;
            border-bottom: 1px solid #e0e0e0;
        }}

        /* Color palette */
        .color-palette {{
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
            gap: 16px;
        }}
        .color-swatch {{
            border-radius: 12px;
            overflow: hidden;
            background: white;
            box-shadow: 0 1px 4px rgba(0,0,0,0.08);
        }}
        .swatch-block {{
            height: 80px;
            display: flex;
            align-items: flex-end;
            padding: 10px 12px;
        }}
        .swatch-hex {{
            font-size: 12px;
            font-family: monospace;
            font-weight: 600;
            opacity: 0.85;
        }}
        .swatch-info {{
            padding: 10px 12px;
        }}
        .swatch-label {{
            font-size: 13px;
            font-weight: 600;
            color: #222;
        }}
        .swatch-desc {{
            font-size: 11px;
            color: #888;
            margin-top: 2px;
        }}

        /* Font Options */
        .font-options {{
            display: flex;
            flex-direction: column;
            gap: 24px;
        }}
        .font-option {{
            background: white;
            border-radius: 16px;
            padding: 28px;
            box-shadow: 0 1px 4px rgba(0,0,0,0.08);
            border: 2px solid transparent;
            transition: border-color 0.2s, box-shadow 0.2s;
        }}
        .font-option.selected {{
            border-color: {primary};
            box-shadow: 0 0 0 4px {primary}22;
        }}
        .option-label {{
            font-size: 11px;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.1em;
            color: {primary};
            margin-bottom: 8px;
        }}
        .font-meta {{
            display: flex;
            gap: 20px;
            font-size: 13px;
            color: #555;
            margin-bottom: 24px;
            flex-wrap: wrap;
        }}
        .font-meta a {{
            color: {primary};
            text-decoration: none;
        }}
        .font-meta a:hover {{
            text-decoration: underline;
        }}
        .font-preview-block {{
            background: {neutral_light};
            border-radius: 12px;
            padding: 28px;
            display: flex;
            flex-direction: column;
            gap: 16px;
        }}
        .preview-headline {{
            font-size: 36px;
            font-weight: 700;
            color: {neutral_dark};
            line-height: 1.1;
        }}
        .preview-subheadline {{
            font-size: 18px;
            font-weight: 500;
            color: {primary};
        }}
        .preview-body {{
            font-size: 15px;
            color: #444;
            line-height: 1.65;
            max-width: 520px;
        }}
        .preview-ui {{
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
        }}
        .preview-btn-primary {{
            padding: 10px 22px;
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
        }}
        .preview-btn-secondary {{
            padding: 10px 22px;
            background: transparent;
            border: 2px solid;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
        }}
        .preview-ui-element {{
            display: flex;
            flex-direction: column;
            gap: 4px;
        }}
        .ui-label {{
            font-size: 12px;
            font-weight: 600;
            color: #555;
        }}
        .ui-input {{
            background: white;
            border: 1.5px solid #d0d5dd;
            border-radius: 8px;
            padding: 9px 14px;
            font-size: 14px;
            color: #888;
            max-width: 280px;
        }}
        .ui-helper {{
            font-size: 11px;
            color: #999;
        }}
        .preview-sizes {{
            display: flex;
            align-items: baseline;
            gap: 20px;
            color: {neutral_dark};
        }}
        .option-cta {{
            margin-top: 20px;
            display: flex;
            justify-content: flex-end;
        }}
        .select-btn {{
            background: {primary};
            color: white;
            border: none;
            padding: 10px 24px;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: opacity 0.2s;
        }}
        .select-btn:hover {{ opacity: 0.85; }}

        /* Selected banner */
        .selected-banner {{
            display: none;
            background: {primary};
            color: white;
            text-align: center;
            padding: 16px;
            border-radius: 12px;
            font-weight: 600;
            font-size: 15px;
            margin-top: 24px;
        }}
        .selected-banner.visible {{ display: block; }}
    </style>
</head>
<body>
<div class="container">

    <div class="header">
        <div class="badge">Brand Preview</div>
        <h1>{name}</h1>
        <p>Review the color palette and typography options below. Click "Select" on your preferred option.</p>
    </div>

    <!-- Color Palette -->
    <div class="section">
        <div class="section-title">Color Palette</div>
        <div class="color-palette">
            {color_swatches}
        </div>
    </div>

    <!-- Typography Options -->
    <div class="section">
        <div class="section-title">Typography Options — Pick One</div>
        <div class="font-options">
            {option_cards}
        </div>
    </div>

    <div class="selected-banner" id="selected-banner">
        ✅ Option <span id="selected-label"></span> selected! Share this with your team.
    </div>

</div>

<script>
    function selectOption(label) {{
        document.querySelectorAll('.font-option').forEach(el => el.classList.remove('selected'));
        document.getElementById('option-' + label).classList.add('selected');
        document.getElementById('selected-label').textContent = label;
        document.getElementById('selected-banner').classList.add('visible');
        document.getElementById('selected-banner').scrollIntoView({{ behavior: 'smooth', block: 'nearest' }});
    }}
</script>
</body>
</html>"""

    return html


def is_dark(hex_color):
    """Rough check if a hex color is dark (for text contrast)."""
    hex_color = hex_color.lstrip("#")
    r, g, b = int(hex_color[0:2], 16), int(hex_color[2:4], 16), int(hex_color[4:6], 16)
    luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255
    return luminance < 0.5


def main():
    parser = argparse.ArgumentParser(description="Generate brand preview HTML")
    parser.add_argument("--output", required=True, help="Output HTML file path")
    parser.add_argument("--name", required=True, help="Brand name")
    parser.add_argument("--tagline", default="", help="Brand tagline")
    parser.add_argument("--primary", default="#2563EB", help="Primary color hex")
    parser.add_argument("--secondary", default="#EFF6FF", help="Secondary color hex")
    parser.add_argument("--accent", default="#10B981", help="Accent color hex")
    parser.add_argument("--neutral-dark", default="#1E3A5F", help="Dark neutral hex")
    parser.add_argument("--neutral-light", default="#F8FAFC", help="Light neutral hex")
    parser.add_argument(
        "--options",
        default="Lexend+Atkinson Hyperlegible,Nunito+Nunito Sans,Figtree+Rubik",
        help="Comma-separated font pairs (heading+body)"
    )
    args = parser.parse_args()

    font_options = parse_font_options(args.options)

    html = generate_html(
        name=args.name,
        tagline=args.tagline,
        primary=args.primary,
        secondary=args.secondary,
        accent=args.accent,
        neutral_dark=getattr(args, "neutral_dark"),
        neutral_light=getattr(args, "neutral_light"),
        font_options=font_options,
    )

    os.makedirs(os.path.dirname(os.path.abspath(args.output)), exist_ok=True)
    with open(args.output, "w", encoding="utf-8") as f:
        f.write(html)

    print(f"✓ Brand preview generated: {args.output}")
    print(f"  Colors: {args.primary} | {args.secondary} | {args.accent}")
    print(f"  Font options: {len(font_options)}")


if __name__ == "__main__":
    main()
