#!/usr/bin/env python3
"""Patch Awin section of feed-sync-v4.py for transparent feeds."""

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

# Find the Awin offer section - the "ext_id = str(variants[0]" that comes after "# ── Awin feeds ──"
awin_marker = "# ── Awin feeds ──"
awin_pos = content.find(awin_marker)
if awin_pos == -1:
    print("ERROR: Could not find Awin section marker")
    exit(1)

# Find "ext_id = str(variants[0]" after the awin marker
target = '            ext_id = str(variants[0].get("id","")).strip()'
target_pos = content.find(target, awin_pos)
if target_pos == -1:
    print("ERROR: Could not find ext_id line in Awin section")
    exit(1)

patch = """            # Set cutout for transparent feeds (Awin)
            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()

"""

if "Set cutout for transparent feeds (Awin)" not in content:
    content = content[:target_pos] + patch + content[target_pos:]
    with open("/var/www/sneakerpicks/scripts/feed-sync-v4.py", "w") as f:
        f.write(content)
    print("Patched Awin section successfully")
else:
    print("Awin section already patched")
