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')
engine = create_engine(f'sqlite:///{DB_PATH}')
Session = sessionmaker(bind=engine)
session = Session()

# 指定的商品編號
i_codes = ['5939587', '14713987', '14237189', '13759520', '13330513', '13731019', 
           '14049583', '14695038', '14373672', '13646926', '4633943', '6271461', '13559833']

print("🔧 修復第二批商品的圖片 URL:\n")
print("=" * 100)

success_count = 0
fail_count = 0

for i, i_code in enumerate(i_codes, 1):
    product = session.query(Product).filter(Product.i_code == i_code).first()
    if product:
        print(f"\n[{i}/{len(i_codes)}] 處理: [{i_code}] {product.name[:50]}...")
        
        # 檢查當前圖片是否正確
        if product.image_url and i_code in product.image_url:
            print(f"  ⏭️  圖片已正確: {product.image_url}")
            success_count += 1
        else:
            if product.image_url:
                print(f"  ❌ 舊圖片: {product.image_url[:80]}...")
            else:
                print(f"  ⚠️  無圖片")
            
            # 獲取新的圖片 URL
            new_image_url = get_product_image_url(i_code)
            
            if new_image_url:
                product.image_url = new_image_url
                session.commit()
                print(f"  ✅ 更新: {new_image_url}")
                success_count += 1
            else:
                print(f"  ⚠️  無法獲取圖片（可能已下架或不存在）")
                fail_count += 1
        
        # 延遲避免請求過快
        if i < len(i_codes):
            time.sleep(0.5)
    else:
        print(f"\n[{i}/{len(i_codes)}] ⚠️ 找不到商品: [{i_code}]")
        fail_count += 1

print("\n" + "=" * 100)
print(f"\n📊 修復結果:")
print(f"  ✅ 成功: {success_count}")
print(f"  ❌ 失敗: {fail_count}")
print(f"  總計: {len(i_codes)}")

session.close()
