#!/usr/bin/env python
"""
处理单个订单并生成产品主表
专门用于处理订单 2906687247880694950
"""

import asyncio
import sys
import os
from datetime import datetime

# 添加项目路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'backend'))

from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
from sqlalchemy import select
from app.models.raw_orders import RawOrder
from app.models.products_master import ProductMaster, ProductSourceMapping
from app.services.products_master_service import ProductsMasterService

async def process_single_order(order_id: int):
    """处理单个订单"""
    
    # 创建数据库连接
    # 使用绝对路径确保找到正确的数据库文件
    import os
    db_path = os.path.join(os.path.dirname(__file__), 'ordersys.db')
    database_url = f"sqlite+aiosqlite:///{db_path}"
    engine = create_async_engine(database_url, echo=False)
    async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
    
    async with async_session() as db:
        print("\n" + "="*60)
        print(f"处理订单 ID: {order_id}")
        print("="*60 + "\n")
        
        try:
            # 1. 获取订单
            result = await db.execute(
                select(RawOrder).where(RawOrder.id == order_id)
            )
            raw_order = result.scalar_one_or_none()
            
            if not raw_order:
                print(f"❌ 订单 {order_id} 不存在")
                return
            
            print(f"✅ 找到订单:")
            print(f"   - 订单号: {raw_order.原始订单编号}")
            print(f"   - 商品名称: {raw_order.线上宝贝名称}")
            print(f"   - 销售属性: {raw_order.线上销售属性}")
            print(f"   - 单价: {raw_order.订单单价}")
            print(f"   - 数量: {raw_order.数量}")
            
            # 2. 检查是否已有映射
            result = await db.execute(
                select(ProductSourceMapping).where(
                    ProductSourceMapping.raw_order_id == order_id
                )
            )
            existing_mapping = result.scalar_one_or_none()
            
            if existing_mapping:
                print(f"\n⚠️  订单已有产品映射 (产品ID: {existing_mapping.product_id})")
                # 检查产品是否存在
                result = await db.execute(
                    select(ProductMaster).where(
                        ProductMaster.id == existing_mapping.product_id
                    )
                )
                product = result.scalar_one_or_none()
                if product:
                    print(f"✅ 产品主表记录已存在:")
                    print(f"   - 品牌: {product.品牌}")
                    print(f"   - 货号: {product.货号}")
                    print(f"   - 采购方式: {product.procurement_method}")
                    return
                else:
                    print("❌ 产品主表记录丢失，需要重新生成")
            
            # 3. 使用ProductsMasterService处理订单
            print("\n开始生成产品主表...")
            service = ProductsMasterService()
            await service.initialize_extractors(db)
            
            # 处理单个订单
            result = await service._process_single_order(db, raw_order)
            
            # 提交事务
            await db.commit()
            
            print(f"\n✅ 产品主表生成成功: {result['action']}")
            
            # 4. 验证结果
            print("\n验证生成结果...")
            
            # 查询新创建的映射
            result = await db.execute(
                select(ProductSourceMapping).where(
                    ProductSourceMapping.raw_order_id == order_id
                )
            )
            mapping = result.scalar_one_or_none()
            
            if mapping:
                # 查询产品主表
                result = await db.execute(
                    select(ProductMaster).where(
                        ProductMaster.id == mapping.product_id
                    )
                )
                product = result.scalar_one_or_none()
                
                if product:
                    print(f"\n✅ 产品主表记录创建成功:")
                    print(f"   - 产品ID: {product.id}")
                    print(f"   - SKU Key: {product.sku_key}")
                    print(f"   - 品牌: {product.品牌}")
                    print(f"   - 货号: {product.货号}")
                    print(f"   - 颜色: {product.颜色}")
                    print(f"   - 尺寸: {product.尺寸}")
                    print(f"   - 采购方式: {product.procurement_method}")
                    print(f"   - 平均价格: {product.avg_price}")
                    print(f"   - 总订单数: {product.total_orders}")
                    
                    # 5. 生成采购订单（可选）
                    print("\n生成采购订单...")
                    from app.services.procurement_order_service_v2 import ProcurementOrderServiceV2
                    procurement_service = ProcurementOrderServiceV2()
                    
                    # 为这个产品生成采购订单
                    procurement_result = await procurement_service._create_or_update_procurement_order(
                        db=db,
                        raw_order=raw_order,
                        product_master=product
                    )
                    
                    if procurement_result:
                        print("✅ 采购订单已生成")
                    else:
                        print("⚠️  采购订单生成失败或已存在")
                    
                    await db.commit()
                    
                    print("\n" + "="*60)
                    print("✅ 处理完成！")
                    print("="*60)
                else:
                    print("❌ 产品主表记录创建失败")
            else:
                print("❌ 产品映射创建失败")
                
        except Exception as e:
            print(f"\n❌ 处理失败: {e}")
            import traceback
            traceback.print_exc()
            await db.rollback()

async def main():
    """主函数"""
    # 处理订单 ID 15444 (订单号: 2906687247880694950)
    await process_single_order(15444)
    
    # 也可以通过订单号查找
    # 如果需要处理其他订单，可以修改这里的ID

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