import json
import re

json_path = 'chef-kamil/menü/trendyol_menu_full (6).json'
html_path = 'chef-kamil/menu.html'

with open(json_path, 'r', encoding='utf-8') as f:
    data = json.load(f)
products = data.get('products', [])

categories = [
    "Pizzalar", "Pideler", "Gözlemeler", "Ekmek Arası Ürünler", 
    "Tatlılar", "Çorbalar", "İçecekler"
]

local_images = {
    "waffle": "images/waffles.jpeg",
    "kavurmalı": "images/kavurmalı.jpg",
    "margherita": "images/margheritta.jpg",
    "margheritta": "images/margheritta.jpg",
    "mixy": "images/mixy.jpg",
    "pepperoni": "images/pepperoni-yeni.jpg",
    "quattro": "images/quattro formaggi.jpg",
    "formaggi": "images/quattro formaggi.jpg",
}

# Products with valid images
valid_products = [p for p in products if p.get('imageUrl')]

def get_shared_word_count(title1, title2):
    stop_words = {"ve", "ile", "pizza", "pide", "gözleme", "tost", "içecek", "tatlı"}
    w1 = set([w for w in title1.lower().split() if w not in stop_words])
    w2 = set([w for w in title2.lower().split() if w not in stop_words])
    return len(w1.intersection(w2))

cards_html = ""
for p in products:
    cat = p.get('category', '')
    title = p.get('title', '')
    desc = p.get('description', '')
    imgUrl = p.get('imageUrl', '')
    
    # Try to match the exact JSON category to one of the tabs
    matched_cat = cat
    for c in categories:
        if c.lower() in cat.lower():
            matched_cat = c
            break
            
    # Resolve missing image
    if not imgUrl:
        # 1. Local image check based on name
        found_local = False
        for keyword, local_path in local_images.items():
            if keyword in title.lower():
                imgUrl = local_path
                found_local = True
                break
        
        # 2. Similar name product check
        if not found_local:
            best_match = None
            best_score = 0
            for vp in valid_products:
                score = get_shared_word_count(title, vp.get('title', ''))
                if score > best_score:
                    best_score = score
                    best_match = vp
                    
            if best_match and best_score > 0:
                imgUrl = best_match.get('imageUrl')
            else:
                # 3. Fallback to same category first image
                cat_products = [vp for vp in valid_products if vp.get('category') == cat]
                if cat_products:
                    imgUrl = cat_products[0].get('imageUrl')
                else:
                    imgUrl = 'images/dismekan.jpg' # Ultimate fallback if no category image exists
                    
    # By default, display all items since the first tab is "Tümü"
    display = 'block'
        
    card = f"""
    <div class="menu-item-wrapper" data-category="{matched_cat}">
      <div class="card menu-card h-100">
        <img src="{imgUrl}" alt="{title}" title="{title}" class="menu-card-img" loading="lazy" onerror="this.src='images/dismekan.jpg'">
        <div class="menu-card-content">
          <h3 class="menu-card-title">{title}</h3>
          <p class="menu-card-desc">{desc}</p>
        </div>
      </div>
    </div>
    """
    cards_html += card

with open(html_path, 'r', encoding='utf-8') as f:
    html = f.read()

# Replace cards in grid
# We need to find the <div class="grid-4" id="menu-grid"> and its closing tag
pattern = r'(<div class="grid-4" id="menu-grid">)(.*?)(</div>\s*<div style="text-align: center; margin-top: 3rem;">)'
# Wait, the grid contains all the previous items, so DOTALL will capture until the first </div> which is wrong.
# It's better to just use a known boundary like <div style="text-align: center; margin-top: 3rem;">
html = re.sub(r'<div class="grid-4" id="menu-grid">.*?</div>\s*<div style="text-align: center; margin-top: 3rem;">', 
              f'<div class="grid-4" id="menu-grid">\n{cards_html}\n</div>\n    <div style="text-align: center; margin-top: 3rem;">', 
              html, flags=re.DOTALL)

with open(html_path, 'w', encoding='utf-8') as f:
    f.write(html)

print("Chef Kamil menu updated with better images.")
