import re

with open('site/tools/merchant-feed-generator.html', 'r', encoding='utf-8') as f:
    html = f.read()

# Replace titles and meta
html = html.replace('Google Merchant feed generator', 'Facebook product feed generator')
html = html.replace('Free Google Merchant Feed Generator', 'Free Facebook Product Feed Generator')
html = html.replace('merchant-feed-generator', 'facebook-product-feed-generator')
html = html.replace('Google Merchant Center-ready XML feed', 'Facebook/Instagram Commerce Manager-ready CSV feed')
html = html.replace('Google Merchant Center', 'Facebook Catalog')
html = html.replace('Merchant feed XML', 'Facebook feed CSV')
html = html.replace('merchant-feed.xml', 'facebook-feed.csv')
html = html.replace("application/xml", "text/csv")
html = html.replace('xml', 'csv')
html = html.replace('XML', 'CSV')

# Fix any casing issues from bulk replace
html = html.replace('Facebook/Instagram Commerce Manager-ready CSV feed', 'Facebook/Instagram Commerce Manager-ready CSV feed')

# Replace buildFeed logic with CSV logic
xml_build_feed_re = r'  function buildFeed\(items\)\{.*?  \}'
csv_build_feed = '''  function buildFeed(items){
    var header = 'id,title,description,availability,condition,price,link,image_link,brand';
    var rows = items.map(function(p){
      var v = [p.id, p.title, p.description, p.availability || 'in_stock', p.condition || 'new', p.price, p.link, p.image_link, p.brand];
      return v.map(function(val){
        var str = String(val == null ? "" : val);
        if (/[",\\n]/.test(str)) return '"' + str.replace(/"/g, '""') + '"';
        return str;
      }).join(',');
    });
    $('output').textContent = [header].concat(rows).join('\\n');
    $('feed-output-section').classList.remove('hidden');
  }'''

html = re.sub(xml_build_feed_re, csv_build_feed, html, flags=re.DOTALL)

with open('site/tools/facebook-product-feed-generator.html', 'w', encoding='utf-8') as f:
    f.write(html)
print("Done")
