#!/usr/bin/env python3
"""Fix remaining dedup issues."""

with open('/var/www/sneakerpicks/scripts/feed-sync-v4.py', 'r') as f:
    code = f.read()

# 1. Fix normalize_product_name to handle "Maat 41 1/3"
old = r"name = re.sub(r'\s*-\s*(?:Maat|Size)\s*\d{2,3}(?:[.,]\d{1,2})?\b', '', name, flags=re.I)"
new = r"name = re.sub(r'\s*-\s*(?:Maat|Size)\s*\d{2,3}(?:\s+\d+/\d+|[.,]\d{1,2})?\b', '', name, flags=re.I)"
if old in code:
    code = code.replace(old, new)
    print("PATCHED: normalize_product_name handles fractional sizes (41 1/3)")
else:
    print("WARNING: Could not find Maat regex")

# 2. Add merge call for Webgains shops (line 687 area)
old_wg = '''        total_new += new_products; total_offers += shop_offers; total_ph += ph_count
        print(f"  => {new_products} new products, {shop_offers} offers, {ph_count} price records")

    # ── Awin feeds ──'''

new_wg = '''        # Merge duplicate offers (same product, same feed)
        merged = merge_duplicate_offers(cur, conn, db_feed_id, shop_name)
        shop_offers -= merged

        total_new += new_products; total_offers += shop_offers; total_ph += ph_count
        print(f"  => {new_products} new products, {shop_offers} offers, {ph_count} price records")

    # ── Awin feeds ──'''

if old_wg in code:
    code = code.replace(old_wg, new_wg, 1)  # only first occurrence
    print("PATCHED: Added merge call for Webgains shops")
else:
    print("WARNING: Could not find Webgains end section")
    # Try to find what's actually there
    idx = code.find("# ── Awin feeds")
    if idx >= 0:
        print(f"  Found 'Awin feeds' at pos {idx}")
        print(f"  Context: ...{repr(code[idx-200:idx+50])}")

with open('/var/www/sneakerpicks/scripts/feed-sync-v4.py', 'w') as f:
    f.write(code)
print("Done!")
