import json

# Tostum
with open('tostum/js/main.js', 'r', encoding='utf-8') as f:
    t_js = f.read()

# Replace the fallback logic in Tostum
fallback_tostum = """
              let imgUrl = item.imageUrl;
              if (!imgUrl || imgUrl.trim() === '') {
                // Find another product with similar name
                const similar = items.find(p => p.imageUrl && p.title && (p.title.split(' ')[0] === item.title.split(' ')[0] || p.category === item.category));
                imgUrl = similar ? similar.imageUrl : '../images/logo.png';
              }
"""

t_js = t_js.replace("img src=\"${item.imageUrl || 'images/logo.png'}\"", "img src=\"${imgUrl}\"")

# We need to inject the logic right before the HTML string in renderCards
t_js = t_js.replace('container.innerHTML = items.map(item => `', '''
    const htmls = items.map(item => {
      let imgUrl = item.imageUrl;
      if (!imgUrl || imgUrl.trim() === '') {
        const similar = items.find(p => p.imageUrl && p.title && p.category === item.category);
        imgUrl = similar ? similar.imageUrl : '../images/logo.png';
      }
      return `
''')
t_js = t_js.replace('</div>\n    `).join(\'\');', '</div>\n    `;\n    });\n    container.innerHTML = htmls.join(\'\');')

with open('tostum/js/main.js', 'w', encoding='utf-8') as f:
    f.write(t_js)

# Chef Kamil
with open('chef-kamil/menu.html', 'r', encoding='utf-8') as f:
    c_html = f.read()

fallback_chef = """
              let imgUrl = product.imageUrl;
              if(!imgUrl || imgUrl.trim() === '') {
                const similar = data.products.find(p => p.imageUrl && p.title && p.category === product.category);
                imgUrl = similar ? similar.imageUrl : 'https://via.placeholder.com/300x200/1a1a1a/d4af37?text=G%C3%B6rsel+Haz%C4%B1rlan%C4%B1yor';
              }
"""
c_html = c_html.replace("""
              let imgUrl = product.imageUrl;
              if(!imgUrl || imgUrl.trim() === '') {
                imgUrl = 'https://via.placeholder.com/300x200/1a1a1a/d4af37?text=G%C3%B6rsel+Haz%C4%B1rlan%C4%B1yor';
              }
""", fallback_chef)

with open('chef-kamil/menu.html', 'w', encoding='utf-8') as f:
    f.write(c_html)
