#!/usr/bin/env python3
"""Extract dominant colors from all competitor brand images and output JSON."""

import json
import os
import sys
from colorthief import ColorThief
from pathlib import Path
import colorsys

COMPETITION_DIR = "/root/.openclaw/workspace/public/etoro-competition"
OUTPUT_FILE = "/root/.openclaw/workspace/public/etoro-competition/chromatic-data.json"

# Brand display names
BRAND_NAMES = {
    "cashapp": "Cash App",
    "coinbase-live": "Coinbase",
    "ig-group-live": "IG Group",
    "interactive-brokers-live": "Interactive Brokers",
    "monzo": "Monzo",
    "plus500-live": "Plus500",
    "revolut-live": "Revolut",
    "robinhood-live": "Robinhood",
    "trade-republic-live": "Trade Republic",
    "trading212-live": "Trading 212",
    "venmo-live": "Venmo",
    "charles-schwab-live": "Charles Schwab",
    "goldman-marcus-live": "Marcus by Goldman Sachs",
    "fidelity-live": "Fidelity",
    "stripe-live": "Stripe",
    "monzo-live": "Monzo",
}

# Known brand primary colors (fallback)
BRAND_PRIMARY = {
    "Cash App": "#00D632",
    "Coinbase": "#0052FF",
    "IG Group": "#E4003A",
    "Interactive Brokers": "#D81B3C",
    "Monzo": "#FF5A6E",
    "Plus500": "#0289D1",
    "Revolut": "#0066FF",
    "Robinhood": "#00C805",
    "Trade Republic": "#1A1A2E",
    "Trading 212": "#0D47A1",
    "Venmo": "#008CFF",
    "Charles Schwab": "#00A0DF",
    "Marcus by Goldman Sachs": "#1A73E8",
    "Fidelity": "#4AA74C",
    "Stripe": "#635BFF",
}

def rgb_to_hsl(r, g, b):
    """Convert RGB (0-255) to HSL (0-360, 0-100, 0-100)."""
    h, l, s = colorsys.rgb_to_hls(r/255, g/255, b/255)
    return round(h * 360), round(s * 100), round(l * 100)

def rgb_to_hex(r, g, b):
    return f"#{r:02x}{g:02x}{b:02x}"

def extract_brand_colors(brand_dir, max_images=30):
    """Extract dominant colors from all images in a brand directory."""
    images = []
    all_colors = []
    
    exts = {'.jpg', '.jpeg', '.png', '.webp'}
    image_files = sorted([
        f for f in Path(brand_dir).rglob('*') 
        if f.suffix.lower() in exts and f.stat().st_size > 5000  # Skip tiny files
    ])[:max_images]
    
    for img_path in image_files:
        try:
            ct = ColorThief(str(img_path))
            dominant = ct.get_color(quality=5)
            palette = ct.get_palette(color_count=5, quality=5)
            
            h, s, l = rgb_to_hsl(*dominant)
            hex_color = rgb_to_hex(*dominant)
            
            image_data = {
                "file": img_path.name,
                "path": str(img_path.relative_to(COMPETITION_DIR)),
                "dominant": {
                    "rgb": list(dominant),
                    "hex": hex_color,
                    "hsl": [h, s, l]
                },
                "palette": [
                    {
                        "rgb": list(c),
                        "hex": rgb_to_hex(*c),
                        "hsl": list(rgb_to_hsl(*c))
                    }
                    for c in palette
                ]
            }
            images.append(image_data)
            all_colors.append({"hex": hex_color, "hsl": [h, s, l], "rgb": list(dominant)})
            
        except Exception as e:
            print(f"  SKIP {img_path.name}: {e}", file=sys.stderr)
    
    # Calculate brand average color
    if all_colors:
        avg_h = sum(c["hsl"][0] for c in all_colors) / len(all_colors)
        avg_s = sum(c["hsl"][1] for c in all_colors) / len(all_colors)
        avg_l = sum(c["hsl"][2] for c in all_colors) / len(all_colors)
    else:
        avg_h, avg_s, avg_l = 0, 0, 50
    
    return images, {
        "avgHue": round(avg_h),
        "avgSaturation": round(avg_s),
        "avgLightness": round(avg_l)
    }

def main():
    brands = {}
    
    for entry in sorted(os.listdir(COMPETITION_DIR)):
        brand_dir = os.path.join(COMPETITION_DIR, entry)
        if not os.path.isdir(brand_dir):
            continue
        
        display_name = BRAND_NAMES.get(entry)
        if not display_name:
            continue
            
        print(f"Processing {display_name} ({entry})...", file=sys.stderr)
        
        images, avg_color = extract_brand_colors(brand_dir)
        
        if not images:
            print(f"  No images found, skipping", file=sys.stderr)
            continue
        
        primary = BRAND_PRIMARY.get(display_name, images[0]["dominant"]["hex"] if images else "#888888")
        
        brands[entry] = {
            "name": display_name,
            "slug": entry,
            "primaryColor": primary,
            "avgColor": avg_color,
            "imageCount": len(images),
            "images": images
        }
        
        print(f"  → {len(images)} images, avg hue: {avg_color['avgHue']}°", file=sys.stderr)
    
    output = {
        "generated": "2026-03-18",
        "brandCount": len(brands),
        "totalImages": sum(b["imageCount"] for b in brands.values()),
        "brands": brands
    }
    
    with open(OUTPUT_FILE, 'w') as f:
        json.dump(output, f, indent=2)
    
    print(f"\nDone: {len(brands)} brands, {output['totalImages']} images → {OUTPUT_FILE}", file=sys.stderr)

if __name__ == "__main__":
    main()
