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 = ['6323590', '7904362', '5954422', '6009343', '4248163', '3331634', '7351198', 
           '12589232', '11118441', '10755887', '9009264', '9562474', '11038732', '10901361', 
           '9250857', '5477268', '9600967', '10440331', '10080994', '9900915', '3821684', 
           '10567236', '13351736', '13351734', '12777975', '11640264', '5894654', '10050962', 
           '8318051', '11593427', '9857434']

print(f"🔧 修復第三批商品的圖片 URL (共 {len(i_codes)} 個):\n")
print("=" * 100)

success_count = 0
fail_count = 0
skip_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[:45]}...")
        
        # 檢查當前圖片是否正確
        if product.image_url and i_code in product.image_url:
            print(f"  ⏭️  圖片已正確")
            skip_count += 1
        else:
            if product.image_url:
                print(f"  ❌ 舊圖片: {product.image_url[:70]}...")
            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"  ✅ 更新成功")
                success_count += 1
            else:
                print(f"  ⚠️  無法獲取（可能已下架）")
                fail_count += 1
        
        # 延遲避免請求過快
        if i < len(i_codes):
            time.sleep(0.3)
    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"  ⏭️  已正確跳過: {skip_count}")
print(f"  ❌ 失敗: {fail_count}")
print(f"  總計: {len(i_codes)}")

session.close()
