#!/usr/bin/env python3
"""Patch feed-sync-v4.py to handle transparent feeds."""
import re

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

# 1. Add TRANSPARENT_FEEDS config after imports
insert_after = "from collections import defaultdict\n"
config_block = "\n# Feeds with transparent PNG images (skip rembg for these)\nTRANSPARENT_FEED_NAMES = {\"Foot Locker NL\", \"Sneakermood\"}\n"
if "TRANSPARENT_FEED_NAMES" not in content:
    content = content.replace(insert_after, insert_after + config_block, 1)
    print("Added TRANSPARENT_FEED_NAMES config")

# 2. Find all "# Upsert offer" locations
positions = [m.start() for m in re.finditer(r'# Upsert offer', content)]
print(f"Found {len(positions)} '# Upsert offer' locations")

# Insert transparent-feed logic before each "# Upsert offer"
# We need to do it in reverse order to preserve positions
cutout_block_wg = """            # Set cutout for transparent feeds (Webgains)
            if product_id and shop_name in TRANSPARENT_FEED_NAMES and image and image.lower().endswith('.png'):
                try:
                    cur.execute("UPDATE products SET cutout_image_url = image_url, needs_cutout = false WHERE id = %s AND cutout_image_url IS NULL", (product_id,))
                except: conn.rollback()

            """

cutout_block_awin = """            # Set cutout for transparent feeds (Awin)
            if product_id and feed_name in TRANSPARENT_FEED_NAMES and image and image.lower().endswith('.png'):
                try:
                    cur.execute("UPDATE products SET cutout_image_url = image_url, needs_cutout = false WHERE id = %s AND cutout_image_url IS NULL", (product_id,))
                except: conn.rollback()

            """

if "Set cutout for transparent feeds" not in content:
    # Apply in reverse order
    for i, pos in enumerate(reversed(positions)):
        idx = len(positions) - 1 - i
        # Find the start of the line containing "# Upsert offer"
        line_start = content.rfind('\n', 0, pos) + 1
        indent = content[line_start:pos]
        
        if idx == 0:
            # First occurrence = Webgains section
            content = content[:line_start] + cutout_block_wg + content[line_start:]
            print(f"Patched Webgains section (position {idx})")
        elif idx == 1:
            # Second occurrence = Awin section
            content = content[:line_start] + cutout_block_awin + content[line_start:]
            print(f"Patched Awin section (position {idx})")

with open("/var/www/sneakerpicks/scripts/feed-sync-v4.py", "w") as f:
    f.write(content)

print("Done! feed-sync-v4.py patched.")
