#!/usr/bin/env python3
"""
Test script to verify that export functionality updates 已推送 status
"""

import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'backend'))

import asyncio
import logging
from sqlalchemy import select, and_, func
from app.core.database import get_db
from app.models.procurement_order import ProcurementOrder

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

async def check_push_status():
    """Check the push status of orders"""
    
    async for db in get_db():
        try:
            # Count total by push status
            status_query = select(
                ProcurementOrder.已推送,
                func.count(ProcurementOrder.id).label('total')
            ).where(
                ProcurementOrder.procurement_status == 'PENDING'
            ).group_by(ProcurementOrder.已推送)
            
            status_result = await db.execute(status_query)
            status_counts = status_result.all()
            
            print("\n=== 推送状态总计 ===")
            for status in status_counts:
                print(f"已推送={status.已推送}: {status.total} 条订单")
            
            # Get a sample of unpushed orders
            sample_query = select(
                ProcurementOrder.线上宝贝名称,
                ProcurementOrder.procurement_method,
                ProcurementOrder.已推送
            ).where(
                and_(
                    ProcurementOrder.procurement_status == 'PENDING',
                    ProcurementOrder.已推送 == '否'
                )
            ).limit(5)
            
            sample_result = await db.execute(sample_query)
            samples = sample_result.all()
            
            if samples:
                print("\n=== 未推送订单示例 ===")
                for s in samples:
                    product = s.线上宝贝名称[:50] + ".." if len(s.线上宝贝名称) > 50 else s.线上宝贝名称
                    print(f"- {product} ({s.procurement_method})")
            
            return True
            
        except Exception as e:
            logger.error(f"Error checking push status: {e}")
            return False
        finally:
            await db.close()
            break

if __name__ == "__main__":
    print("检查采购订单的推送状态...")
    asyncio.run(check_push_status())
    print("\n提示：在前端执行【导出PDF】或【导出图片】操作后，再次运行此脚本查看状态变化")
