# Descarga genérica de packs Pawchive (WaifuInvoker) y hoja de contacto.
# Uso: python Engine/_download_pawchive.py <post_id> <nombre_carpeta> <nombre_hoja>
# Extrae las URLs t1.pawchive.pw/f/... de la página del post (necesitan Referer).

import pathlib
import re
import sys
import urllib.request
from PIL import Image, ImageDraw, ImageFont

BASE = pathlib.Path(r"C:\Users\Usuario\Downloads\SD")
POST_ID = sys.argv[1]
NAME = sys.argv[2]
SHEET = sys.argv[3] if len(sys.argv) > 3 else f"pawchive_{NAME.lower()}_sheet.jpg"

PAGE = f"https://pawchive.pw/patreon/user/94454331/post/{POST_ID}"
OUTDIR = BASE / "Output" / "pawchive_refs" / NAME
OUTDIR.mkdir(parents=True, exist_ok=True)

UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120 Safari/537.36"
req = urllib.request.Request(PAGE, headers={"User-Agent": UA})
html = urllib.request.urlopen(req, timeout=30).read().decode("utf-8", "ignore")
urls = sorted(set(re.findall(r"https://t1\.pawchive\.pw/f/[^\"]+", html)))
print(f"post {POST_ID}: {len(urls)} urls")

def key(u: str):
    m = re.search(r"/(\d+(?:\.\d+)?)\.png\?", u)
    return (float(m.group(1)), u) if m else (9999, u)

urls = sorted(urls, key=key)
import time
ok = fail = 0
for n, u in enumerate(urls, 1):
    dest = OUTDIR / f"{n:03d}.png"
    if dest.exists():
        ok += 1
        continue
    for attempt in range(4):
        try:
            r = urllib.request.Request(u, headers={"User-Agent": UA, "Referer": PAGE, "Accept": "image/png,image/jpeg,*/*"})
            with urllib.request.urlopen(r, timeout=30) as resp, open(dest, "wb") as f:
                f.write(resp.read())
            ok += 1
            break
        except Exception as e:
            if attempt == 3:
                print(f"fail {n}: {e}")
                fail += 1
            else:
                time.sleep(2 * (attempt + 1) + 1)
        time.sleep(0.15)
print(f"downloaded ok={ok} fail={fail} dir={OUTDIR}")

files = sorted(OUTDIR.glob("*.png"))
COLS, THUMB, PAD, LABEL_H = 8, 230, 6, 26
thumbs = []
for p in files:
    with Image.open(p) as im:
        rgb = im.convert("RGB")
        r = THUMB / rgb.width
        thumbs.append((p.stem, rgb.resize((THUMB, int(rgb.height * r)))))
rows = (len(thumbs) + COLS - 1) // COLS
cell_h = max(t[1].height for t in thumbs) + LABEL_H + PAD * 2
W = COLS * (THUMB + PAD) + PAD
H = rows * cell_h + PAD
sheet = Image.new("RGB", (W, H), (18, 18, 18))
d = ImageDraw.Draw(sheet)
try:
    font = ImageFont.load_default(size=13)
except TypeError:
    font = ImageFont.load_default()
for k, (nm, th) in enumerate(thumbs):
    x = PAD + (k % COLS) * (THUMB + PAD)
    y = PAD + (k // COLS) * cell_h
    sheet.paste(th, (x, y + LABEL_H))
    d.text((x + 2, y + 4), nm, fill=(255, 210, 120), font=font)
out = BASE / "Output" / SHEET
sheet.save(out, quality=88)
print(out, sheet.size)
