"""Batch write descriptions for many products at once.
Reads _batch.json: list of {leader, cikks: [...], rows: [...], short, long}
Writes all to xlsx in one open/save cycle, updates progress atomically.
"""
import openpyxl, json, os, sys, io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

BASE = os.path.dirname(os.path.abspath(__file__))
DST = os.path.join(BASE, 'merged_master_v2_updated.xlsx')
PROGRESS = os.path.join(BASE, '_progress.json')
BATCH = os.path.join(BASE, '_batch.json')

with open(BATCH, encoding='utf-8') as f:
    text = f.read()
# Auto-fix Hungarian opening quote followed by ASCII closing quote -> proper right double quote
import re
text_fixed = re.sub(r'„([^"]{1,80})"', lambda m: '„' + m.group(1) + '”', text)
if text_fixed != text:
    with open(BATCH, 'w', encoding='utf-8') as f:
        f.write(text_fixed)
    print('Auto-fixed Hungarian quotes')
batch = json.loads(text_fixed)

# Validation
for item in batch:
    sl = len(item['short']); ll = len(item['long'])
    if sl < 700 or sl > 1100:
        print(f"WARN: {item['leader']} short={sl}")
    if ll < 700 or ll > 1100:
        print(f"WARN: {item['leader']} long={ll}")

# Open xlsx once, write all, save once
wb = openpyxl.load_workbook(DST)
ws = wb['Sheet1']
for item in batch:
    for r in item['rows']:
        ws.cell(row=r, column=104, value=item['short'])
        ws.cell(row=r, column=105, value=item['long'])
tmp = DST + '.tmp'
wb.save(tmp); wb.close()
os.replace(tmp, DST)

# Update progress
with open(PROGRESS, encoding='utf-8') as f:
    prog = json.load(f)
done_leaders = set(prog.get('done_leaders', []))
done_cikks = set(prog.get('done_cikks', []))
for item in batch:
    done_leaders.add(item['leader'])
    for c in item['cikks']:
        done_cikks.add(c)
prog['done_leaders'] = list(done_leaders)
prog['done_cikks'] = list(done_cikks)
prog['next_index'] = prog.get('next_index', 0) + len(batch)
tmp = PROGRESS + '.tmp'
with open(tmp, 'w', encoding='utf-8') as f:
    json.dump(prog, f, ensure_ascii=False, indent=1)
os.replace(tmp, PROGRESS)

print(f'OK: wrote {len(batch)} products. Total done_leaders: {len(done_leaders)}')
