#!/usr/bin/env python3
"""
Generate simple placeholder icons for platform plugins using Pillow.

This script creates gradient icons with initials/symbols for each plugin.
No API key required - uses pure Python image generation.

Usage:
    python generate_placeholder_icons.py
"""

from pathlib import Path

try:
    from PIL import Image, ImageDraw, ImageFont
except ImportError:
    print("Error: Pillow package not installed")
    print("Install with: pip install Pillow")
    exit(1)


# Plugin definitions with colors and symbols
PLUGINS = [
    {
        'slug': 'daily-appointment-summary',
        'name': 'Daily Appointment Summary',
        'symbol': '📅',
        'initials': 'DS',
        'colors': ('#6366f1', '#8b5cf6'),  # Indigo to violet
    },
    {
        'slug': 'no-show-tracker',
        'name': 'No-Show Customer Tracker',
        'symbol': '❌',
        'initials': 'NS',
        'colors': ('#f97316', '#ef4444'),  # Orange to red
    },
    {
        'slug': 'birthday-greetings',
        'name': 'Birthday Greeting Campaign',
        'symbol': '🎂',
        'initials': 'BG',
        'colors': ('#ec4899', '#f472b6'),  # Pink shades
    },
    {
        'slug': 'monthly-revenue-report',
        'name': 'Monthly Revenue Report',
        'symbol': '📈',
        'initials': 'MR',
        'colors': ('#22c55e', '#10b981'),  # Green shades
    },
    {
        'slug': 'appointment-reminder-24hr',
        'name': 'Appointment Reminder (24hr)',
        'symbol': '🔔',
        'initials': 'AR',
        'colors': ('#0ea5e9', '#06b6d4'),  # Sky to cyan
    },
    {
        'slug': 'inactive-customer-reengagement',
        'name': 'Inactive Customer Re-engagement',
        'symbol': '🔄',
        'initials': 'IR',
        'colors': ('#f59e0b', '#fbbf24'),  # Amber shades
    },
]


def hex_to_rgb(hex_color: str) -> tuple:
    """Convert hex color to RGB tuple."""
    hex_color = hex_color.lstrip('#')
    return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))


def create_gradient(size: int, color1: str, color2: str) -> Image.Image:
    """Create a diagonal gradient image."""
    img = Image.new('RGB', (size, size))
    c1 = hex_to_rgb(color1)
    c2 = hex_to_rgb(color2)

    for y in range(size):
        for x in range(size):
            # Diagonal gradient
            t = (x + y) / (2 * size)
            r = int(c1[0] * (1 - t) + c2[0] * t)
            g = int(c1[1] * (1 - t) + c2[1] * t)
            b = int(c1[2] * (1 - t) + c2[2] * t)
            img.putpixel((x, y), (r, g, b))

    return img


def add_rounded_corners(img: Image.Image, radius: int) -> Image.Image:
    """Add rounded corners to an image."""
    # Create a mask with rounded corners
    mask = Image.new('L', img.size, 0)
    draw = ImageDraw.Draw(mask)
    draw.rounded_rectangle([(0, 0), img.size], radius=radius, fill=255)

    # Apply mask
    result = Image.new('RGBA', img.size, (0, 0, 0, 0))
    result.paste(img, mask=mask)
    return result


def generate_icon(plugin: dict, output_dir: Path, size: int = 256) -> bool:
    """Generate a placeholder icon for a plugin."""
    slug = plugin['slug']
    initials = plugin['initials']
    color1, color2 = plugin['colors']

    output_path = output_dir / f"{slug}.png"

    print(f"Generating icon for: {plugin['name']}")
    print(f"  Output: {output_path}")

    try:
        # Create gradient background
        img = create_gradient(size, color1, color2)
        draw = ImageDraw.Draw(img)

        # Try to use a nice font, fall back to default
        font_size = size // 3
        try:
            # Try common system fonts
            for font_name in ['DejaVuSans-Bold.ttf', '/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf',
                              'Arial Bold.ttf', 'Helvetica Bold.ttf']:
                try:
                    font = ImageFont.truetype(font_name, font_size)
                    break
                except OSError:
                    continue
            else:
                font = ImageFont.load_default()
        except Exception:
            font = ImageFont.load_default()

        # Draw initials centered
        bbox = draw.textbbox((0, 0), initials, font=font)
        text_width = bbox[2] - bbox[0]
        text_height = bbox[3] - bbox[1]
        x = (size - text_width) // 2
        y = (size - text_height) // 2 - bbox[1]

        # Draw text with slight shadow for depth
        shadow_offset = 2
        draw.text((x + shadow_offset, y + shadow_offset), initials, fill=(0, 0, 0, 80), font=font)
        draw.text((x, y), initials, fill='white', font=font)

        # Add rounded corners
        img = add_rounded_corners(img, radius=size // 8)

        # Save
        img.save(output_path, 'PNG')
        print(f"  ✓ Saved to {output_path}")
        return True

    except Exception as e:
        print(f"  ✗ Error: {e}")
        return False


def main():
    # Setup output directory
    script_dir = Path(__file__).parent
    project_root = script_dir.parent
    output_dir = project_root / "static" / "plugin-logos"
    output_dir.mkdir(parents=True, exist_ok=True)

    print(f"Output directory: {output_dir}")
    print(f"Generating {len(PLUGINS)} placeholder icons...\n")

    # Generate icons
    success_count = 0
    for plugin in PLUGINS:
        if generate_icon(plugin, output_dir):
            success_count += 1
        print()

    print("=" * 50)
    print(f"Generated {success_count}/{len(PLUGINS)} icons successfully")
    print(f"Icons saved to: {output_dir}")

    if success_count > 0:
        print("\nNext steps:")
        print("1. Review the generated placeholder icons")
        print("2. Update plugin logo_url paths in seed_platform_plugins.py")
        print("3. Optionally replace with AI-generated icons later using generate_plugin_icons.py")


if __name__ == "__main__":
    main()
