#!/usr/bin/env python3
"""Analyze background color of generated images"""

from PIL import Image
import numpy as np
from typing import Tuple, Dict
from collections import Counter

def analyze_background_color(image_path: str) -> Dict:
    """
    Analyze the actual background color of an image
    by examining edges and corners

    Returns:
        Dict with background color info
    """
    img = Image.open(image_path)
    if img.mode != 'RGB':
        img = img.convert('RGB')

    data = np.array(img)
    height, width = data.shape[:2]

    # Collect edge pixels
    edge_pixels = []

    # Sample corners more densely
    corner_size = 20
    for y in range(corner_size):
        for x in range(corner_size):
            # Top-left
            edge_pixels.append(tuple(data[y, x]))
            # Top-right
            edge_pixels.append(tuple(data[y, width-1-x]))
            # Bottom-left
            edge_pixels.append(tuple(data[height-1-y, x]))
            # Bottom-right
            edge_pixels.append(tuple(data[height-1-y, width-1-x]))

    # Sample edges
    for i in range(0, width, 5):
        edge_pixels.append(tuple(data[0, i]))
        edge_pixels.append(tuple(data[height-1, i]))
    for i in range(0, height, 5):
        edge_pixels.append(tuple(data[i, 0]))
        edge_pixels.append(tuple(data[i, width-1]))

    # Find most common color
    color_counts = Counter(edge_pixels)
    most_common = color_counts.most_common(5)

    dominant_color = most_common[0][0]
    dominant_count = most_common[0][1]
    total_samples = len(edge_pixels)

    # Calculate color uniformity
    uniformity = dominant_count / total_samples

    # Check if background is uniform
    is_uniform = uniformity > 0.7  # 70% of edge pixels are same color

    # Calculate average for non-uniform backgrounds
    avg_color = tuple(np.mean(edge_pixels, axis=0).astype(int))

    # Calculate color variance
    std_dev = tuple(np.std(edge_pixels, axis=0).astype(int))

    result = {
        'dominant_color': dominant_color,
        'dominant_rgb': f"RGB{dominant_color}",
        'dominant_hex': '#{:02x}{:02x}{:02x}'.format(*dominant_color),
        'average_color': avg_color,
        'average_rgb': f"RGB{avg_color}",
        'uniformity': uniformity,
        'is_uniform': is_uniform,
        'color_std_dev': std_dev,
        'top_colors': most_common[:3]
    }

    return result

def test_chroma_key_prompt():
    """Generate test with chroma key green"""
    prompt = """
    Children's crayon drawing of a happy person.
    CRITICAL: Background MUST be EXACTLY chroma key green RGB(0,255,0).
    Use PURE GREEN #00FF00 for entire background.
    Background must be COMPLETELY UNIFORM single color.
    No gradients, no texture, no variation.
    Like a green screen for movies.
    """
    return prompt

if __name__ == "__main__":
    import sys

    if len(sys.argv) > 1:
        result = analyze_background_color(sys.argv[1])

        print("Background Analysis:")
        print(f"  Dominant Color: {result['dominant_rgb']} / {result['dominant_hex']}")
        print(f"  Average Color:  {result['average_rgb']}")
        print(f"  Uniformity:     {result['uniformity']:.1%}")
        print(f"  Is Uniform:     {result['is_uniform']}")
        print(f"  Color Std Dev:  RGB{result['color_std_dev']}")
        print(f"\nTop 3 colors:")
        for color, count in result['top_colors']:
            print(f"  RGB{color}: {count} pixels")
    else:
        print("Usage: python background_analyzer.py <image_file>")