import os
import sys
import re
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()

def check_image_url_match(i_code: str, image_url: str) -> bool:
    """檢查圖片 URL 是否包含對應的 i_code"""
    if not image_url:
        return False
    
    # TP 開頭的商品，檢查完整 i_code
    if i_code.startswith('TP'):
        return i_code in image_url
    
    # 數字商品，檢查多種格式
    code_num = str(int(i_code))
    
    # 格式1: /{i_code}_  或  /{i_code}.
    if f"/{code_num}_" in image_url or f"/{code_num}." in image_url:
        return True
    
    # 格式2: 分段格式 /0014/548/538/ for 14548538
    code_str = code_num.zfill(8)
    part3 = code_str[-3:]
    part2 = code_str[-6:-3]
    part1 = code_str[:-6].zfill(4)
    path_pattern = f"/{part1}/{part2}/{part3}/"
    
    if path_pattern in image_url:
        return True
    
    return False

print("🔍 檢查全部商品的圖片 URL...\n")
print("=" * 100)

# 獲取所有有圖片的商品
products = session.query(Product).filter(Product.image_url.isnot(None), Product.image_url != '').all()

total = len(products)
correct = 0
incorrect = 0
incorrect_list = []

print(f"總商品數（有圖片）: {total}\n")
print("檢查中...")

for i, product in enumerate(products, 1):
    if i % 500 == 0:
        print(f"  進度: {i}/{total} ({i*100//total}%)")
    
    if check_image_url_match(product.i_code, product.image_url):
        correct += 1
    else:
        incorrect += 1
        incorrect_list.append(product.i_code)

print(f"\n" + "=" * 100)
print(f"\n📊 檢查結果:")
print(f"  ✅ 正確: {correct} ({correct*100//total}%)")
print(f"  ❌ 錯誤: {incorrect} ({incorrect*100//total}%)")
print(f"  總計: {total}")

if incorrect > 0:
    print(f"\n⚠️  發現 {incorrect} 個商品的圖片 URL 不正確")
    print(f"\n需要修復的商品 i_code 清單:")
    
    # 輸出到文件
    with open('incorrect_images.txt', 'w') as f:
        for i_code in incorrect_list:
            f.write(f"{i_code}\n")
    
    print(f"  已保存到 incorrect_images.txt")
    
    # 顯示前 50 個
    print(f"\n前 50 個需要修復的商品:")
    for i, i_code in enumerate(incorrect_list[:50], 1):
        print(f"  {i}. {i_code}")
    
    if len(incorrect_list) > 50:
        print(f"  ... 還有 {len(incorrect_list) - 50} 個")

session.close()
