# cSpell:ignore momo
"""
批次更新缺少圖片的商品
使用 i_code 從商品詳情頁直接獲取圖片 URL
"""
import os
import sys
import time
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

# 設定路徑
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, BASE_DIR)

from database.models import Product
from utils.image_url_builder import get_product_image_url

# 資料庫路徑
DB_PATH = os.path.join(BASE_DIR, 'data', 'momo_database.db')

def update_missing_images(batch_size: int = 50, delay: float = 0.5):
    """
    批次更新缺少圖片的商品

    Args:
        batch_size: 每批處理的商品數量
        delay: 每個請求之間的延遲（秒），避免請求過快
    """
    print("🔄 開始批次更新缺少圖片的商品...\n")

    if not os.path.exists(DB_PATH):
        print(f"❌ 資料庫檔案不存在: {DB_PATH}")
        return

    try:
        engine = create_engine(f"sqlite:///{DB_PATH}")
        Session = sessionmaker(bind=engine)
        session = Session()

        # 查詢所有缺圖的商品
        missing_products = session.query(Product).filter(
            (Product.image_url == None) | (Product.image_url == '')
        ).limit(batch_size).all()

        total = len(missing_products)
        print(f"📊 找到 {total} 個缺圖商品（本次處理前 {batch_size} 個）\n")

        if total == 0:
            print("✅ 沒有需要更新的商品！")
            return

        success_count = 0
        fail_count = 0

        for idx, product in enumerate(missing_products, 1):
            print(f"[{idx}/{total}] 處理: [{product.i_code}] {product.name[:50]}...")

            try:
                # 從商品詳情頁獲取圖片 URL
                image_url = get_product_image_url(product.i_code)

                if image_url:
                    product.image_url = image_url
                    session.commit()
                    print(f"  ✅ 成功: {image_url}")
                    success_count += 1
                else:
                    print(f"  ⚠️ 無法獲取圖片（可能已下架或不存在）")
                    fail_count += 1

                # 延遲，避免請求過快
                time.sleep(delay)

            except Exception as e:
                print(f"  ❌ 錯誤: {e}")
                fail_count += 1
                session.rollback()

        session.close()

        print("\n" + "=" * 60)
        print("📊 更新結果")
        print("=" * 60)
        print(f"✅ 成功: {success_count}/{total} ({success_count/total*100:.1f}%)")
        print(f"❌ 失敗: {fail_count}/{total} ({fail_count/total*100:.1f}%)")

        if success_count > 0:
            print(f"\n💡 提示: 已更新 {success_count} 個商品的圖片！")
        if fail_count > 0:
            print(f"\n⚠️ 注意: {fail_count} 個商品無法獲取圖片（可能已下架）")

    except Exception as e:
        print(f"❌ 批次更新失敗: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(description='批次更新缺圖商品')
    parser.add_argument('--batch-size', type=int, default=50, help='每批處理的商品數量（預設: 50）')
    parser.add_argument('--delay', type=float, default=0.5, help='每個請求之間的延遲秒數（預設: 0.5）')

    args = parser.parse_args()

    update_missing_images(batch_size=args.batch_size, delay=args.delay)
