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()

# 讀取需要修復的商品清單
with open('incorrect_images.txt', 'r') as f:
    i_codes = [line.strip() for line in f if line.strip()]

total = len(i_codes)
print(f"🔧 開始修復 {total} 個商品的圖片 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:
        if i % 50 == 0 or i <= 10:
            print(f"\n[{i}/{total}] 處理: [{i_code}] {product.name[:45]}...")
            if product.image_url:
                print(f"  ❌ 舊: {product.image_url[:70]}...")
        
        # 獲取新的圖片 URL
        new_image_url = get_product_image_url(i_code)
        
        if new_image_url:
            product.image_url = new_image_url
            session.commit()
            if i % 50 == 0 or i <= 10:
                print(f"  ✅ 新: {new_image_url}")
            success_count += 1
        else:
            if i % 50 == 0 or i <= 10:
                print(f"  ⚠️  無法獲取")
            fail_count += 1
        
        # 每 10 個顯示進度
        if i % 10 == 0:
            progress = i * 100 // total
            print(f"  進度: {i}/{total} ({progress}%) - 成功: {success_count}, 失敗: {fail_count}")
        
        # 延遲避免請求過快
        time.sleep(0.3)
    else:
        fail_count += 1

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

session.close()
