#!/usr/bin/env python
"""
修复被截断的图片URL
批量从raw_orders表恢复正确的图片URL到products_master表
"""
import asyncio
import logging
import json
from sqlalchemy import select, update, and_
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.database import get_db
from app.models.products_master import ProductMaster
from app.models.raw_orders import RawOrder

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


async def fix_truncated_urls(db: AsyncSession):
    """修复被截断的图片URL"""
    
    # 1. 查找所有被截断的记录
    logger.info("查找被截断的图片URL...")
    query = select(ProductMaster).where(
        ProductMaster.main_image_path.like('%~crop') |
        ProductMaster.main_image_path.like('%~_')
    )
    result = await db.execute(query)
    truncated_products = result.scalars().all()
    
    logger.info(f"找到 {len(truncated_products)} 个被截断的产品")
    
    fixed_count = 0
    failed_count = 0
    
    for product in truncated_products:
        try:
            # 2. 查找对应的原始订单，获取完整图片URL
            raw_query = select(RawOrder).where(
                RawOrder.线上宝贝名称 == product.线上宝贝名称
            ).limit(1)
            raw_result = await db.execute(raw_query)
            raw_order = raw_result.scalar_one_or_none()
            
            if not raw_order or not raw_order.图片:
                logger.warning(f"产品 {product.线上宝贝名称} 找不到原始订单或图片")
                failed_count += 1
                continue
            
            # 3. 提取完整的图片URL
            full_image_url = str(raw_order.图片).strip()
            
            # 确保是完整的URL
            if not full_image_url.startswith('http'):
                logger.warning(f"产品 {product.线上宝贝名称} 的图片URL无效: {full_image_url}")
                failed_count += 1
                continue
            
            # 4. 更新产品主表
            product.main_image_path = full_image_url
            product.original_image_urls = json.dumps([full_image_url], ensure_ascii=False)
            
            logger.info(f"修复产品: {product.线上宝贝名称}")
            logger.info(f"  原URL: {product.main_image_path[:50]}...")
            logger.info(f"  新URL: {full_image_url[:50]}...")
            
            fixed_count += 1
            
            # 每修复10个产品提交一次
            if fixed_count % 10 == 0:
                await db.commit()
                logger.info(f"已修复 {fixed_count} 个产品...")
                
        except Exception as e:
            logger.error(f"修复产品 {product.线上宝贝名称} 失败: {e}")
            failed_count += 1
            continue
    
    # 最终提交
    await db.commit()
    
    logger.info(f"修复完成！成功: {fixed_count}, 失败: {failed_count}")
    
    # 5. 验证修复结果
    verify_query = select(ProductMaster).where(
        ProductMaster.main_image_path.like('%~crop') |
        ProductMaster.main_image_path.like('%~_')
    )
    verify_result = await db.execute(verify_query)
    remaining = len(verify_result.scalars().all())
    
    logger.info(f"验证结果: 还有 {remaining} 个产品的图片URL仍然被截断")
    
    return {
        'fixed': fixed_count,
        'failed': failed_count,
        'remaining': remaining
    }


async def main():
    """主函数"""
    async for db in get_db():
        try:
            result = await fix_truncated_urls(db)
            print(f"\n修复结果:")
            print(f"  成功修复: {result['fixed']} 个产品")
            print(f"  修复失败: {result['failed']} 个产品")
            print(f"  剩余问题: {result['remaining']} 个产品")
        finally:
            await db.close()
        break


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