#!/usr/bin/env python3
"""
Create ASCII fox animation frames for Ginger marketing video.
Converts ASCII art to PNG images with color.
"""

import os
from PIL import Image, ImageDraw, ImageFont
import textwrap

# ASCII fox frames
FRAMES = [
    # Frame 1: Eyes Closed
    """        /\\_/\\
   ____/ o o \\
 /~____  =ø= /
(______)__m_m)""",
    
    # Frame 2: Eyes Open
    """        /\\_/\\
   ____/ O O \\
 /~____  =ø= /
(______)__m_m)""",
    
    # Frame 3: Ears Up
    """        /\\_/\\
   ____/ o o \\
 /~____  =ø= /
(______)__m_m)
   |     |""",
    
    # Frame 4: Tail Wag
    """        /\\_/\\
   ____/ o o \\
 /~____  =ø= /
(______)__m_m)
        \\__/""",
    
    # Frame 5: Happy
    """        /\\_/\\
   ____/ ^ ^ \\
 /~____  =ø= /
(______)__m_m)  :)""",
    
    # Frame 6: Alert
    """        /\\_/\\
   ____/ ! ! \\
 /~____  =ø= /
(______)__m_m)
   |  |  |"""
]

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

def create_frame(frame_text, frame_num, output_dir="animation_frames"):
    """Create an image from ASCII text."""
    # Create output directory
    os.makedirs(output_dir, exist_ok=True)
    
    # Image dimensions
    width = 800
    height = 600
    
    # Create image with dark background
    img = Image.new('RGB', (width, height), color=COLORS['background'])
    draw = ImageDraw.Draw(img)
    
    try:
        # Try to use a monospace font
        font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf", 24)
    except:
        # Fallback to default font
        font = ImageFont.load_default()
    
    # Split text into lines
    lines = frame_text.split('\n')
    
    # Calculate starting position (centered)
    line_height = 30
    total_height = len(lines) * line_height
    start_y = (height - total_height) // 2
    
    # Draw each line
    for i, line in enumerate(lines):
        # Calculate text width for centering
        text_width = draw.textlength(line, font=font)
        x = (width - text_width) // 2
        y = start_y + (i * line_height)
        
        # Color coding based on characters
        colored_text = ""
        for char in line:
            if char in 'oO^!':  # Eyes and expressions
                draw.text((x, y), char, fill=COLORS['blue'], font=font)
            elif char in '/\\_~=()|':  # Fox body
                draw.text((x, y), char, fill=COLORS['fox_orange'], font=font)
            elif char in 'mø':  # Nose and details
                draw.text((x, y), char, fill=COLORS['green'], font=font)
            elif char in ':)' :  # Smiley
                draw.text((x, y), char, fill=COLORS['green'], font=font)
            else:
                draw.text((x, y), char, fill=COLORS['white'], font=font)
            x += draw.textlength(char, font=font)
    
    # Add frame number and title
    title = f"Ginger Frame {frame_num}"
    title_width = draw.textlength(title, font=font)
    draw.text(((width - title_width) // 2, 50), title, fill=COLORS['white'], font=font)
    
    # Add subtitle
    subtitle = "Your AI Assistant 🦊"
    subtitle_width = draw.textlength(subtitle, font=font)
    draw.text(((width - subtitle_width) // 2, height - 100), subtitle, fill=COLORS['fox_orange'], font=font)
    
    # Save image
    output_path = os.path.join(output_dir, f"frame_{frame_num:02d}.png")
    img.save(output_path)
    print(f"Created: {output_path}")
    
    return output_path

def create_animation_gif(frame_files, output_path="ginger_animation.gif"):
    """Create animated GIF from frame images."""
    images = []
    
    for frame_file in frame_files:
        img = Image.open(frame_file)
        images.append(img)
    
    # Save as animated GIF
    images[0].save(
        output_path,
        save_all=True,
        append_images=images[1:],
        duration=500,  # 500ms per frame
        loop=0,  # Infinite loop
        optimize=True
    )
    
    print(f"Created animated GIF: {output_path}")
    return output_path

def main():
    """Main function to create all animation assets."""
    print("Creating Ginger ASCII animation frames...")
    
    # Create individual frames
    frame_files = []
    for i, frame_text in enumerate(FRAMES, 1):
        frame_file = create_frame(frame_text, i)
        frame_files.append(frame_file)
    
    # Create animated GIF
    gif_file = create_animation_gif(frame_files)
    
    # Create a simple HTML preview
    html_content = """<!DOCTYPE html>
<html>
<head>
    <title>Ginger 🦊 ASCII Animation</title>
    <style>
        body {
            background-color: #191919;
            color: white;
            font-family: monospace;
            text-align: center;
            padding: 20px;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
        }
        h1 {
            color: #FF8C00;
        }
        .animation {
            margin: 20px 0;
            border: 2px solid #FF8C00;
            border-radius: 10px;
            padding: 20px;
            background-color: #333;
        }
        .frames {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            gap: 10px;
            margin: 20px 0;
        }
        .frame {
            border: 1px solid #444;
            padding: 10px;
            background-color: #222;
        }
        .ascii {
            color: #FF8C00;
            font-size: 14px;
            line-height: 1.4;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🦊 Ginger ASCII Animation</h1>
        <p>Animation frames for marketing video introduction</p>
        
        <div class="animation">
            <h2>Animated GIF Preview</h2>
            <img src="ginger_animation.gif" alt="Ginger Animation" style="max-width: 100%;">
        </div>
        
        <div class="frames">
            <h2>Individual Frames</h2>
"""
    
    # Add frame previews
    for i, frame_text in enumerate(FRAMES, 1):
        html_content += f"""
            <div class="frame">
                <h3>Frame {i}</h3>
                <pre class="ascii">{frame_text}</pre>
                <img src="animation_frames/frame_{i:02d}.png" alt="Frame {i}" style="max-width: 200px;">
            </div>
"""
    
    html_content += """
        </div>
        
        <div style="margin-top: 30px; color: #888;">
            <p>Generated for Ginger AI Assistant marketing materials</p>
            <p>Date: February 16, 2026</p>
        </div>
    </div>
</body>
</html>"""
    
    with open("animation_preview.html", "w") as f:
        f.write(html_content)
    
    print("Created HTML preview: animation_preview.html")
    print("\n🎬 Animation assets created successfully!")
    print("Files created:")
    print(f"  - {len(frame_files)} PNG frames in 'animation_frames/'")
    print(f"  - Animated GIF: ginger_animation.gif")
    print(f"  - HTML preview: animation_preview.html")
    print("\nNext steps:")
    print("  1. Open animation_preview.html in browser")
    print("  2. Use frames in video editing software")
    print("  3. Integrate with marketing video script")

if __name__ == "__main__":
    main()