#!/usr/bin/env python3
"""
Test the new image update flow with sync confirmation
"""
import requests
import json

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

def test_image_update_flow():
    """Test the complete image update and sync flow"""
    
    # Step 1: Get a product to test with (Alexander Wang)
    print("Step 1: Finding Alexander Wang product...")
    response = requests.get(
        f"{API_BASE}/products-master/products",
        params={
            "brand": "Alexander Wang",
            "page_size": 1
        }
    )
    
    if response.status_code != 200 or not response.json()['data']['items']:
        print("No Alexander Wang products found")
        return
    
    product = response.json()['data']['items'][0]
    product_id = product['id']
    print(f"Found product: {product['线上宝贝名称']} (ID: {product_id})")
    
    # Step 2: Update the image (without auto-sync)
    print("\nStep 2: Updating product image...")
    test_image_url = "https://img.alicdn.com/imgextra/i3/2734547339/O1CN0133Imfw245JoUwBj0f_!!2734547339.jpg"
    
    response = requests.put(
        f"{API_BASE}/products-master/products/{product_id}/image",
        json={"image_url": test_image_url}
    )
    
    if response.status_code == 200:
        result = response.json()
        print(f"Image update result: {result['message']}")
        print(f"  - Success: {result['success']}")
        print(f"  - Pending sync count: {result['data'].get('pending_sync_count', 0)}")
        print(f"  - Needs sync: {result['data'].get('needs_sync', False)}")
        
        # Step 3: If there are pending syncs, manually trigger sync
        if result['data'].get('needs_sync'):
            print("\nStep 3: Manually triggering sync to procurement orders...")
            sync_response = requests.post(
                f"{API_BASE}/products-master/products/{product_id}/sync-image"
            )
            
            if sync_response.status_code == 200:
                sync_result = sync_response.json()
                print(f"Sync result: {sync_result['message']}")
                print(f"  - Synced count: {sync_result['data']['synced_count']}")
            else:
                print(f"Sync failed: {sync_response.text}")
        else:
            print("\nNo procurement orders need syncing")
    else:
        print(f"Image update failed: {response.text}")

if __name__ == "__main__":
    print("Testing Image Update with Sync Confirmation")
    print("=" * 50)
    test_image_update_flow()
    print("\n✅ Test complete. Check the frontend to see the confirmation dialog.")