# -*- coding: utf-8 -*-
import urllib.request, ssl, re, io, os
from bs4 import BeautifulSoup
from urllib.parse import urljoin
from PIL import Image
ctx=ssl.create_default_context(); ctx.check_hostname=False; ctx.verify_mode=ssl.CERT_NONE
DECOR=re.compile(r'(logo|icon|btn|button|ebook|flowchart|process|banner|sprite|blank|no_?img|arrow|_arr\.|bullet|^bg|_bg|footer|header|sns|share|top_|quick|^er_|file\.gif|^0\.jpg)',re.I)
def get(u):
    req=urllib.request.Request(u,headers={"User-Agent":"Mozilla/5.0"})
    return urllib.request.urlopen(req,context=ctx,timeout=25).read()
def imgs_of(u):
    raw=get(u); soup=BeautifulSoup(raw,"html.parser")
    cont=None
    for sel in [".contents","#contents","#content",".content"]:
        el=soup.select_one(sel)
        if el and len(el.get_text(strip=True))>5: cont=el;break
    if cont is None: cont=soup.body
    res=[]
    for im in cont.find_all("img"):
        s=(im.get("src") or im.get("data-src") or "")
        if not s: continue
        fn=s.split("/")[-1].split("?")[0]
        if DECOR.search(fn): continue
        res.append(urljoin(u,s))
    # board list: also grab list thumbnails / first detail
    return res
TARGETS={
 23:"https://www.k-medi.or.kr/web/lay1/S1T867C868/contents.do",
 26:"https://www.k-medi.or.kr/web/lay1/S1T870C875/contents.do",
 28:"https://www.k-medi.or.kr/web/lay1/S1T870C877/contents.do",
 38:"https://www.k-medi.or.kr/web/lay1/S1T114C115/contents.do",
 43:"https://www.k-medi.or.kr/web/lay1/program/S1T248C648/education/index.do",
 50:"https://www.k-medi.or.kr/web/lay1/S1T29C150/contents.do",
 63:"https://www.k-medi.or.kr/web/lay1/S1T14C93/contents.do",
 72:"https://www.k-medi.or.kr/web/lay1/S1T98C172/contents.do",
 74:"https://www.k-medi.or.kr/web/lay1/S1T234C489/contents.do",
 81:"https://www.k-medi.or.kr/web/lay1/S1T15C99/contents.do",
 84:"https://www.k-medi.or.kr/web/lay1/S1T15C100/contents.do",
 70:"https://www.k-medi.or.kr/web/lay1/S1T98C173/contents.do",
 71:"https://www.k-medi.or.kr/web/lay1/S1T98C174/contents.do",
 78:"https://www.k-medi.or.kr/web/lay1/S1T236C237/contents.do",
}
os.makedirs("_nshots",exist_ok=True)
log=io.open("_montage_log.txt","w",encoding="utf-8")
for r,u in TARGETS.items():
    try:
        srcs=imgs_of(u)[:6]
        ims=[]
        for s in srcs:
            try:
                data=get(s); im=Image.open(io.BytesIO(data)).convert("RGB")
                im.thumbnail((300,300)); ims.append(im)
            except Exception as e: pass
        log.write("r%d: %d imgs %s\n"%(r,len(ims),[s.split('/')[-1][:25] for s in srcs]))
        if not ims: continue
        W=sum(i.width for i in ims)+10*len(ims); H=max(i.height for i in ims)+10
        canvas=Image.new("RGB",(W,H),(255,255,255)); x=5
        for i in ims: canvas.paste(i,(x,5)); x+=i.width+10
        canvas.save("_nshots/row%02d.png"%r)
    except Exception as e:
        log.write("r%d ERR %s\n"%(r,e))
log.close();print("done")
