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"
]

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
            
    if not imgUrl:
        # User requested to use a specific similar image or generic
        imgUrl = 'images/dismekan.jpg'
        
    # 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 loading div and grid with static grid
# Remove loading-menu
html = re.sub(r'<div id="loading-menu">.*?</div>', '', html, flags=re.DOTALL)

# Inject cards into grid, remove style="display: none;"
html = re.sub(r'<div class="grid-4" id="menu-grid" style="display: none;">.*?</div>', 
              f'<div class="grid-4" id="menu-grid">\n{cards_html}\n</div>', 
              html, flags=re.DOTALL)

# Replace the script block containing fetch with static filter logic
new_script = """
  <script>
    document.addEventListener('DOMContentLoaded', () => {
      const tabBtns = document.querySelectorAll('.tab-btn');
      const menuItems = document.querySelectorAll('.menu-item-wrapper');
      
      tabBtns.forEach(btn => {
        btn.addEventListener('click', (e) => {
          tabBtns.forEach(b => b.classList.remove('active'));
          e.target.classList.add('active');
          
          const filter = e.target.dataset.filter;
          menuItems.forEach(item => {
            if (filter === 'all' || item.dataset.category === filter) {
              item.style.display = 'block';
            } else {
              item.style.display = 'none';
            }
          });
        });
      });
    });
  </script>
</body>
"""

html = re.sub(r'<script>\s*document.addEventListener\(\'DOMContentLoaded\'.*?</script>\s*</body>', new_script, html, flags=re.DOTALL)

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

print("Chef Kamil static menu generated.")
