#!/usr/bin/env python3
"""
Final test to verify the 已推送 status is working end-to-end
"""
import requests
import json

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

def test_push_status_complete():
    """Complete test of push status feature"""
    
    print("=" * 60)
    print("TESTING 已推送 (Push Status) Feature - Complete Flow")
    print("=" * 60)
    
    # Step 1: Get procurement orders
    print("\n1. Fetching procurement orders...")
    response = requests.get(
        f"{API_BASE}/procurement/list",
        params={
            "procurement_method": "NY",
            "page_size": 2
        }
    )
    
    if response.status_code == 200:
        products = response.json()['products']
        print(f"   ✓ Found {len(products)} products")
        
        print("\n2. Current push status:")
        for idx, product in enumerate(products, 1):
            push_status = product.get('已推送', 'MISSING')
            status_icon = "✓" if push_status == '是' else "✗" if push_status == '否' else "?"
            print(f"   {idx}. {product['product_name'][:40]}...")
            print(f"      [{status_icon}] 已推送: {push_status}")
            print(f"      Order IDs: {', '.join(product.get('order_ids', [])[:2])}")
        
        # Step 3: Test updating status
        if products and len(products) > 1:
            # Find a product that is not pushed yet
            unpushed_product = None
            for p in products:
                if p.get('已推送') == '否':
                    unpushed_product = p
                    break
            
            if unpushed_product:
                order_ids = unpushed_product['order_ids']
                print(f"\n3. Updating unpushed product to '是'...")
                print(f"   Product: {unpushed_product['product_name'][:40]}...")
                print(f"   Orders to update: {order_ids}")
                
                update_response = requests.post(
                    f"{API_BASE}/procurement/orders/update-push-status",
                    json={
                        "order_ids": order_ids,
                        "status": "是"
                    }
                )
                
                if update_response.status_code == 200:
                    result = update_response.json()
                    print(f"   ✓ {result['message']}")
                else:
                    print(f"   ✗ Update failed: {update_response.text}")
        
        # Step 4: Verify in database
        print("\n4. Database verification:")
        import sqlite3
        conn = sqlite3.connect('backend/ordersys.db')
        cursor = conn.cursor()
        cursor.execute("SELECT COUNT(*) FROM procurement_orders WHERE 已推送 = '是'")
        pushed_count = cursor.fetchone()[0]
        cursor.execute("SELECT COUNT(*) FROM procurement_orders WHERE 已推送 = '否'")
        unpushed_count = cursor.fetchone()[0]
        conn.close()
        
        print(f"   已推送='是': {pushed_count} orders")
        print(f"   已推送='否': {unpushed_count} orders")
        
        print("\n" + "=" * 60)
        print("✅ BACKEND TEST COMPLETE")
        print("\nFRONTEND CHECKLIST:")
        print("1. Open http://localhost:3000 in browser")
        print("2. Navigate to '待采购订单列表' (Procurement List)")
        print("3. Select procurement method 'NY'")
        print("4. Click '查询' to load data")
        print("5. You should see tags next to each product:")
        print("   - Green '已推送' tag for pushed orders")
        print("   - Yellow '未推送' tag for unpushed orders")
        print("=" * 60)
        
    else:
        print(f"✗ Failed to get procurement orders: {response.text}")

if __name__ == "__main__":
    test_push_status_complete()