import subprocess, os, re
from PIL import Image
IMG='/data/news/images/1104/brand_hotspots_1.jpg'
UA='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36'
cands=['https://file.digitaling.com/eImg/cover/20261102/20261102162610_27303.png']
html='/tmp/dig.html'
subprocess.run(['curl','-sL','--max-time','30','-A',UA,'-o',html,'https://www.digitaling.com/articles/1614941.html'],check=False)
try:
    txt=open(html,'rb').read().decode('utf-8','ignore')
except Exception:
    txt=''
print('html bytes',len(txt))
mas=re.findall(r'https?://file\.digitaling\.com/eImg/[^"\'\s\)]+?\.(?:jpg|jpeg|png)',txt)
extra=[]
for m in mas:
    if m not in extra: extra.append(m)
print('found',len(extra))
for m in extra[:10]: print(' ',m)
cands += extra

done=False
for u in cands:
    tmp='/tmp/b1.src'
    subprocess.run(['curl','-sL','--max-time','25','-e','https://www.digitaling.com/','-A',UA,'-o',tmp,u],check=False)
    sz=os.path.getsize(tmp) if os.path.exists(tmp) else 0
    if sz<20000:
        print(u[-50:],'sz',sz); continue
    try:
        im=Image.open(tmp); w,h=im.size
        print(u[-50:],im.size,im.mode)
        if w<h or w<600: print('  skip landscape'); continue
        if im.mode!='RGB':
            im2=im.convert('RGBA'); bg=Image.new('RGB',im2.size,(255,255,255)); bg.paste(im2,mask=im2.split()[-1]); im=bg
        if w>1200: im=im.resize((1200,int(h*1200/w)),Image.LANCZOS)
        im.save(IMG,'JPEG',quality=88)
        print('SAVED',Image.open(IMG).size,os.path.getsize(IMG)); done=True; break
    except Exception as e:
        print('ERR',e)
print('DONE' if done else 'FAILED')
