#!/usr/bin/env python3
"""
Visual Capture: Element Crops

Captures targeted visual elements from a website for brand analysis.
Uses Playwright to navigate and screenshot specific sections.

Usage:
  python element-crops.py URL BRAND_NAME [--output-dir DIR]

Example:
  python element-crops.py "https://stripe.com/atlas" stripe-atlas --output-dir ./output
"""

import argparse
import subprocess
import os
import sys

# Standard element crop configs
ELEMENT_CONFIGS = {
    'hero': {
        'description': 'Above-fold hero section',
        'viewport': '1200x800',
        'scroll': 0,
    },
    'color': {
        'description': 'Color palette in context (cards, buttons, accents)',
        'viewport': '1200x900',
        'scroll': 800,  # Often color shows in card sections below fold
    },
    'typography': {
        'description': 'Typography hierarchy (headline + body + buttons)',
        'viewport': '1200x700',
        'scroll': 0,
    },
    'components': {
        'description': 'UI components (cards, buttons, icons, labels)',
        'viewport': '1200x900',
        'scroll': 1200,
    },
    'whitespace': {
        'description': 'Visual density / breathing room',
        'viewport': '1400x900',
        'scroll': 600,
    },
}

def capture_element(url: str, brand: str, element: str, config: dict, output_dir: str) -> str:
    """Capture a single element crop."""
    filename = f"{brand}-{element}.png"
    filepath = os.path.join(output_dir, filename)
    
    width, height = config['viewport'].split('x')
    
    # Build playwright command
    cmd = [
        'playwright', 'screenshot',
        '--browser', 'chromium',
        f'--viewport-size={width},{height}',
    ]
    
    # Add scroll if needed (requires full-page then crop, or browser automation)
    # For now, use simple viewport capture
    cmd.extend([url, filepath])
    
    print(f"Capturing {element}: {config['description']}")
    result = subprocess.run(cmd, capture_output=True, text=True)
    
    if result.returncode == 0:
        print(f"  ✓ Saved: {filename}")
        return filepath
    else:
        print(f"  ✗ Failed: {result.stderr}")
        return None

def main():
    parser = argparse.ArgumentParser(description='Capture visual element crops from a website')
    parser.add_argument('url', help='Website URL to capture')
    parser.add_argument('brand', help='Brand name for file naming')
    parser.add_argument('--output-dir', '-o', default='./visual-crops', help='Output directory')
    parser.add_argument('--elements', '-e', nargs='+', 
                        choices=list(ELEMENT_CONFIGS.keys()) + ['all'],
                        default=['hero'],
                        help='Elements to capture (default: hero)')
    
    args = parser.parse_args()
    
    # Create output directory
    os.makedirs(args.output_dir, exist_ok=True)
    
    # Determine which elements to capture
    elements = list(ELEMENT_CONFIGS.keys()) if 'all' in args.elements else args.elements
    
    print(f"\nCapturing {len(elements)} element(s) from {args.url}")
    print(f"Output: {args.output_dir}\n")
    
    captured = []
    for element in elements:
        config = ELEMENT_CONFIGS[element]
        result = capture_element(args.url, args.brand, element, config, args.output_dir)
        if result:
            captured.append(result)
    
    print(f"\nDone! Captured {len(captured)}/{len(elements)} elements.")
    return 0 if len(captured) == len(elements) else 1

if __name__ == '__main__':
    sys.exit(main())
