#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Generate webp (max 1000x567, keep aspect) untuk semua featured yg perlu fix.
Baca /tmp/need_fix.json, unduh source, reseize, simpan /tmp/rsia_norm/{media}.webp.
Output list file utk upload /tmp/rsia_norm/to_upload.txt (+map media->file utk set featured)."""
import os,io,json,time,sys
import urllib.request
from PIL import Image

WORK="/tmp/rsia_norm"; os.makedirs(WORK,exist_ok=True)
need=json.load(open('/tmp/need_fix.json'))
UA="Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120 Safari/537.36"
MAXW,MAXH=1000,567
LOG=f"{WORK}/gen_log.txt"
open(LOG,'w').close()

def log(*a):
    line=" ".join(str(x) for x in a); print(line,flush=True)
    with open(LOG,'a') as f: f.write(line+"\n")

def fetch(url,timeout=90):
    req=urllib.request.Request(url,headers={"User-Agent":UA})
    with urllib.request.urlopen(req,timeout=timeout) as r:
        return r.read()

def make(img_path,src):
    raw=fetch(src)
    im=Image.open(io.BytesIO(raw))
    im=im.convert("RGB")
    w,h=im.size
    scale=min(MAXW/w,MAXH/h,1.0)
    if scale<1.0:
        im=im.resize((max(1,int(w*scale)),max(1,int(h*scale))),Image.LANCZOS)
    im.save(img_path,"WEBP",quality=85,method=6)
    return im.size, len(raw)

def main():
    done=0; fail=0; map_=json.load(open(WORK+"/gen_map.json")) if os.path.exists(WORK+"/gen_map.json") else {}
    to_up=[]
    for item in need:
        mid=item['media']; src=item.get('src'); posts=item.get('posts',[])
        outp=f"{WORK}/{mid}.webp"
        if not src:
            if 'w' in item and item['w']:
                log(f"{mid}: no src_url tapi ada w, treat alamat dari source_url di cache? skip")
            else:
                log(f"{mid}: NO SOURCE - skip (featured id tanpa url)")
            fail+=1; continue
        if os.path.exists(outp) and os.path.getsize(outp)>0:
            # reuse
            map_[mid]={"file":outp,"posts":posts}; to_up.append(outp); done+=1; continue
        try:
            size,rawlen=make(outp,src)
            map_[mid]={"file":outp,"posts":posts}
            to_up.append(outp)
            log(f"OK {mid}: {size} webp (src {rawlen} bytes)")
            done+=1
        except Exception as e:
            log(f"FAIL {mid}: {str(e)[:100]}"); fail+=1
        time.sleep(0.3)
    json.dump(map_ ,open(WORK+"/gen_map.json",'w'),indent=1)
    open(WORK+"/to_upload.txt",'w').writelines(f+"\n" for f in to_up)
    # juga pastikan post 4348 + innocent tersedia: source dari media 4471/4472/4473
    for pid,src in [("4348_innocent", "https://rsia.kendangsari.com/wp-content/uploads/2026/08/pexels_15511324.jpg")]:
        outp=f"{WORK}/{pid}.webp"
        if not os.path.exists(outp):
            try:
                size,_=make(outp,src); log(f"OK {pid}: {size}"); done+=1
            except Exception as e:
                log(f"FAIL {pid}: {str(e)[:80]}"); fail+=1
        open(WORK+"/to_upload.txt",'a').write(outp+"\n")
    log(f"\nDONE generated={done} fail={fail} | total upload list={len(open(WORK+'/to_upload.txt').readlines())}")

sys.exit(main())
