import os
import sys
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

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

print(f"🔍 分析剩餘 {len(i_codes)} 個錯誤商品...\n")

# 分析圖片 URL 格式
old_format = 0  # img2.momoshop.com.tw
og_format_wrong = 0  # og.momoshop.com.tw 但 i_code 不對
no_image = 0

old_format_list = []
og_wrong_list = []

for i_code in i_codes[:100]:  # 只檢查前 100 個
    product = session.query(Product).filter(Product.i_code == i_code).first()
    if product:
        if not product.image_url:
            no_image += 1
        elif 'img' in product.image_url and 'momoshop.com.tw/ecm/img/online' in product.image_url:
            old_format += 1
            old_format_list.append(i_code)
        elif 'og.momoshop.com.tw' in product.image_url:
            og_format_wrong += 1
            og_wrong_list.append(i_code)

print(f"📊 前 100 個商品分析:")
print(f"  舊格式 (img2.momoshop...): {old_format}")
print(f"  新格式但 i_code 錯誤: {og_format_wrong}")
print(f"  無圖片: {no_image}")

print(f"\n舊格式商品範例 (前 10 個):")
for i_code in old_format_list[:10]:
    product = session.query(Product).filter(Product.i_code == i_code).first()
    print(f"  [{i_code}] {product.name[:40]}...")
    print(f"    {product.image_url[:80]}...")

if og_wrong_list:
    print(f"\n新格式但 i_code 錯誤的商品範例 (前 5 個):")
    for i_code in og_wrong_list[:5]:
        product = session.query(Product).filter(Product.i_code == i_code).first()
        print(f"  [{i_code}] {product.name[:40]}...")
        print(f"    {product.image_url}")

session.close()
