import sys, os
sys.path.append(r'D:\cnf\chatbot-canifa-feedback\backend')
from common.pool_wrapper import get_pooled_connection_compat
import json

conn = get_pooled_connection_compat()
cur = conn.cursor()

# Update sunny weather tags
cur.execute('''
    SELECT internal_ref_code, tags 
    FROM dashboard_canifa.ultra_descriptions 
    WHERE LOWER(product_name) LIKE '%ch?ng n?ng%' 
       OR LOWER(clean_description) LIKE '%ch?ng n?ng%' 
       OR LOWER(clean_description) LIKE '%anti uv%'
''')
sunny_items = cur.fetchall()

# Update rainy weather tags
cur.execute('''
    SELECT internal_ref_code, tags 
    FROM dashboard_canifa.ultra_descriptions 
    WHERE LOWER(product_name) LIKE '%áo gió%' 
       OR LOWER(clean_description) LIKE '%áo gió%' 
       OR LOWER(clean_description) LIKE '%tru?t nu?c%' 
       OR LOWER(clean_description) LIKE '%c?n nu?c%'
''')
rainy_items = cur.fetchall()

def merge_tags(existing_tags, new_tag):
    if not existing_tags:
        return [new_tag]
    if isinstance(existing_tags, str):
        try:
            existing_tags = json.loads(existing_tags)
        except:
            existing_tags = []
    if new_tag not in existing_tags:
        existing_tags.append(new_tag)
    return existing_tags

updates = {}

for code, tags in sunny_items:
    updated = merge_tags(tags, 'wthr:troi_nang')
    if 'func:chong_uv' not in updated:
        updated.append('func:chong_uv')
    updates[code] = updated

for code, tags in rainy_items:
    updated = merge_tags(updates.get(code, tags), 'wthr:troi_mua')
    if 'func:can_nuoc' not in updated:
        updated.append('func:can_nuoc')
    # Áo gió cung có th? m?c di choi, mùa thu
    if 'wthr:mua_thu' not in updated:
        updated.append('wthr:mua_thu')
    updates[code] = updated

count = 0
for code, tags in updates.items():
    cur.execute('''
        UPDATE dashboard_canifa.ultra_descriptions 
        SET tags = %s::jsonb 
        WHERE internal_ref_code = %s
    ''', (json.dumps(tags), code))
    count += 1

conn.commit()
cur.close()
conn.close()

print(f'Successfully updated {count} items for sunny/rainy weather.')
