#!/usr/bin/env python3
"""
extract-colors.py — Extract dominant brand colors from logo images.
Usage:     python3 extract-colors.py <image_path> [num_colors]
Examples:  python3 extract-colors.py logo.png
           python3 extract-colors.py logo.png banner.png 8

Dependencies: Pillow, numpy (both available on VPS)
"""
import sys
from PIL import Image
import numpy as np
from collections import Counter

def extract_brand_colors(image_path, num_colors=8, resize=150):
    """
    Extract dominant brand colors from a logo image.
    - Resizes image for performance
    - Removes transparent pixels
    - Skips near-white background pixels
    - Quantizes to reduce noise (rounds RGB to nearest 15)
    Returns list of (hex_color, percentage) tuples.
    """
    img = Image.open(image_path)
    img = img.convert('RGBA')
    img_small = img.resize((resize, resize), Image.LANCZOS)
    pixels = np.array(img_small).reshape(-1, 4)

    filtered = []
    for p in pixels:
        r, g, b, a = int(p[0]), int(p[1]), int(p[2]), int(p[3])
        if a < 50:  # skip transparent
            continue
        if r > 240 and g > 240 and b > 240:  # skip white background
            continue
        # Quantize to reduce noise
        qr, qg, qb = (r // 15) * 15, (g // 15) * 15, (b // 15) * 15
        filtered.append(f"#{qr:02x}{qg:02x}{qb:02x}")

    if not filtered:
        print(f"  [No non-white, non-transparent pixels found]")
        return

    total = len(filtered)
    counts = Counter(filtered)
    print(f"\n[{image_path}]")
    for hex_color, count in counts.most_common(num_colors):
        print(f"  {hex_color.upper()}  {count/total*100:.1f}%")


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python3 extract-colors.py <image_path> [num_colors]")
        sys.exit(1)

    num = 10
    paths = sys.argv[1:]
    if paths and paths[-1].isdigit():
        num = int(paths.pop())
    for path in paths:
        try:
            extract_brand_colors(path, num_colors=num)
        except FileNotFoundError:
            print(f"[File not found: {path}]")
        except Exception as e:
            print(f"[Error reading {path}: {e}]")
