#!/usr/bin/env python3
"""Fix main_image_path that was incorrectly set to '['"""

import asyncio
import json
from sqlalchemy import select, update
from app.core.database import AsyncSessionLocal
from app.models.products_master import ProductMaster
import logging

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

async def fix_main_image_path():
    """修复main_image_path字段"""
    async with AsyncSessionLocal() as db:
        # 查找所有main_image_path为'['的记录
        stmt = select(ProductMaster).where(ProductMaster.main_image_path == '[')
        result = await db.execute(stmt)
        products = result.scalars().all()
        
        logger.info(f"找到 {len(products)} 个需要修复的产品")
        
        fixed_count = 0
        failed_count = 0
        
        for product in products:
            try:
                # original_image_urls在数据库中是JSON字符串
                if product.original_image_urls:
                    # 根据类型处理
                    if isinstance(product.original_image_urls, str):
                        # 如果是JSON字符串，解析它
                        try:
                            urls = json.loads(product.original_image_urls)
                            if isinstance(urls, list) and len(urls) > 0:
                                first_url = urls[0]
                            else:
                                first_url = None
                        except json.JSONDecodeError:
                            # 如果不是有效的JSON，可能是普通字符串
                            first_url = product.original_image_urls
                    elif isinstance(product.original_image_urls, list):
                        # 如果已经是列表（SQLAlchemy JSON类型自动解析）
                        if len(product.original_image_urls) > 0:
                            first_url = product.original_image_urls[0]
                        else:
                            first_url = None
                    else:
                        first_url = None
                    
                    if first_url and isinstance(first_url, str) and first_url.startswith('http'):
                        # 更新main_image_path
                        update_stmt = (
                            update(ProductMaster)
                            .where(ProductMaster.id == product.id)
                            .values(main_image_path=first_url)
                        )
                        await db.execute(update_stmt)
                        fixed_count += 1
                        
                        if fixed_count <= 5:  # 只显示前5个
                            logger.info(f"修复产品 {product.id} ({product.品牌} {product.货号})")
                            logger.info(f"  新URL: {first_url}")
                    else:
                        # 没有有效的URL，设置为空
                        update_stmt = (
                            update(ProductMaster)
                            .where(ProductMaster.id == product.id)
                            .values(main_image_path=None)
                        )
                        await db.execute(update_stmt)
                        failed_count += 1
                        
                        if failed_count <= 3:
                            logger.warning(f"产品 {product.id} 没有有效的图片URL")
                else:
                    # 没有original_image_urls，设置为空
                    update_stmt = (
                        update(ProductMaster)
                        .where(ProductMaster.id == product.id)
                        .values(main_image_path=None)
                    )
                    await db.execute(update_stmt)
                    failed_count += 1
                    
            except Exception as e:
                failed_count += 1
                logger.error(f"处理产品 {product.id} 时出错: {e}")
        
        await db.commit()
        
        logger.info(f"\n修复完成:")
        logger.info(f"  - 成功修复: {fixed_count} 个产品")
        logger.info(f"  - 无效URL: {failed_count} 个产品")
        
        # 验证修复结果
        stmt2 = select(ProductMaster).where(ProductMaster.main_image_path == '[')
        result2 = await db.execute(stmt2)
        remaining = result2.scalars().all()
        
        logger.info(f"  - 剩余未修复: {len(remaining)} 个产品")
        
        # 测试几个产品
        stmt3 = select(ProductMaster).where(
            ProductMaster.main_image_path.like('http%')
        ).limit(3)
        result3 = await db.execute(stmt3)
        test_products = result3.scalars().all()
        
        logger.info(f"\n验证修复后的产品:")
        for p in test_products:
            logger.info(f"  {p.品牌} {p.货号}: {p.main_image_path[:80]}...")

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