#!/usr/bin/env python3
"""
Test script to verify image export fix - each color should have its own image
"""
import json
import requests
import base64
import os
from datetime import datetime

# Test data mimicking frontend structure with color-specific image URLs
test_data = {
    "selected_products": [
        {
            "product_name": "小王国Polo Ralph Lauren 大童 LOGO马标加绒棉质拉链连帽衫32354",
            "product_code": "32354",
            "brand": "Polo Ralph Lauren",
            "image_url": "",  # Product level image (not used when SKUs have their own)
            "skus": [
                {
                    "color": "CRUISE NAVY",
                    "size": "L(14-16)",
                    "sales_attr": "",
                    "quantity": 2,
                    "avg_price": 100,
                    "image_url": "/api/v1/static/images/323547626001.jpg"  # Color-specific image
                },
                {
                    "color": "CRUISE NAVY",
                    "size": "XL(18-20)",
                    "sales_attr": "",
                    "quantity": 1,
                    "avg_price": 100,
                    "image_url": "/api/v1/static/images/323547626001.jpg"  # Same color, same image
                },
                {
                    "color": "ANDOVER HEATHER",
                    "size": "L(14-16)",
                    "sales_attr": "",
                    "quantity": 2,
                    "avg_price": 100,
                    "image_url": "/api/v1/static/images/323547625002.jpg"  # Different color, different image
                },
                {
                    "color": "NEW FOREST",
                    "size": "M(10-12)",
                    "sales_attr": "",
                    "quantity": 1,
                    "avg_price": 100,
                    "image_url": "/api/v1/static/images/323547625003.jpg"  # Another color-specific image
                }
            ]
        }
    ],
    "procurement_method": "NY"
}

def test_image_export():
    """Test the v2 image export endpoint"""
    url = "http://localhost:8000/api/v1/procurement/v2/export/images"
    
    print("Testing image export with color-specific images...")
    print(f"URL: {url}")
    print(f"Test data: {json.dumps(test_data, indent=2, ensure_ascii=False)}")
    
    try:
        response = requests.post(url, json=test_data)
        print(f"Response status: {response.status_code}")
        
        if response.status_code == 200:
            result = response.json()
            print(f"Success: {result.get('success')}")
            print(f"Message: {result.get('message')}")
            print(f"Images generated: {result.get('count')}")
            
            # Save images for inspection
            if result.get('images'):
                output_dir = f"test_output_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
                os.makedirs(output_dir, exist_ok=True)
                
                for img in result['images']:
                    filename = img['filename']
                    print(f"\n  - {filename}")
                    
                    # Extract base64 data
                    data = img['data']
                    if data.startswith('data:image'):
                        # Remove data URL prefix
                        data = data.split(',')[1]
                    
                    # Decode and save
                    img_data = base64.b64decode(data)
                    filepath = os.path.join(output_dir, filename)
                    with open(filepath, 'wb') as f:
                        f.write(img_data)
                    print(f"    Saved to: {filepath}")
                
                print(f"\nAll images saved to: {output_dir}/")
                print("\nExpected result:")
                print("  - Should have 3 images (one per color)")
                print("  - CRUISE NAVY image should show L(14-16)(2), XL(18-20)(1)")
                print("  - ANDOVER HEATHER image should show L(14-16)(2)")
                print("  - NEW FOREST image should show M(10-12)(1)")
                print("  - Each image should have its correct color-specific product photo")
        else:
            print(f"Error: {response.text}")
            
    except Exception as e:
        print(f"Request failed: {e}")

if __name__ == "__main__":
    test_image_export()