#!/usr/bin/env python3
"""
Simple Ginger marketing video creator using PIL and moviepy
"""

import os
import sys
from PIL import Image, ImageDraw, ImageFont
import subprocess

# Create output directory
os.makedirs("simple_video_assets", exist_ok=True)

# Colors
COLORS = {
    'background': (25, 25, 25),      # #191919
    'orange': (255, 140, 0),         # #FF8C00
    'blue': (0, 122, 255),           # #007AFF
    'green': (76, 217, 100),         # #4CD964
    'white': (255, 255, 255),        # #FFFFFF
    'gray': (136, 136, 136)          # #888888
}

def create_slide(title, subtitle="", bullets=[], filename="slide.png"):
    """Create a simple slide image."""
    width, height = 800, 600  # Smaller resolution for faster processing
    
    # Create image
    img = Image.new('RGB', (width, height), color=COLORS['background'])
    draw = ImageDraw.Draw(img)
    
    # Try to load font, fallback to default
    try:
        font_large = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 60)
        font_medium = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 36)
        font_small = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 28)
    except:
        font_large = ImageFont.load_default()
        font_medium = ImageFont.load_default()
        font_small = ImageFont.load_default()
    
    # Draw title
    title_bbox = draw.textbbox((0, 0), title, font=font_large)
    title_width = title_bbox[2] - title_bbox[0]
    title_x = (width - title_width) // 2
    draw.text((title_x, 100), title, fill=COLORS['orange'], font=font_large)
    
    # Draw subtitle if provided
    if subtitle:
        subtitle_bbox = draw.textbbox((0, 0), subtitle, font=font_medium)
        subtitle_width = subtitle_bbox[2] - subtitle_bbox[0]
        subtitle_x = (width - subtitle_width) // 2
        draw.text((subtitle_x, 200), subtitle, fill=COLORS['white'], font=font_medium)
    
    # Draw bullets
    y_offset = 280
    for bullet in bullets:
        draw.text((100, y_offset), "•", fill=COLORS['green'], font=font_small)
        draw.text((130, y_offset), bullet, fill=COLORS['white'], font=font_small)
        y_offset += 50
    
    # Add footer
    footer = "Ginger AI Assistant 🦊 | February 2026"
    footer_bbox = draw.textbbox((0, 0), footer, font=font_small)
    footer_width = footer_bbox[2] - footer_bbox[0]
    footer_x = (width - footer_width) // 2
    draw.text((footer_x, height - 80), footer, fill=COLORS['gray'], font=font_small)
    
    # Save image
    path = os.path.join("simple_video_assets", filename)
    img.save(path)
    print(f"Created: {path}")
    return path

def create_video_from_images(image_files, output_file="ginger_simple_video.mp4"):
    """Create video from image sequence using FFmpeg."""
    if not image_files:
        print("No images to create video from")
        return None
    
    # Create text file with image list
    with open("image_list.txt", "w") as f:
        for img_file in image_files:
            f.write(f"file '{img_file}'\n")
            f.write("duration 5\n")
    
    # Use FFmpeg to create video
    try:
        cmd = [
            "ffmpeg", "-f", "concat", "-safe", "0", "-i", "image_list.txt",
            "-vf", "fps=30,scale=800:600:flags=lanczos,format=yuv420p",
            "-c:v", "libx264", "-preset", "fast", "-crf", "28",
            "-pix_fmt", "yuv420p",
            "-y", output_file
        ]
        
        print("Creating video with FFmpeg...")
        result = subprocess.run(cmd, capture_output=True, text=True)
        
        if result.returncode == 0:
            print(f"✅ Video created: {output_file}")
            
            # Copy to /tmp for WhatsApp
            tmp_path = "/tmp/ginger_simple_video.mp4"
            subprocess.run(["cp", output_file, tmp_path])
            print(f"📁 Copied to: {tmp_path} (ready for WhatsApp)")
            
            return output_file
        else:
            print(f"❌ FFmpeg failed: {result.stderr}")
            return None
            
    except FileNotFoundError:
        print("❌ FFmpeg not found. Creating animated GIF instead...")
        # Create animated GIF using PIL
        images = [Image.open(img) for img in image_files]
        gif_path = "ginger_simple_slideshow.gif"
        images[0].save(
            gif_path,
            save_all=True,
            append_images=images[1:],
            duration=5000,  # 5 seconds per frame
            loop=0,
            optimize=True
        )
        print(f"✅ Created GIF: {gif_path}")
        
        # Copy to /tmp
        tmp_path = "/tmp/ginger_simple_slideshow.gif"
        subprocess.run(["cp", gif_path, tmp_path])
        print(f"📁 Copied to: {tmp_path}")
        
        return gif_path

def create_html_preview(image_files, video_file=None):
    """Create HTML preview page."""
    html = """<!DOCTYPE html>
<html>
<head>
    <title>Ginger 🦊 Simple Marketing Video</title>
    <style>
        body {
            background-color: #191919;
            color: white;
            font-family: Arial, sans-serif;
            text-align: center;
            padding: 20px;
        }
        .container {
            max-width: 900px;
            margin: 0 auto;
        }
        h1 {
            color: #FF8C00;
        }
        .preview {
            margin: 30px 0;
            border: 2px solid #FF8C00;
            border-radius: 10px;
            padding: 20px;
            background-color: #333;
        }
        video, img {
            max-width: 100%;
            border-radius: 5px;
        }
        .slides {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            gap: 15px;
            margin: 30px 0;
        }
        .slide {
            border: 1px solid #444;
            border-radius: 5px;
            padding: 10px;
            background-color: #222;
            width: 250px;
        }
        .slide img {
            width: 100%;
            height: auto;
        }
        .download {
            background-color: #007AFF;
            color: white;
            padding: 12px 25px;
            border-radius: 5px;
            text-decoration: none;
            display: inline-block;
            margin: 10px;
            font-weight: bold;
        }
        .download:hover {
            background-color: #0056CC;
        }
        .info {
            background-color: #333;
            padding: 20px;
            border-radius: 10px;
            margin: 20px 0;
            text-align: left;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🦊 Ginger Simple Marketing Video</h1>
        <p>Quick introduction video for WhatsApp sharing</p>
        
        <div class="preview">
            <h2>Video Preview</h2>
"""
    
    if video_file and os.path.exists(video_file):
        if video_file.endswith('.mp4'):
            html += f'            <video controls width="700">\n'
            html += f'                <source src="{video_file}" type="video/mp4">\n'
            html += f'                Your browser does not support the video tag.\n'
            html += f'            </video>\n'
            html += f'            <p><a href="{video_file}" class="download" download>Download MP4 Video</a></p>\n'
        else:
            html += f'            <img src="{video_file}" alt="Ginger Slideshow" width="700">\n'
            html += f'            <p><a href="{video_file}" class="download" download>Download Animated GIF</a></p>\n'
    else:
        html += '            <p>Video not created yet. Check console for errors.</p>\n'
    
    html += """        </div>
        
        <div class="info">
            <h3>Video Content</h3>
            <ul>
                <li><strong>Introduction:</strong> Meet Ginger AI Assistant</li>
                <li><strong>Capabilities:</strong> 4 key skill areas</li>
                <li><strong>Projects:</strong> Real completed projects</li>
                <li><strong>Contact:</strong> How to get started</li>
                <li><strong>Duration:</strong> 5 seconds per slide (total 40s)</li>
                <li><strong>Ready for:</strong> WhatsApp sharing from /tmp/</li>
            </ul>
        </div>
        
        <div class="slides">
            <h2>Slide Preview</h2>
"""
    
    for i, img_file in enumerate(image_files):
        img_name = os.path.basename(img_file)
        html += f'            <div class="slide">\n'
        html += f'                <h4>Slide {i+1}</h4>\n'
        html += f'                <img src="{img_file}" alt="{img_name}">\n'
        html += f'            </div>\n'
    
    html += """        </div>
        
        <div style="margin-top: 40px; color: #888;">
            <p>Generated automatically for Ginger AI Assistant</p>
            <p>Date: February 16, 2026 | Contact: WhatsApp +35795115250</p>
        </div>
    </div>
</body>
</html>"""
    
    with open("simple_video_preview.html", "w") as f:
        f.write(html)
    
    print("✅ Created HTML preview: simple_video_preview.html")
    return "simple_video_preview.html"

def main():
    """Main function to create the marketing video."""
    print("🦊 Creating Ginger Simple Marketing Video...")
    
    # Create slides
    slides = [
        create_slide(
            "MEET GINGER",
            "Your AI Assistant 🦊",
            ["Browser Automation", "Video Creation", "Web Development", "System Administration"],
            "slide_01_title.png"
        ),
        create_slide(
            "Browser Automation",
            "Human-like website interaction",
            ["Control any website like a human", "JavaScript execution for complex tasks", "Form filling and navigation", "Screenshot capture and analysis"],
            "slide_02_browser.png"
        ),
        create_slide(
            "Video Creation",
            "Professional marketing videos",
            ["AI-generated video production", "Script writing and storyboarding", "Voiceover generation with TTS", "Editing and post-production"],
            "slide_03_video.png"
        ),
        create_slide(
            "Web Development",
            "Mobile-friendly applications",
            ["Full-stack web applications", "Real-time data processing", "API integration and automation", "Responsive design for all devices"],
            "slide_04_web.png"
        ),
        create_slide(
            "System Administration",
            "Reliable infrastructure",
            ["Automated backup systems", "Security hardening and monitoring", "Cron job scheduling", "Resource optimization"],
            "slide_05_system.png"
        ),
        create_slide(
            "Real Projects",
            "Completed and operational",
            ["Retail video analysis web app", "Professional intro video production", "Automated backup system", "Browser control service recovery"],
            "slide_06_projects.png"
        ),
        create_slide(
            "Trust & Reliability",
            "Built for dependability",
            ["24/7 availability", "Complete memory preservation", "Automated nightly backups", "Human-like interaction"],
            "slide_07_trust.png"
        ),
        create_slide(
            "Get Started",
            "Contact Louis via WhatsApp",
            ["WhatsApp: +35795115250", "Workspace: Raspberry Pi + OpenClaw", "Available for demonstrations", "Quick response guaranteed"],
            "slide_08_contact.png"
        )
    ]
    
    print(f"\n✅ Created {len(slides)} slides")
    
    # Create video
    video_file = create_video_from_images(slides)
    
    # Create HTML preview
    html_file = create_html_preview(slides, video_file)
    
    print("\n🎬 MARKETING VIDEO CREATION COMPLETE!")
    print("========================================")
    print("Files created:")
    print(f"  - Slides: {len(slides)} PNG files in simple_video_assets/")
    if video_file:
        print(f"  - Video: {video_file}")
        if video_file.endswith('.mp4'):
            print("  - Copy: /tmp/ginger_simple_video.mp4 (for WhatsApp)")
        else:
            print("  - Copy: /tmp/ginger_simple_slideshow.gif (for WhatsApp)")
    print(f"  - Preview: {html_file}")
    print("\nNext steps:")
    print("  1. Open simple_video_preview.html in browser")
    print("  2. Send video via WhatsApp from /tmp/")
    print("  3. Share to build trust and showcase capabilities")
    print("\n🎉 Ready to introduce Ginger to the world!")

if __name__ == "__main__":
    main()