import csv
import sys

input_file = '/var/www/vhosts/tesscorp.com.mx/hazard.tesscorp.com.mx/Etiquetas_EAN13_Hazard_2026-06-02.csv'
output_file = '/var/www/vhosts/tesscorp.com.mx/hazard.tesscorp.com.mx/update_barcodes.sql'

try:
    with open(input_file, mode='r', encoding='utf-8') as f, open(output_file, mode='w', encoding='utf-8') as out:
        reader = csv.DictReader(f)
        out.write('BEGIN;\n')
        count = 0
        for row in reader:
            sku = row.get('SKU', '').strip()
            barcode = row.get('EAN-13', '').strip()
            if sku and barcode:
                sku_escaped = sku.replace("'", "''")
                barcode_escaped = barcode.replace("'", "''")
                out.write(f"UPDATE product_product SET barcode = '{barcode_escaped}' WHERE default_code = '{sku_escaped}';\n")
                count += 1
        out.write('COMMIT;\n')
    print(f'Generated {count} update statements in {output_file}')
except Exception as e:
    print(f"Error: {e}")
    sys.exit(1)
