#!/usr/bin/env python3
"""
直接测试API返回的实际数据
"""
import sys
import asyncio
import json
sys.path.append('backend')

from app.core.database import get_db
from app.services.products_master_service import ProductsMasterService

async def test_api_directly():
    """直接测试API方法返回的数据"""
    print("直接测试ProductsMasterService.get_products_list方法...")
    print("=" * 80)
    
    try:
        async for db in get_db():
            service = ProductsMasterService()
            
            # 搜索包含"卡其色麻花拖鞋"的产品
            print("1. 搜索卡其色麻花拖鞋产品:")
            print("-" * 40)
            
            result = await service.get_products_list(
                db=db,
                product_name="卡其色麻花拖鞋",
                page=1,
                page_size=10
            )
            
            print(f"API返回结果结构:")
            print(f"  - total: {result.get('total', 'N/A')}")
            print(f"  - items数量: {len(result.get('items', []))}")
            print()
            
            items = result.get('items', [])
            if items:
                print("找到的产品:")
                for i, item in enumerate(items, 1):
                    print(f"\n{i}. 产品详情:")
                    
                    # 检查是否是字典还是对象
                    if hasattr(item, '__dict__'):
                        # 对象类型，转换为字典查看
                        item_dict = {
                            'id': getattr(item, 'id', None),
                            '线上宝贝名称': getattr(item, '线上宝贝名称', None),
                            '品牌': getattr(item, '品牌', None),
                            '货号': getattr(item, '货号', None)
                        }
                        print(f"   对象属性:")
                        for key, value in item_dict.items():
                            print(f"     {key}: '{value}'")
                            
                        # 特别检查品牌
                        brand = getattr(item, '品牌', None)
                        if brand == "Tods":
                            print(f"   ✅ API中品牌正确: '{brand}'")
                        else:
                            print(f"   ❌ API中品牌错误: '{brand}' (应该是'Tods')")
                            print(f"   品牌长度: {len(brand)} 字符")
                    else:
                        # 字典类型
                        print(f"   字典内容: {item}")
                        brand = item.get('品牌', 'N/A')
                        if brand == "Tods":
                            print(f"   ✅ API中品牌正确: '{brand}'")
                        else:
                            print(f"   ❌ API中品牌错误: '{brand}'")
            else:
                print("❌ 没有找到相关产品")
            
            # 2. 搜索具体的产品名称
            print(f"\n\n2. 搜索具体产品名称:")
            print("-" * 40)
            
            specific_result = await service.get_products_list(
                db=db,
                product_name="Tods女款卡其色麻花拖鞋 XXW70K0GU70MIDM033美国代购8.15 LA",
                page=1,
                page_size=5
            )
            
            specific_items = specific_result.get('items', [])
            if specific_items:
                for i, item in enumerate(specific_items, 1):
                    print(f"\n产品 {i}:")
                    if hasattr(item, '__dict__'):
                        brand = getattr(item, '品牌', None)
                        name = getattr(item, '线上宝贝名称', None)
                        print(f"   产品名称: {name}")
                        print(f"   品牌: '{brand}'")
                        print(f"   品牌长度: {len(brand) if brand else 0} 字符")
                        
                        if brand == "Tods":
                            print(f"   ✅ API返回的品牌正确")
                        else:
                            print(f"   ❌ API返回的品牌错误: '{brand}'")
                            # 检查是否包含产品描述
                            if "卡其色" in brand:
                                print(f"   ⚠️ 品牌包含颜色描述")
                            if "麻花拖鞋" in brand:
                                print(f"   ⚠️ 品牌包含产品类型描述")
            else:
                print("❌ 精确搜索未找到产品")
                
            # 3. 检查所有Tods品牌产品
            print(f"\n\n3. 检查所有Tods品牌产品:")
            print("-" * 40)
            
            tods_result = await service.get_products_list(
                db=db,
                brand="Tods",
                page=1,
                page_size=5
            )
            
            tods_items = tods_result.get('items', [])
            print(f"找到 {tods_result.get('total', 0)} 个Tods品牌产品")
            
            if tods_items:
                print(f"前5个Tods产品样本:")
                for i, item in enumerate(tods_items, 1):
                    if hasattr(item, '__dict__'):
                        brand = getattr(item, '品牌', None)
                        name = getattr(item, '线上宝贝名称', None)
                        print(f"\n{i}. {name[:50]}...")
                        print(f"   品牌: '{brand}' (长度: {len(brand) if brand else 0})")
                        
                        if brand != "Tods":
                            print(f"   ❌ 发现品牌不一致!")
            
            break
            
    except Exception as e:
        print(f"Error: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    asyncio.run(test_api_directly())