#!/usr/bin/env python3
"""
Test script to reproduce and fix the Polo Ralph Lauren export bug
where only one color gets its push status updated
"""
import requests
import json

API_BASE = "http://localhost:8000/api/v1"

def test_polo_export_bug():
    print("=" * 80)
    print("TESTING POLO RALPH LAUREN MULTI-COLOR EXPORT BUG")
    print("=" * 80)
    
    # Step 1: Get the Polo product with all colors
    print("\n1. Fetching Polo Ralph Lauren product with all colors...")
    response = requests.get(
        f"{API_BASE}/procurement/list",
        params={
            "procurement_method": "NY",
            "product_name": "Polo Ralph Lauren 大童 LOGO马标加绒棉质拉链连帽衫32354",
            "page_size": 20
        }
    )
    
    if response.status_code != 200:
        print(f"Failed to get products: {response.text}")
        return
    
    products = response.json().get('products', [])
    
    # Group by color to see all variants
    color_groups = {}
    for p in products:
        color = p.get('color', 'Unknown')
        if color not in color_groups:
            color_groups[color] = []
        color_groups[color].append(p)
    
    print(f"Found {len(color_groups)} different colors:")
    for color, items in color_groups.items():
        total_qty = sum(item.get('pending_procurement_qty', 0) for item in items)
        print(f"  - {color}: {total_qty} pieces")
    
    # Step 2: Prepare export data with ALL colors
    print("\n2. Preparing export data with all colors...")
    export_data = {
        "selected_products": [{
            "product_name": "小王国Polo Ralph Lauren 大童 LOGO马标加绒棉质拉链连帽衫32354",
            "product_code": "32354",
            "brand": "Polo Ralph Lauren",
            "image_url": "",
            "skus": []
        }],
        "procurement_method": "NY"
    }
    
    # Add all color variants as SKUs
    for color, items in color_groups.items():
        for item in items:
            sku = {
                "color": color,  # Use the exact color format from API
                "size": item.get('size', '均码'),
                "sales_attr": item.get('sales_attr', ''),
                "quantity": item.get('pending_procurement_qty', 0),
                "avg_price": item.get('avg_price', 0),
                "image_url": item.get('main_image_path', '')
            }
            export_data["selected_products"][0]["skus"].append(sku)
    
    print(f"Prepared {len(export_data['selected_products'][0]['skus'])} SKUs for export")
    
    # Step 3: Check current push status before export
    print("\n3. Checking push status BEFORE export...")
    before_status = {}
    for color in color_groups.keys():
        # Get orders for this specific color
        orders_response = requests.get(
            f"{API_BASE}/procurement/orders",
            params={
                "procurement_method": "NY",
                "page_size": 100
            }
        )
        if orders_response.status_code == 200:
            orders = orders_response.json().get('orders', [])
            color_orders = [o for o in orders 
                          if "32354" in o.get('线上宝贝名称', '') 
                          and o.get('颜色') == color]
            pushed = sum(1 for o in color_orders if o.get('已推送') == '是')
            unpushed = sum(1 for o in color_orders if o.get('已推送') == '否')
            before_status[color] = {'pushed': pushed, 'unpushed': unpushed}
            print(f"  {color[:30]}... Pushed: {pushed}, Unpushed: {unpushed}")
    
    # Step 4: Export PDF (which should update all colors)
    print("\n4. Exporting PDF with all colors...")
    print(f"Export data being sent:")
    print(f"  Product: {export_data['selected_products'][0]['product_name']}")
    print(f"  SKUs: {len(export_data['selected_products'][0]['skus'])}")
    for sku in export_data['selected_products'][0]['skus'][:5]:  # Show first 5
        print(f"    - Color: {sku['color'][:30]}... Qty: {sku['quantity']}")
    
    export_response = requests.post(
        f"{API_BASE}/procurement/v2/export/pdf",
        json=export_data
    )
    
    if export_response.status_code == 200:
        print(f"✓ PDF exported successfully, size: {len(export_response.content)} bytes")
    else:
        print(f"✗ Export failed: {export_response.text}")
        return
    
    # Step 5: Check push status AFTER export
    print("\n5. Checking push status AFTER export...")
    after_status = {}
    for color in color_groups.keys():
        orders_response = requests.get(
            f"{API_BASE}/procurement/orders",
            params={
                "procurement_method": "NY",
                "page_size": 100
            }
        )
        if orders_response.status_code == 200:
            orders = orders_response.json().get('orders', [])
            color_orders = [o for o in orders 
                          if "32354" in o.get('线上宝贝名称', '') 
                          and o.get('颜色') == color]
            pushed = sum(1 for o in color_orders if o.get('已推送') == '是')
            unpushed = sum(1 for o in color_orders if o.get('已推送') == '否')
            after_status[color] = {'pushed': pushed, 'unpushed': unpushed}
            
            # Compare before and after
            before = before_status.get(color, {})
            newly_pushed = pushed - before.get('pushed', 0)
            
            status_icon = "✓" if newly_pushed > 0 else "✗"
            print(f"  {status_icon} {color[:30]}... Pushed: {pushed} (+{newly_pushed}), Unpushed: {unpushed}")
    
    # Step 6: Analysis
    print("\n6. ANALYSIS:")
    colors_updated = sum(1 for color in color_groups.keys() 
                        if after_status.get(color, {}).get('pushed', 0) > 
                           before_status.get(color, {}).get('pushed', 0))
    
    if colors_updated == len(color_groups):
        print(f"✅ SUCCESS: All {colors_updated} colors had their push status updated!")
    else:
        print(f"❌ BUG CONFIRMED: Only {colors_updated} out of {len(color_groups)} colors were updated")
        print("\nColors that were NOT updated:")
        for color in color_groups.keys():
            before = before_status.get(color, {})
            after = after_status.get(color, {})
            if after.get('pushed', 0) == before.get('pushed', 0):
                print(f"  - {color}")
    
    print("\n" + "=" * 80)

if __name__ == "__main__":
    test_polo_export_bug()