#!/usr/bin/env python3
"""
Fix ProductI18n.init() not being called on page load.
Insert it right after TrueBabyCost.init() in all product pages.
"""

pages = ['diapers.html', 'formula.html', 'bottles.html', 'wipes.html', 'breast-pumps.html', 'baby-monitors.html']

for filename in pages:
    path = f'/root/clawd/stroller-app/{filename}'
    try:
        html = open(path).read()
    except FileNotFoundError:
        print(f'⚠️  {filename} not found')
        continue

    original = html

    # Remove old/broken patterns first (partial init calls that are wrong)
    # Pattern 1: inline if-check version that existed before
    import re
    html = re.sub(
        r'\s*if \(typeof ProductI18n !== "undefined" && window\.productPageType\) \{[^}]*\}',
        '',
        html
    )

    # Now insert proper call after TrueBabyCost.init()
    # Handle both spaced and compact versions
    OLD1 = 'await TrueBabyCost.init();\n      \n      // Country picker'
    NEW1 = 'await TrueBabyCost.init();\n\n      // Initialize translations\n      if (typeof ProductI18n !== "undefined") { await ProductI18n.init(window.productPageType); }\n\n      // Country picker'

    OLD2 = 'await TrueBabyCost.init();\n      \n      // Populate country picker'
    NEW2 = 'await TrueBabyCost.init();\n\n      // Initialize translations\n      if (typeof ProductI18n !== "undefined") { await ProductI18n.init(window.productPageType); }\n\n      // Populate country picker'

    OLD3 = 'await TrueBabyCost.init();\n\n      // Country picker'
    NEW3 = 'await TrueBabyCost.init();\n\n      // Initialize translations\n      if (typeof ProductI18n !== "undefined") { await ProductI18n.init(window.productPageType); }\n\n      // Country picker'

    # Don't double-add
    if 'ProductI18n.init(window.productPageType)' not in html:
        if OLD1 in html:
            html = html.replace(OLD1, NEW1, 1)
        elif OLD2 in html:
            html = html.replace(OLD2, NEW2, 1)
        elif OLD3 in html:
            html = html.replace(OLD3, NEW3, 1)
        else:
            # Fallback: insert after any await TrueBabyCost.init(); line
            html = re.sub(
                r'(await TrueBabyCost\.init\(\);)',
                r'\1\n\n      // Initialize translations\n      if (typeof ProductI18n !== "undefined") { await ProductI18n.init(window.productPageType); }',
                html,
                count=1
            )
            print(f'  (used fallback regex for {filename})')

    if html != original:
        open(path, 'w').write(html)
        print(f'✓ Fixed {filename}')
    else:
        print(f'- No changes in {filename}')

print('\n✅ ProductI18n.init() added to all pages')
