#!/usr/bin/env python3
"""
Test script to verify the Polo Ralph Lauren multi-color export bug fix
"""
import requests
import json
import time

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

def test_polo_export_fix():
    print("=" * 80)
    print("TESTING POLO RALPH LAUREN MULTI-COLOR EXPORT BUG FIX")
    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",
            "page_size": 100
        }
    )
    
    if response.status_code != 200:
        print(f"Failed to get products: {response.text}")
        return
    
    products = response.json().get('products', [])
    
    # Filter for product code 32354
    polo_products = [p for p in products if '32354' in p.get('product_name', '')]
    
    # Group by color to see all variants
    color_groups = {}
    for p in polo_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 product 32354:")
    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 across {len(items)} SKUs")
    
    # Step 2: Check current push status BEFORE export
    print("\n2. Checking push status BEFORE export...")
    orders_response = requests.get(
        f"{API_BASE}/procurement/orders",
        params={
            "procurement_method": "NY",
            "page_size": 500
        }
    )
    
    if orders_response.status_code != 200:
        print(f"Failed to get orders: {orders_response.text}")
        return
    
    all_orders = orders_response.json().get('orders', [])
    
    # Count push status for each color
    before_status = {}
    for color in color_groups.keys():
        color_orders = [o for o in all_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] = {
            'total': len(color_orders),
            'pushed': pushed, 
            'unpushed': unpushed
        }
        print(f"  {color[:30]}... Total: {len(color_orders)}, Pushed: {pushed}, Unpushed: {unpushed}")
    
    # Step 3: Prepare export data with ALL colors
    print("\n3. 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
    total_skus = 0
    for color, items in color_groups.items():
        for item in items:
            if item.get('pending_procurement_qty', 0) > 0:
                sku = {
                    "color": color,
                    "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)
                total_skus += 1
    
    print(f"Prepared {total_skus} SKUs across {len(color_groups)} colors for export")
    
    # Step 4: Export PDF (which should update all colors)
    print("\n4. Exporting PDF with all colors...")
    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: Wait a moment for database updates
    print("\n5. Waiting for database updates...")
    time.sleep(2)
    
    # Step 6: Check push status AFTER export
    print("\n6. Checking push status AFTER export...")
    orders_response = requests.get(
        f"{API_BASE}/procurement/orders",
        params={
            "procurement_method": "NY",
            "page_size": 500
        }
    )
    
    if orders_response.status_code != 200:
        print(f"Failed to get orders: {orders_response.text}")
        return
    
    all_orders = orders_response.json().get('orders', [])
    
    # Count push status for each color after export
    after_status = {}
    colors_updated = 0
    colors_not_updated = []
    
    for color in color_groups.keys():
        color_orders = [o for o in all_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] = {
            'total': len(color_orders),
            'pushed': pushed, 
            'unpushed': unpushed
        }
        
        # Compare before and after
        before = before_status.get(color, {})
        newly_pushed = pushed - before.get('pushed', 0)
        
        if newly_pushed > 0:
            colors_updated += 1
            status_icon = "✓"
        else:
            colors_not_updated.append(color)
            status_icon = "✗"
        
        print(f"  {status_icon} {color[:30]}... Total: {len(color_orders)}, Pushed: {pushed} (+{newly_pushed}), Unpushed: {unpushed}")
    
    # Step 7: Final Analysis
    print("\n7. FINAL ANALYSIS:")
    print("=" * 80)
    
    if colors_updated == len(color_groups):
        print(f"✅ SUCCESS: All {colors_updated} colors had their push status updated!")
        print("The bug has been FIXED!")
    else:
        print(f"❌ BUG STILL EXISTS: Only {colors_updated} out of {len(color_groups)} colors were updated")
        print(f"\nColors that were NOT updated:")
        for color in colors_not_updated:
            print(f"  - {color}")
        print("\nThe fix needs further investigation.")
    
    print("=" * 80)

if __name__ == "__main__":
    test_polo_export_fix()