# 3_design_generator.py

import os
import json
import argparse
import time
from pathlib import Path
from typing import Dict, List, Optional
import re

from dotenv import load_dotenv
import vertexai
from vertexai.generative_models import GenerativeModel, GenerationResponse, GenerationConfig

# --- Model & Pricing Configuration ---
MODELS_CONFIG = [
    {
        "name": "Gemini 2.5 Pro (GA)",
        "model_id": "gemini-2.5-pro",
        "location": "us-east1",
        "pricing": { "input": 1.25 / 1_000_000, "output": 10.00 / 1_000_000 }
    },
    {
        "name": "Gemini 2.5 Flash (GA)",
        "model_id": "gemini-2.5-flash",
        "location": "us-east1",
        "pricing": { "input": 0.30 / 1_000_000, "output": 2.50 / 1_000_000 }
    },
    {
        "name": "Gemini 2.5 Flash Lite (Preview)",
        "model_id": "gemini-2.5-flash-lite",
        "location": "global",
        "pricing": { "input": 0.10 / 1_000_000, "output": 0.40 / 1_000_000 }
    }
]

DEFAULT_MODEL_INDEX = 0  # Gemini 2.5 Pro for design generation

def setup_gcp_credentials():
    """Auto-setup GCP credentials from default location or environment."""
    import os
    import json
    from pathlib import Path
    
    # Default paths to check for credentials (multiple structures)
    credential_paths = [
        Path("../data/credentials/gcp_key.json"),           # Development: from dashboard/scripts
        Path("./data/credentials/gcp_key.json"),            # Alternative: from project root
        Path("../dashboard/data/credentials/gcp_key.json"), # Production with dashboard: from /test/scripts
        Path("dashboard/data/credentials/gcp_key.json"),    # Alternative production with dashboard
        Path("data/credentials/gcp_key.json")               # Fallback
    ]
    
    # Check if GOOGLE_APPLICATION_CREDENTIALS is already set
    if not os.getenv("GOOGLE_APPLICATION_CREDENTIALS"):
        # Try to find credentials file in order of preference
        key_path = None
        for path in credential_paths:
            if path.exists():
                key_path = path
                break
        
        if key_path:
            os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = str(key_path.absolute())
            print(f"🔑 Auto-detected GCP key: {key_path}")
    
    # Check if GCLOUD_PROJECT is already set
    if not os.getenv("GCLOUD_PROJECT"):
        # Try to read project ID from the key file
        creds_path = os.getenv("GOOGLE_APPLICATION_CREDENTIALS")
        if creds_path and Path(creds_path).exists():
            try:
                with open(creds_path, 'r') as f:
                    key_data = json.load(f)
                    project_id = key_data.get("project_id")
                    if project_id:
                        os.environ["GCLOUD_PROJECT"] = project_id
                        print(f"🌐 Auto-detected GCP project: {project_id}")
            except Exception as e:
                print(f"⚠️ Could not read project ID from key file: {e}")

def get_gemini_model_with_schema(model_index: int, response_schema: Dict) -> GenerativeModel:
    """Get Gemini model with structured output schema."""
    # Auto-setup credentials if not already configured
    setup_gcp_credentials()
    
    active_model_config = MODELS_CONFIG[model_index]
    gcloud_project = os.getenv("GCLOUD_PROJECT")
    if not gcloud_project:
        raise ValueError("GCLOUD_PROJECT not found. Please check your GCP setup.")
    
    vertexai.init(project=gcloud_project, location=active_model_config["location"])
    
    generation_config = GenerationConfig(
        response_mime_type="application/json",
        response_schema=response_schema
    )
    
    return GenerativeModel(
        active_model_config["model_id"],
        generation_config=generation_config
    )

def print_usage_and_cost(response: GenerationResponse, model_index: int, stage_name: str) -> dict:
    """Calculate and print API usage costs."""
    usage_data = {"cost": 0, "tokens": 0}
    try:
        active_model_config = MODELS_CONFIG[model_index]
        usage = response.usage_metadata
        pricing = active_model_config["pricing"]
        input_tokens = usage.prompt_token_count
        output_tokens = usage.candidates_token_count
        usage_data["cost"] = (input_tokens * pricing["input"]) + (output_tokens * pricing["output"])
        usage_data["tokens"] = input_tokens + output_tokens
        print(f"   - Usage for {stage_name}: {(usage_data['tokens']):,} tokens, cost: ${usage_data['cost']:.6f}")
    except Exception: 
        pass
    return usage_data

def create_design_schema() -> Dict:
    """Define the structured output schema for design generation."""
    return {
        "type": "object",
        "properties": {
            "designs": {
                "type": "array",
                "items": {
                    "type": "object",
                    "properties": {
                        "design_name": {"type": "string"},
                        "design_philosophy": {"type": "string"},
                        "visual_direction": {"type": "string"},
                        "target_emotion": {"type": "string"},
                        "color_scheme": {
                            "type": "object",
                            "properties": {
                                "primary": {"type": "string"},
                                "secondary": {"type": "string"},
                                "accent": {"type": "string"},
                                "background": {"type": "string"},
                                "surface": {"type": "string"},
                                "text_primary": {"type": "string"},
                                "text_secondary": {"type": "string"},
                                "success": {"type": "string"},
                                "warning": {"type": "string"},
                                "error": {"type": "string"},
                                "gradient_primary": {"type": "string"},
                                "gradient_secondary": {"type": "string"}
                            },
                            "required": ["primary", "secondary", "accent", "background", "text_primary"]
                        },
                        "typography": {
                            "type": "object",
                            "properties": {
                                "heading_font": {"type": "string"},
                                "heading_weight": {"type": "string"},
                                "body_font": {"type": "string"},
                                "body_weight": {"type": "string"},
                                "accent_font": {"type": "string"},
                                "font_scale": {
                                    "type": "object",
                                    "properties": {
                                        "h1": {"type": "string"},
                                        "h2": {"type": "string"},
                                        "h3": {"type": "string"},
                                        "h4": {"type": "string"},
                                        "h5": {"type": "string"},
                                        "h6": {"type": "string"},
                                        "body": {"type": "string"},
                                        "small": {"type": "string"},
                                        "large": {"type": "string"}
                                    }
                                },
                                "line_heights": {
                                    "type": "object",
                                    "properties": {
                                        "tight": {"type": "string"},
                                        "normal": {"type": "string"},
                                        "relaxed": {"type": "string"}
                                    }
                                }
                            }
                        },
                        "spacing": {
                            "type": "object",
                            "properties": {
                                "unit": {"type": "string"},
                                "xs": {"type": "string"},
                                "sm": {"type": "string"},
                                "md": {"type": "string"},
                                "lg": {"type": "string"},
                                "xl": {"type": "string"},
                                "xxl": {"type": "string"}
                            }
                        },
                        "components": {
                            "type": "object",
                            "properties": {
                                "header": {
                                    "type": "object",
                                    "properties": {
                                        "style": {"type": "string"},
                                        "height": {"type": "string"},
                                        "background": {"type": "string"},
                                        "backdrop_filter": {"type": "string"},
                                        "shadow": {"type": "string"},
                                        "sticky": {"type": "boolean"},
                                        "layout": {"type": "string"},
                                        "logo_size": {"type": "string"},
                                        "padding": {"type": "string"}
                                    }
                                },
                                "navigation": {
                                    "type": "object",
                                    "properties": {
                                        "style": {"type": "string"},
                                        "mobile_style": {"type": "string"},
                                        "hover_effect": {"type": "string"},
                                        "active_indicator": {"type": "string"},
                                        "font_size": {"type": "string"},
                                        "spacing": {"type": "string"}
                                    }
                                },
                                "hero": {
                                    "type": "object",
                                    "properties": {
                                        "layout": {"type": "string"},
                                        "height": {"type": "string"},
                                        "content_alignment": {"type": "string"},
                                        "overlay": {"type": "string"},
                                        "background_effect": {"type": "string"},
                                        "animation": {"type": "string"},
                                        "text_shadow": {"type": "string"}
                                    }
                                },
                                "buttons": {
                                    "type": "object",
                                    "properties": {
                                        "primary_style": {"type": "string"},
                                        "secondary_style": {"type": "string"},
                                        "border_radius": {"type": "string"},
                                        "padding": {"type": "string"},
                                        "hover_effect": {"type": "string"},
                                        "transition": {"type": "string"},
                                        "font_weight": {"type": "string"},
                                        "text_transform": {"type": "string"}
                                    }
                                },
                                "cards": {
                                    "type": "object",
                                    "properties": {
                                        "style": {"type": "string"},
                                        "shadow": {"type": "string"},
                                        "border_radius": {"type": "string"},
                                        "hover_effect": {"type": "string"},
                                        "padding": {"type": "string"},
                                        "background": {"type": "string"},
                                        "border": {"type": "string"}
                                    }
                                },
                                "footer": {
                                    "type": "object",
                                    "properties": {
                                        "layout": {"type": "string"},
                                        "background": {"type": "string"},
                                        "sections": {"type": "integer"},
                                        "padding": {"type": "string"},
                                        "text_alignment": {"type": "string"}
                                    }
                                },
                                "forms": {
                                    "type": "object",
                                    "properties": {
                                        "input_style": {"type": "string"},
                                        "label_style": {"type": "string"},
                                        "border_radius": {"type": "string"},
                                        "focus_effect": {"type": "string"},
                                        "validation_style": {"type": "string"}
                                    }
                                }
                            }
                        },
                        "effects": {
                            "type": "object",
                            "properties": {
                                "animations": {"type": "array", "items": {"type": "string"}},
                                "transitions": {"type": "string"},
                                "hover_states": {"type": "string"},
                                "scroll_effects": {"type": "array", "items": {"type": "string"}},
                                "loading_animations": {"type": "array", "items": {"type": "string"}},
                                "micro_interactions": {"type": "array", "items": {"type": "string"}}
                            }
                        },
                        "layout": {
                            "type": "object",
                            "properties": {
                                "grid_system": {"type": "string"},
                                "max_width": {"type": "string"},
                                "breakpoints": {
                                    "type": "object",
                                    "properties": {
                                        "mobile": {"type": "string"},
                                        "tablet": {"type": "string"},
                                        "desktop": {"type": "string"},
                                        "wide": {"type": "string"}
                                    }
                                },
                                "container_padding": {"type": "string"},
                                "section_spacing": {"type": "string"}
                            }
                        },
                        "accessibility": {
                            "type": "object",
                            "properties": {
                                "focus_indicators": {"type": "string"},
                                "contrast_ratio": {"type": "string"},
                                "touch_targets": {"type": "string"},
                                "screen_reader_support": {"type": "boolean"}
                            }
                        },
                        "modern_features": {
                            "type": "object",
                            "properties": {
                                "glassmorphism": {"type": "boolean"},
                                "neumorphism": {"type": "boolean"},
                                "gradient_overlays": {"type": "boolean"},
                                "parallax_scrolling": {"type": "boolean"},
                                "smooth_scrolling": {"type": "boolean"},
                                "dark_mode_support": {"type": "boolean"},
                                "css_grid": {"type": "boolean"},
                                "css_custom_properties": {"type": "boolean"}
                            }
                        }
                    },
                    "required": ["design_name", "design_philosophy", "color_scheme", "typography", "components"]
                }
            },
            "design_brief": {
                "type": "object",
                "properties": {
                    "overall_strategy": {"type": "string"},
                    "target_audience_analysis": {"type": "string"},
                    "competitive_differentiation": {"type": "string"},
                    "technical_requirements": {"type": "array", "items": {"type": "string"}},
                    "recommended_design": {"type": "string"}
                }
            }
        },
        "required": ["designs", "design_brief"]
    }

def load_site_brief(site_dir: Path) -> Dict:
    """Load the site brief from the previous script."""
    brief_path = site_dir / "site_brief.json"
    if not brief_path.exists():
        raise FileNotFoundError(f"Site brief not found at {brief_path}")
    
    with open(brief_path, 'r', encoding='utf-8') as f:
        return json.load(f)

def prepare_content_summary(site_brief: Dict) -> str:
    """Create a comprehensive summary of site content for design context."""
    content_summary = []
    
    # Text-only generation path
    if 'content_brief' in site_brief and 'brand_profile' not in site_brief:
        content_summary.append(f"COMPANY NAME: {site_brief.get('company_name', 'N/A')}")
        content_summary.append(f"\nDESIGN BRIEF & COMPANY INFO:\n{site_brief['content_brief']}")
        return '\n'.join(content_summary)
        
    # Add brand context
    brand_profile = site_brief.get('brand_profile', {})
    content_summary.append(f"BRAND IDENTITY: {brand_profile.get('brand_identity', 'Not specified')}")
    
    # Add current design analysis
    design_style = brand_profile.get('design_style', 'Not specified')
    content_summary.append(f"CURRENT STYLE: {design_style}")
    
    # Add business context
    site_pages = site_brief.get('site_pages', [])
    page_types = []
    content_highlights = []
    
    for page in site_pages:
        page_key = page.get('page_key', '')
        content_sections = page.get('content_sections', {})
        
        page_types.append(page_key)
        
        # Extract key content points
        for section_title, content in content_sections.items():
            if isinstance(content, str) and len(content) > 50:
                # Look for embedded images to understand content richness
                image_count = len(re.findall(r'\[image: [^\]]+\]', content))
                content_preview = re.sub(r'\[image: [^\]]+\]', '', content).strip()[:100]
                if content_preview:
                    content_highlights.append(f"{section_title}: {content_preview}{'...' if len(content_preview) >= 100 else ''} ({image_count} images)")
    
    content_summary.append(f"PAGE TYPES: {', '.join(page_types)}")
    content_summary.append(f"KEY CONTENT AREAS: {'; '.join(content_highlights[:5])}")
    
    # Add technical context
    extraction_summary = site_brief.get('extraction_summary', {})
    success_rate = extraction_summary.get('overall_success_rate', '0%')
    content_summary.append(f"CONTENT EXTRACTION SUCCESS: {success_rate}")
    
    return '\n'.join(content_summary)

def generate_designs(site_brief: Dict, model_index: int) -> tuple[Dict, Dict]:
    """Generate 3 distinct design variations using Gemini structured output."""
    
    # Create the response schema
    print("   🔧 Preparing design generation schema...")
    response_schema = create_design_schema()
    
    # Initialize model with structured output
    print("   🤖 Initializing Gemini model with structured output...")
    model = get_gemini_model_with_schema(model_index, response_schema)
    if not model:
        raise ValueError("Could not initialize design generation model.")
    
    active_model_config = MODELS_CONFIG[model_index]
    print(f"   📊 Analyzing site content and preparing context...")
    
    # Prepare comprehensive context
    brand_profile = site_brief.get('brand_profile', {})
    navigation_links = site_brief.get('navigation_links', [])
    site_metadata = site_brief.get('site_metadata', {})
    content_summary = prepare_content_summary(site_brief)
    
    print(f"   🎨 Sending design request to Gemini ('{active_model_config['name']}')...")
    print(f"   ⏳ This may take 30-60 seconds for comprehensive design generation...")
    
    # Detect business type for theme customization
    brand_identity = brand_profile.get('brand_identity', '').lower()
    business_keywords = brand_profile.get('business_keywords', [])
    all_business_text = f"{brand_identity} {' '.join(business_keywords)}".lower()
    
    # Determine if this is a restaurant/food business
    is_restaurant = any(keyword in all_business_text for keyword in [
        'restaurant', 'food', 'dining', 'kitchen', 'chef', 'menu', 'cuisine', 
        'bar', 'grill', 'cafe', 'bistro', 'eatery', 'tavern', 'pub', 'deli'
    ])
    
    # Create business-specific design guidance
    if is_restaurant:
        design_3_theme = """
**DESIGN 3: "CULINARY ARTISTRY"** (Restaurant-Specific Alternative Theme)
   - Embrace the restaurant's unique culinary personality with creative flair
   - Use food-inspired color palettes (rich burgundies, warm golds, fresh greens, deep browns)
   - Incorporate textures that evoke dining experiences (wood grain, marble, linen, chalkboard)
   - Creative layouts that tell the restaurant's story through visual hierarchy
   - Bold typography mixing script fonts with modern sans-serif for menu appeal
   - Interactive menu presentations and chef showcase areas
   - Warm, inviting atmosphere that makes visitors hungry and excited
   - Creative elements: parallax food imagery, animated ingredient showcases, reservation CTAs
   - Can be more artistic and emotional than typical business sites
   - Target: Food enthusiasts + experience seekers + local community + special occasion diners"""
    else:
        design_3_theme = """
**DESIGN 3: "INDUSTRY INNOVATOR"** (Business-Specific Alternative Theme)
   - Embrace the business's unique industry personality with creative interpretation
   - Use industry-appropriate color psychology and visual metaphors
   - Incorporate textures and patterns that reflect the business nature
   - Creative layouts that showcase expertise and differentiation
   - Bold typography that commands authority in the industry
   - Interactive elements specific to the business type and customer journey
   - Professional yet memorable aesthetic that builds trust and stands out
   - Creative elements: industry-specific animations, interactive showcases, unique navigation
   - More creative freedom while maintaining professional credibility
   - Target: Industry professionals + decision makers + specialized audience + competitors"""

    prompt = f"""You are a world-class web designer creating three distinct design variations for a website redesign project.

CURRENT BRAND ANALYSIS:
{json.dumps(brand_profile, indent=2)}

SITE NAVIGATION:
{json.dumps(navigation_links, indent=2)}

SITE METADATA:
{json.dumps(site_metadata, indent=2)}

CONTENT ANALYSIS:
{content_summary}

🎨 **CRITICAL DESIGN THEME REQUIREMENTS - MUST FOLLOW EXACTLY:**

**DESIGN 1: "CLEAN LIGHT PROFESSIONAL"** (Light Theme - Always Professional)
   - Clean, bright, minimalist aesthetic with plenty of white space
   - Light color palette: whites (#ffffff), light grays (#f8f9fa, #e9ecef), soft blues (#e3f2fd)
   - Professional typography with excellent readability on light backgrounds
   - Subtle shadows (0 2px 10px rgba(0,0,0,0.1)) and clean lines for modern corporate appeal
   - Light backgrounds with dark text (#333333, #212529) for maximum contrast and accessibility
   - Sophisticated yet approachable for business credibility and trust
   - Clean button styles with subtle hover effects
   - Minimal, professional navigation with clear hierarchy
   - Target: Professional clients + corporate partnerships + trust-building + accessibility-focused users

**DESIGN 2: "SOPHISTICATED DARK MODERN"** (Dark Theme - Always Professional)
   - Elegant dark theme with premium feel and modern sophistication
   - Dark color palette: deep navies (#1a1a2e, #16213e), charcoals (#2c2c2c), rich blacks (#0f0f23)
   - Accent with bright colors (#00d4ff, #64ffda, #ff6b6b) for contrast and energy
   - Premium typography with generous spacing for luxury appeal
   - Light text (#ffffff, #f8f9fa) on dark backgrounds for proper contrast
   - Subtle gradients and glowing effects (box-shadow: 0 0 20px rgba(100,255,218,0.3)) for modern tech aesthetic
   - Professional dark mode design that conveys innovation and premium quality
   - Sleek button designs with glow effects on hover
   - Modern navigation with subtle animations
   - Target: Tech-savvy users + premium market + modern professionals + night-mode preferences

{design_3_theme}

**MANDATORY DESIGN SPECIFICATIONS:**

**COLOR CONTRAST REQUIREMENTS:**
- Design 1 (Light): ALL text must be dark (#333333 or darker) on light backgrounds
- Design 2 (Dark): ALL text must be light (#ffffff or #f8f9fa) on dark backgrounds  
- Design 3: Choose appropriate contrast based on theme but maintain 4.5:1 minimum ratio
- NO light text on light backgrounds or dark text on dark backgrounds
- Test every color combination for readability

**PROFESSIONAL QUALITY STANDARDS:**
- All three designs must look professionally crafted and demo-ready
- Design 3 can be more creative but must still maintain professional credibility
- Use modern CSS techniques: CSS Grid, Flexbox, custom properties, smooth transitions
- Include hover states, focus indicators, and micro-interactions
- Ensure mobile-first responsive design for all screen sizes

**BUSINESS-SPECIFIC CUSTOMIZATION:**
- Analyze the business type and industry from the brand analysis
- Tailor Design 3 specifically to the business's unique characteristics
{"- Restaurant/Food businesses: Use culinary themes, warm colors, food imagery integration" if is_restaurant else "- Non-restaurant businesses: Use industry-appropriate themes and professional differentiation"}
- Make Design 3 the most memorable and distinctive while staying professional

**ENHANCED TECHNICAL SPECIFICATIONS:**
- Provide exact hex colors with accessibility testing for all color combinations
- Specify Google Fonts or web-safe font stacks with fallbacks
- Include precise measurements (rem, px, %, vh/vw) for consistent spacing
- Detail hover effects, focus states, and smooth transitions (0.3s ease)
- Plan for mobile-first responsive design with proper breakpoints
- Consider performance optimization and loading states

**MODERN IMPLEMENTATION FEATURES:**
- CSS Grid for complex layouts, Flexbox for component alignment
- CSS custom properties (variables) for theme consistency
- Smooth scroll behavior and micro-interactions
- Interactive elements with proper accessibility (ARIA labels, focus indicators)
- Modern button designs with appropriate touch targets (44px minimum)
- Gradient overlays and subtle shadow effects for depth
- Typography scale with proper line-heights for readability

**DESIGN VALIDATION CHECKLIST:**
✅ Design 1: Clean light theme with dark text on light backgrounds
✅ Design 2: Sophisticated dark theme with light text on dark backgrounds  
✅ Design 3: Creative theme appropriate to business type with proper contrast
✅ All designs are mobile-responsive and professionally polished
✅ Color contrast meets WCAG 2.1 AA standards (4.5:1 minimum)
✅ Typography is readable and hierarchically organized
✅ Interactive elements have proper hover and focus states

The designs should be implementable with modern HTML/CSS/JavaScript and create an impressive user experience that converts visitors into customers while maintaining the highest professional standards.

Return structured JSON following the exact schema provided."""

    try:
        print("   🚀 Generating 3 design variations...")
        print("   💭 AI is creating: Clean Light Professional, Sophisticated Dark Modern, Alternative Theme...")
        print("   ⏳ This may take 30-60 seconds for comprehensive design generation...")
        
        # Add retry logic for socket errors - increased for API stability
        max_retries = 5
        retry_delay = 10
        
        # Add small initial delay to help with rate limiting
        time.sleep(2)
        
        for attempt in range(max_retries):
            try:
                response = model.generate_content(prompt)
                break  # Success, exit retry loop
            except Exception as e:
                if "503" in str(e) or "Socket" in str(e):
                    if attempt < max_retries - 1:
                        print(f"   ⚠️ Socket error, retrying in {retry_delay} seconds... (attempt {attempt + 1}/{max_retries})")
                        time.sleep(retry_delay)
                        retry_delay *= 2  # Exponential backoff
                    else:
                        raise  # Re-raise on final attempt
                else:
                    raise  # Re-raise non-socket errors immediately
        
        print("   ✅ Response received! Processing design specifications...")
        usage_data = print_usage_and_cost(response, model_index, "Design Generation")
        
        print("   🔍 Parsing structured JSON response...")
        # Parse the structured JSON response
        designs_data = json.loads(response.text)
        
        # Validate that we got 3 designs
        designs = designs_data.get('designs', [])
        print(f"   📋 Validated {len(designs)} design variations successfully created")
        
        if len(designs) != 3:
            print(f"⚠️  Warning: Expected 3 designs, got {len(designs)}")
        else:
            for i, design in enumerate(designs, 1):
                design_name = design.get('design_name', f'Design {i}')
                print(f"      ✓ Design {i}: {design_name}")
        
        return designs_data, usage_data
        
    except json.JSONDecodeError as e:
        print(f"❌ JSON parsing error: {e}")
        print(f"Raw response: {response.text[:500]}...")
        raise
    except Exception as e:
        print(f"❌ Design generation error: {e}")
        raise

def create_design_preview(designs_data: Dict, output_dir: Path) -> None:
    """Create a simple HTML preview of the design concepts."""
    
    print("   🎨 Building visual design cards...")
    designs = designs_data.get('designs', [])
    design_brief = designs_data.get('design_brief', {})
    
    preview_html = f"""<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Design Concepts Preview</title>
    <style>
        body {{
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            margin: 0;
            padding: 20px;
            background: #f5f5f5;
            line-height: 1.6;
        }}
        .container {{
            max-width: 1200px;
            margin: 0 auto;
        }}
        .header {{
            text-align: center;
            margin-bottom: 40px;
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }}
        .design-grid {{
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
            gap: 30px;
            margin-bottom: 40px;
        }}
        .design-card {{
            background: white;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 8px 25px rgba(0,0,0,0.1);
            transition: transform 0.3s ease;
        }}
        .design-card:hover {{
            transform: translateY(-5px);
        }}
        .design-header {{
            padding: 20px;
            border-bottom: 2px solid #eee;
        }}
        .design-name {{
            font-size: 1.5em;
            font-weight: 700;
            margin: 0 0 10px 0;
        }}
        .design-philosophy {{
            color: #666;
            font-style: italic;
        }}
        .color-palette {{
            display: flex;
            height: 60px;
        }}
        .color-swatch {{
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 12px;
            font-weight: bold;
            text-shadow: 1px 1px 2px rgba(0,0,0,0.7);
        }}
        .design-details {{
            padding: 20px;
        }}
        .detail-section {{
            margin-bottom: 20px;
        }}
        .detail-title {{
            font-weight: 600;
            color: #333;
            margin-bottom: 8px;
        }}
        .detail-content {{
            color: #666;
            font-size: 0.9em;
        }}
        .brief-section {{
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }}
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>Website Design Concepts</h1>
            <p>Three distinct design directions for your website redesign</p>
        </div>
        
        <div class="design-grid">
"""

    for i, design in enumerate(designs, 1):
        color_scheme = design.get('color_scheme', {})
        typography = design.get('typography', {})
        components = design.get('components', {})
        
        # Create color palette
        primary = color_scheme.get('primary', '#000000')
        secondary = color_scheme.get('secondary', '#666666')
        accent = color_scheme.get('accent', '#ff0000')
        background = color_scheme.get('background', '#ffffff')
        
        preview_html += f"""
            <div class="design-card">
                <div class="design-header">
                    <div class="design-name">Design {i}: {design.get('design_name', 'Untitled')}</div>
                    <div class="design-philosophy">{design.get('design_philosophy', 'No philosophy provided')}</div>
                </div>
                
                <div class="color-palette">
                    <div class="color-swatch" style="background-color: {primary}">Primary</div>
                    <div class="color-swatch" style="background-color: {secondary}">Secondary</div>
                    <div class="color-swatch" style="background-color: {accent}">Accent</div>
                    <div class="color-swatch" style="background-color: {background}; color: #333;">Background</div>
                </div>
                
                <div class="design-details">
                    <div class="detail-section">
                        <div class="detail-title">Visual Direction</div>
                        <div class="detail-content">{design.get('visual_direction', 'Not specified')}</div>
                    </div>
                    
                    <div class="detail-section">
                        <div class="detail-title">Target Emotion</div>
                        <div class="detail-content">{design.get('target_emotion', 'Not specified')}</div>
                    </div>
                    
                    <div class="detail-section">
                        <div class="detail-title">Typography</div>
                        <div class="detail-content">
                            Headings: {typography.get('heading_font', 'Not specified')}<br>
                            Body: {typography.get('body_font', 'Not specified')}
                        </div>
                    </div>
                    
                    <div class="detail-section">
                        <div class="detail-title">Key Features</div>
                        <div class="detail-content">
                            Header: {components.get('header', {}).get('style', 'Not specified')}<br>
                            Buttons: {components.get('buttons', {}).get('primary_style', 'Not specified')}<br>
                            Cards: {components.get('cards', {}).get('style', 'Not specified')}
                        </div>
                    </div>
                </div>
            </div>
        """

    # Add design brief section
    preview_html += f"""
        </div>
        
        <div class="brief-section">
            <h2>Design Strategy Brief</h2>
            <div class="detail-section">
                <div class="detail-title">Overall Strategy</div>
                <div class="detail-content">{design_brief.get('overall_strategy', 'Not provided')}</div>
            </div>
            <div class="detail-section">
                <div class="detail-title">Target Audience Analysis</div>
                <div class="detail-content">{design_brief.get('target_audience_analysis', 'Not provided')}</div>
            </div>
            <div class="detail-section">
                <div class="detail-title">Competitive Differentiation</div>
                <div class="detail-content">{design_brief.get('competitive_differentiation', 'Not provided')}</div>
            </div>
            <div class="detail-section">
                <div class="detail-title">Recommended Design</div>
                <div class="detail-content">{design_brief.get('recommended_design', 'Not provided')}</div>
            </div>
        </div>
    </div>
</body>
</html>
"""

    # Save the preview
    preview_path = output_dir / "design_preview.html"
    with open(preview_path, 'w', encoding='utf-8') as f:
        f.write(preview_html)
    
    print(f"   📋 Design preview saved to: {preview_path.name}")

def main():
    """Main function to generate design variations."""
    load_dotenv()
    
    model_options_text = ', '.join([f"{i}='{config['name']}'" for i, config in enumerate(MODELS_CONFIG)])
    
    parser = argparse.ArgumentParser(description="Generates 3 distinct design variations from extracted website data.")
    parser.add_argument("site_dir", type=str, help="Path to website data directory (output from structure extractor).")
    parser.add_argument("--model-index", type=int, default=DEFAULT_MODEL_INDEX, 
                       choices=range(len(MODELS_CONFIG)),
                       help=f"Model to use for design generation ({model_options_text})")
    
    args = parser.parse_args()
    
    site_data_path = Path(args.site_dir)
    if not site_data_path.is_dir():
        print(f"❌ Error: Directory not found at '{site_data_path}'")
        return
    
    print(f"\n--- Design Generation for {site_data_path.name} ---")
    
    try:
        # Load site brief from previous script
        print("📖 Loading site brief...")
        site_brief = load_site_brief(site_data_path)
        
        # Validate we have the required data
        if not site_brief.get('brand_profile'):
            print("❌ Error: No brand profile found in site brief")
            return
        
        if not site_brief.get('site_pages'):
            print("❌ Error: No site pages found in site brief")
            return
        
        print(f"✅ Loaded site brief with {len(site_brief.get('site_pages', []))} pages")
        
        # Generate designs
        print("🎨 Starting design generation process...")
        print("   📖 Loaded brand profile, navigation, and content from previous analysis")
        print("   🎯 Targeting 3 distinct design approaches for different audiences")
        
        designs_data, usage_data = generate_designs(site_brief, args.model_index)
        
        print("🎉 Design generation complete!")
        
        # Only save designs if we have valid data
        if designs_data and designs_data.get('designs') and len(designs_data.get('designs', [])) > 0:
            # Save designs
            print("💾 Saving design specifications...")
            designs_path = site_data_path / "designs.json"
            try:
                with open(designs_path, 'w', encoding='utf-8') as f:
                    json.dump(designs_data, f, indent=4)
                print(f"✅ Designs saved to: {designs_path}")
                
                # Create preview
                print("🖼️  Creating visual preview...")
                create_design_preview(designs_data, site_data_path)
                print("✅ Preview HTML created for design review")
            except Exception as e:
                print(f"❌ Error saving designs: {e}")
                return
        else:
            print("❌ No valid designs generated - not saving designs.json")
            return
        
        # Summary
        designs_count = len(designs_data.get('designs', []))
        design_names = [d.get('design_name', f'Design {i+1}') for i, d in enumerate(designs_data.get('designs', []))]
        
        print(f"\n🎉 Design generation complete!")
        print(f"   - Generated {designs_count} design variations:")
        for i, name in enumerate(design_names, 1):
            print(f"     {i}. {name}")
        print(f"   - Complete design specifications saved as JSON")
        print(f"   - Visual preview created for stakeholder review")
        print(f"   - Ready for code generation (step 4)")
        
        # Print usage data for orchestrator
        print(json.dumps(usage_data))
        
    except FileNotFoundError as e:
        print(f"❌ File not found: {e}")
    except Exception as e:
        print(f"❌ Design generation failed: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    main()