import os, json, sqlite3
import qrcode
from qrcode.constants import ERROR_CORRECT_H

ROOT=os.path.dirname(os.path.abspath(__file__))
BASE='https://ciba.res.in/laksyashrimp'


def write_qr(path, url):
    os.makedirs(os.path.dirname(path), exist_ok=True)
    qr=qrcode.QRCode(version=None,error_correction=ERROR_CORRECT_H,box_size=12,border=5)
    qr.add_data(url); qr.make(fit=True)
    qr.make_image().save(path)

# 1) Dashboard/static block + feedback QR: use the exact URLs in static_links.json.
sp_map={}
sl_path=os.path.join(ROOT,'static','json','static_links.json')
with open(sl_path,encoding='utf-8') as f: sl=json.load(f)
for sp, items in sl.get('dashboard',{}).items():
    for idx,item in items.items():
        if item.get('block_url') and item.get('block_qr'):
            write_qr(os.path.join(ROOT,item['block_qr'].lstrip('/')), item['block_url'])
        if item.get('feedback_url') and item.get('feedback_qr'):
            write_qr(os.path.join(ROOT,item['feedback_qr'].lstrip('/')), item['feedback_url'])

# 2) Product/stage QR PNGs: the QR must encode the exact existing QR_Link (the clickable URL).
# Also normalize any old IP in QR_Link to the public CIBA base.
changes=0; stage_count=0
for sp in ('vannamei','monodon','indicus','vannamei_2025'):
    droot=os.path.join(ROOT,'static','data',sp)
    if not os.path.isdir(droot): continue
    for fn in os.listdir(droot):
        if not fn.endswith('.json'): continue
        fp=os.path.join(droot,fn)
        try: data=json.load(open(fp,encoding='utf-8'))
        except Exception: continue
        dirty=False
        for e in data.get('lineage',[]):
            url=e.get('QR_Link','')
            if not url: continue
            # enforce public base if an old absolute URL slipped into source data
            if '14.139.181.163:5899' in url:
                url=url.replace('http://14.139.181.163:5899',BASE); e['QR_Link']=url; dirty=True
            elif url.startswith('/stage/'):
                url=BASE+url; e['QR_Link']=url; dirty=True
            qr_rel=e.get('QR','')
            if qr_rel:
                write_qr(os.path.join(ROOT,'static',qr_rel.replace('qr/','qr/',1)),url)
                stage_count+=1
        if dirty:
            json.dump(data,open(fp,'w',encoding='utf-8'),indent=2,ensure_ascii=False); changes+=1

# 3) Regenerate plate/customer-view QRs from their decoded public target, preserving the target.
# This guarantees all qrcodes remain public and scan-safe.
plate_count=0
from PIL import Image
from pyzbar.pyzbar import decode
qroot=os.path.join(ROOT,'static','qrcodes')
for dirpath,_,files in os.walk(qroot):
    for fn in files:
        if not fn.lower().endswith('.png'): continue
        fp=os.path.join(dirpath,fn)
        try:
            ds=decode(Image.open(fp)); url=ds[0].data.decode('utf-8') if ds else ''
        except Exception:
            url=''
        if not url: continue
        if '14.139.181.163:5899' in url:
            url=url.replace('http://14.139.181.163:5899',BASE)
        if url.startswith(BASE):
            write_qr(fp,url); plate_count+=1

print('Dashboard QR regenerated from static click URLs')
print('Stage/product QR regenerated from QR_Link:',stage_count)
print('Plate/customer QR regenerated:',plate_count)
print('JSON files normalized:',changes)
