#!/usr/bin/env python3
"""縦長4コマの仕上げ（1080×1350）に、ガイドのサムネイルと同じシルクスクリーン風の刷りをかける（2026-11-18 試し）

ガイドのサムネイルの仕上げ（p2m-site tools/guide_thumbs/silk.py）の決まりをマンガ用に移したもの:
  地 #f7f7f7・墨 #242424 / 中間の明るさは 45度の網点 / 版ズレ・刷りムラ・紙の粒
マンガは細い線と細かいトーンが多いので、
  - 線（暗い所）は元の形のまま墨で刷る（線の版）
  - トーン・灰色の面はいったんぼかして明るさにし、粗めの網点で刷り直す（網の版）。元の細かいトーンとの干渉（モアレ）を避けるため
  - 網の版だけを少しずらす（版ズレ）
  - 吹き出しの字は線の版に入る。読みにくくならないよう、ムラは弱めにする

使い方:
  python3 silk_manga.py 150 151 152            # 第NN話/仕上げ/ の P1〜P4 → 第NN話/仕上げ_silk/（元の絵は上書きしない）
  python3 silk_manga.py 150 --cell 7 --shift 2 1 --seed 3
"""
import sys, os, glob, argparse
import numpy as np
from PIL import Image, ImageFilter

BASE = os.path.expanduser("~/mnt/PixelstoMotors/ハコブくん/4コママンガ作成データ/縦長")
PAPER = np.array([0xf7, 0xf7, 0xf7], np.float32)
INK = np.array([0x24, 0x24, 0x24], np.float32)

# 週刊誌のマンガの色の付いた再生紙と、色のインク（2026-11-18 試し）
# 紙の色・インクの色（RGB）。SECOND は2色刷り（line_style=two）の2色目
PRESETS = {
    "white":  ((0xf7, 0xf7, 0xf7), (0x24, 0x24, 0x24)),   # ガイドと同じ白い紙・墨
    "yellow": ((0xec, 0xe4, 0xc6), (0x1c, 0x18, 0x14)),   # くすんだ黄色の紙・茶がかった墨（2026-11-18 紙を落ち着かせ、インクを濃く）
    "pink":   ((0xec, 0xda, 0xd8), (0x34, 0x10, 0x18)),   # くすんだピンクの紙・濃いえんじ
    "green":  ((0xe0, 0xe6, 0xd6), (0x10, 0x1a, 0x30)),   # くすんだ緑の紙・濃い紺
    "blue":   ((0xda, 0xe2, 0xe6), (0x12, 0x1a, 0x26)),   # くすんだ水色の紙・紺墨
    # 2026-11-18 追加の案
    "orange": ((0xee, 0xdc, 0xc8), (0x30, 0x18, 0x10)),   # 薄いだいだいの紙・焦げ茶
    "lilac":  ((0xe2, 0xdc, 0xe6), (0x22, 0x16, 0x34)),   # 藤色の紙・紫がかった紺
    "straw":  ((0xe4, 0xdf, 0xd0), (0x20, 0x20, 0x20)),   # わら半紙（灰がかった生成り）・墨
    "grey":   ((0xd9, 0xda, 0xd6), (0x14, 0x1c, 0x2a)),   # ねずみ色の紙・紺墨
    "mint":   ((0xd8, 0xe8, 0xe0), (0x10, 0x2a, 0x24)),   # 青みの緑の紙・深緑
    "cream_red": ((0xf0, 0xe8, 0xcc), (0x5a, 0x16, 0x14)), # 黄色の紙・赤茶のインク（赤刷り風）
}

SECOND = {"orange": (0x40, 0x6e, 0xd8), "lilac": (0xc6, 0x50, 0x4b), "straw": (0xc6, 0x50, 0x4b), "grey": (0xc6, 0x50, 0x4b), "mint": (0xc6, 0x50, 0x4b), "cream_red": (0x40, 0x6e, 0xd8), "yellow": (0xc6, 0x50, 0x4b), "pink": (0x40, 0x6e, 0xd8), "green": (0xc6, 0x50, 0x4b), "blue": (0xc6, 0x50, 0x4b), "white": (0xc6, 0x50, 0x4b)}


def blur(a, r):
    im = Image.fromarray(np.clip(a * 255, 0, 255).astype(np.uint8))
    return np.asarray(im.filter(ImageFilter.GaussianBlur(r)), np.float32) / 255


def noise(h, w, scale, rng):
    """なめらかな雑音（0〜1）。scale は粒の大きさ（px）"""
    sh, sw = max(2, h // scale + 2), max(2, w // scale + 2)
    n = rng.random((sh, sw)).astype(np.float32)
    im = Image.fromarray((n * 255).astype(np.uint8)).resize((w, h), Image.BICUBIC)
    n = np.asarray(im, np.float32) / 255
    n = blur(n, max(1, scale // 4))
    return (n - n.min()) / (n.max() - n.min() + 1e-6)


def halftone(tone, cell, angle=45):
    """tone: 0=黒 1=白。45度の丸い網点で 0/1 の網を返す（1=墨）"""
    h, w = tone.shape
    y, x = np.mgrid[0:h, 0:w].astype(np.float32)
    t = np.deg2rad(angle)
    u = (x * np.cos(t) + y * np.sin(t)) / cell
    v = (-x * np.sin(t) + y * np.cos(t)) / cell
    du, dv = u - np.round(u), v - np.round(v)
    d = np.sqrt(du * du + dv * dv)          # 網点の中心からの距離（0〜0.707）
    cover = 1 - tone                         # 墨の割合
    r = np.sqrt(np.clip(cover, 0, 1) / np.pi)  # 面積が cover になる半径
    dots = (d < r).astype(np.float32)
    # 暗い所（半分より濃い）は白い穴の網にする
    holes = (d >= np.sqrt(np.clip(1 - cover, 0, 1) / np.pi)).astype(np.float32)
    return np.where(cover > 0.5, holes, dots)


def pen_lines(g, soft, where):
    """Gペン・丸ペンのような線にする（2026-11-18 試し）
    - 線の芯をくっきりした墨にする（灰色のぼけた縁を締める）
    - 太い線（Gペンの入りの太い所）は少し太らせ、細い線（丸ペンの細部）は細いまま締める＝強弱を大きくする
    吹き出しの字（where の外）は変えない"""
    crisp = np.clip((0.55 - g) / 0.18, 0, 1)                     # 縁を締めた線
    dark = Image.fromarray(((g < 0.35) * 255).astype(np.uint8))
    core = dark.filter(ImageFilter.MinFilter(3))                   # 幅3px以上の太い所の芯
    fat = np.asarray(core.filter(ImageFilter.MaxFilter(3)), np.float32) / 255   # 芯から1px太らせる
    fat = blur(fat, 0.6)
    fill = blur((g < 0.35).astype(np.float32), 4) > 0.55          # 髪のベタなど広い黒の中は太らせない（ハイライトをつぶさない）
    pen = np.where(fill, crisp, np.maximum(crisp, fat))
    return np.where(where, pen, soft)


def silk(src, cell=5, shift=(2, 1), seed=1, line_th=0.42, gamma=1.0, pen=True, paper="white", line_style="plain", texture="none", rescreen=False, best=False):
    rng = np.random.default_rng(seed)
    g = np.asarray(Image.open(src).convert("L"), np.float32) / 255
    h, w = g.shape
    # 線の版：元の暗い所（少しだけ太らせず、そのまま）
    # 元の絵の細かいトーン（点・斜線）をならした絵。トーンは中間の灰色になり、2〜4px の線は暗いまま残る（2026-11-18 descreen）
    # 面の判定・面の中の線・網の濃さは、すべてこのならした絵から取る。元の絵から取ると、トーンの点を線と見たり見なかったりして、まだらになる
    gs = blur(g, 1.5)
    # トーンの面：ならした絵で中間の灰色が広く続く所
    mid = ((gs > 0.28) & (gs < 0.86)).astype(np.float32)
    area = blur(mid, 6) > 0.6
    # 目・眼鏡のまわりのような小さな灰色の所は網にしない（2026-11-18）。広い面だけ残し、元の面の範囲へ広げ直す
    big = blur(area.astype(np.float32), 18) > 0.6
    area = area & (blur(big.astype(np.float32), 18) > 0.05)
    # 白い地の中の字・細い線（吹き出しの中など）は網にしない：まわりの大半が白い所
    calm = blur((g > 0.9).astype(np.float32), 30) > 0.55
    area = area & ~calm
    # 線の版：面の外は元の線（縁のなめらかさを残す）、面の中はならした絵で暗い所だけ（ポケット・しわの線）
    soft = np.clip((0.62 - g) / 0.4, 0, 1)
    if pen:
        soft = pen_lines(g, soft, ~calm)
    line = np.where(area, np.clip((0.3 - gs) / 0.12, 0, 1), soft)
    tone_area = area
    if not rescreen:
        # 元の絵のトーンをそのまま刷る（2026-11-18 網点を刷り直すと細部がつぶれ、まだらになるため）
        line = np.clip((0.66 - g) / 0.42, 0, 1)
        tone_area = area.copy()
        area = np.zeros_like(area)
    # 網の版：ならした絵の明るさで刷り直す。白に近い所（面の中の手・顔）には乗せない
    tone = np.clip((blur(g, 3.0) ** gamma - 0.06) / 0.88, 0, 1)
    tone = 1 - (1 - tone) * 0.8                                  # 網は元のトーンより少し明るく（やりすぎない）
    net = halftone(tone, cell) * area * (blur(g, 3.0) < 0.82)
    if best:
        # 「ベストのタッチ」（2026-11-18 エイイチが第151話P2で決定）：網点を粗く刷り直し、線は全部揺らす
        # 面の判定・線・網は、descreen を入れる前の作り方そのまま
        if best is True or best == "v1":
            mean = blur(g, 3)
            mid = ((mean > 0.22) & (mean < 0.88)).astype(np.float32)
            area = blur(mid, 9) > 0.78
            big = blur(area.astype(np.float32), 22) > 0.7
            area = area & (blur(big.astype(np.float32), 22) > 0.05) & ~calm
        else:
            # v2：面の判定だけ、ならした絵（gs）から取る。古い話の目の細かいトーンで面がまだらに切れるのを防ぐ（2026-11-18）
            area = tone_area.copy()   # 上で gs から作った面（rescreen=False のとき area は空にしてあるので、写しから戻す）
        inner = np.clip((0.36 - g) / 0.12, 0, 1)
        if best == "v2":
            inner = inner * (blur(g, 1.0) < 0.42)   # 面の中は、元のトーンの1点ずつの黒を線と見なさない（線だけ残す）
        line = np.where(area, inner, soft)
        tone = np.clip((blur(g, max(cell * 0.6, 3.5 if best == "v2" else 0)) ** gamma - 0.06) / 0.88, 0, 1)
        tone = 1 - (1 - tone) * 0.8
        net = halftone(tone, cell) * area
        tone_area = area.copy() if best == "v2" else np.zeros_like(area)   # v2 は面の中の線を揺らさない（トーンの点が塊になるため）
    net = np.roll(net, shift, axis=(0, 1))                        # 版ズレ（網の版だけ少しずらす）
    # 線の版の刷りの見せ方（2026-11-18 案を比べる）
    #  ghost: 版ズレ：線の版をもう1回、少しずらして薄く刷った影
    #  bleed: にじみ：線が紙に少し広がり、縁にインクが溜まる（芯はやや薄い）
    #  mesh : 版の網目：インクの面と線の縁に、スクリーンの細かい格子が出る
    ghost = None
    # 薄い線（奥のドア・壁などを細い灰色の線で描いた所）を消さない（2026-11-18）。
    # 縁を締める・網目で 0/1 にすると、明るい灰色の線は紙と見なされて消えるため、薄いインクとして別に残す
    faint = np.clip((0.93 - g) / 0.5, 0, 1) * 0.7 * (~area)
    if line_style == "ghost":
        ghost = np.roll(line, (3, -2), axis=(0, 1)) * 0.28
    elif line_style == "bleed":
        sp = blur(line, 1.2)
        rim = np.clip(sp - blur(line, 3.0), 0, 1)                  # 縁
        line = np.clip(np.maximum(line * 0.88, sp * 0.95) + rim * 0.6, 0, 1)
    elif line_style == "mesh":
        yy, xx = np.mgrid[0:h, 0:w]
        grid = ((xx % 3 == 0) | (yy % 3 == 0)).astype(np.float32)  # スクリーンの糸
        line = np.clip(line - grid * 0.22 * (line > 0.5), 0, 1)
        edge = (line > 0.15) & (line < 0.85)
        line = np.where(edge, (line > 0.5 - (grid - 0.5) * 0.3).astype(np.float32), line)
    if best:
        line = np.maximum(line, faint)                             # ベストのタッチは、薄い線も揺らす（決めたときの作り方のまま）
    # 線の手ざわり（2026-11-18「線が綺麗すぎる」）
    #  gain  : 刷りの太り。インクが紙に広がって線が少し太り、太さがわずかに揺れる
    #  wobble: 縁の小さな揺れ（にじみ・欠け）。かすれは入れない
    if texture == "soften":
        # 縮めて戻す：確認用の縮小画像を拡大したときの、ほどよく甘い線（2026-11-18）
        im = Image.fromarray((np.clip(line, 0, 1) * 255).astype(np.uint8))
        im = im.resize((round(w * 0.5), round(h * 0.5)), Image.LANCZOS).resize((w, h), Image.BICUBIC)
        line = np.asarray(im, np.float32) / 255
    if texture in ("gain", "both"):
        spread = blur(line, 1.1)
        wob = noise(h, w, 9, rng) - 0.5
        line = np.maximum(line, np.clip((spread - (0.32 + wob * 0.25)) / 0.12, 0, 1))
    if texture in ("wobble", "both"):
        e = blur(line, 0.8)
        band = (e > 0.1) & (e < 0.9) & ~tone_area   # トーンの面の中だけは揺らさない（トーンの点を揺らすと黒い塊になる）。それ以外の線は細い線も揺らす
        r = noise(h, w, 2, rng) - 0.5
        line = np.where(band, np.clip(e + r * 0.9, 0, 1), line)
    if not best:
        line = np.maximum(line, faint)                             # 薄い線は揺らさずに足す（揺らすと点々に途切れるため）
    ink = np.maximum(line, net)
    if ghost is not None:
        ink = np.maximum(ink, ghost)
    # 刷りムラ：大きなムラで墨を少し薄く。ベタの所だけ小さな刷り抜け（紙が見える点）
    m = noise(h, w, 220, rng)
    density = 1 - 0.08 * m
    solid = blur(line, 2) > 0.9                                   # 太いベタだけ（字や細い線には入れない）
    pin = (rng.random((h, w)) > 0.994) & (noise(h, w, 40, rng) > 0.6)
    pin = blur(pin.astype(np.float32), 0.8) > 0.25
    density = np.where(solid & pin, 0.0, density)
    # 紙の粒
    grain = (rng.random((h, w)).astype(np.float32) - 0.5) * 4
    pc, ic = PRESETS[paper]
    pc, ic = np.array(pc, np.float32), np.array(ic, np.float32)
    if paper != "white":
        # 再生紙：色の濃さのムラと、紙に混じった小さな繊維・ごみ
        pc = pc[None, None, :] * (1 - 0.035 * noise(h, w, 120, rng))[..., None]
        fib = (rng.random((h, w)) > 0.9992).astype(np.float32)
        fib = blur(fib, 0.9) * 2.5
        pc = pc * (1 - 0.25 * np.clip(fib, 0, 1))[..., None]
        ic = ic[None, None, :] * np.ones((h, w, 1), np.float32)
        # インクは紙に染みる（掛け合わせ）。ベタでも紙の色が少し透ける
        if line_style == "two":
            # 2色刷り：網の版だけ2色目のインクで刷り、線の版（墨）と重ねる。2色目は版ズレを大きめに
            c2 = np.array(SECOND.get(paper, (0xc6, 0x50, 0x4b)), np.float32)
            n2 = np.roll(net, (3, 2), axis=(0, 1)) * density * 0.9
            l1 = (line * density * 0.99)[..., None]
            out = pc * (1 - n2[..., None] * (1 - c2 / 255))           # 2色目を掛け合わせ
            out = out * (1 - l1) + (out * ic / 255) * l1 + grain[..., None]
        else:
            a = (ink * density * 0.99)[..., None]
            out = pc * (1 - a) + (pc * ic / 255) * a + grain[..., None]
    else:
        a = (ink * density)[..., None]
        out = pc * (1 - a) + ic * a + grain[..., None]
    return Image.fromarray(np.clip(out, 0, 255).astype(np.uint8))


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("eps", nargs="+", type=int)
    ap.add_argument("--cell", type=float, default=5)
    ap.add_argument("--shift", type=int, nargs=2, default=(2, 1))
    ap.add_argument("--seed", type=int, default=1)
    ap.add_argument("--gamma", type=float, default=1.0)
    ap.add_argument("--paper", default=["white"], help="紙とインク: white / yellow / pink / green / blue / orange / lilac / straw / grey / mint / cream_red（話ごとに変えるなら 150=yellow のように並べる）", nargs="+")
    ap.add_argument("--line", default="mesh", help="線の刷り: plain / ghost / bleed / mesh / two（2026-11-18 mesh に決定）")
    ap.add_argument("--texture", default="none", help="線の手ざわり: none / wobble（縁の揺れ）/ gain / both / soften")
    ap.add_argument("--no-pen", action="store_true", help="線のペンの強弱を付けない")
    a = ap.parse_args()
    papers = dict(p.split("=") if "=" in p else (None, p) for p in a.paper)
    for ep in a.eps:
        paper = papers.get(str(ep), papers.get(None, "white"))
        d = "%s/第%d話" % (BASE, ep)
        outd = d + ("/仕上げ_silk" if paper == "white" else "/仕上げ_color_" + paper)
        os.makedirs(outd, exist_ok=True)
        files = sorted(glob.glob(d + "/仕上げ/第%d話_P*_1080x1350.png" % ep))
        ims = []
        for i, f in enumerate(files):
            im = silk(f, a.cell, tuple(a.shift), a.seed + ep * 10 + i, gamma=a.gamma, pen=not a.no_pen, paper=paper, line_style=a.line, texture=a.texture)
            o = outd + "/" + os.path.basename(f).replace(".png", "_%s.png" % paper)
            im.save(o)
            ims.append(im)
            print(o)
        if ims:  # 4枚を並べた確認用
            s = 0.42
            tw, th = round(1080 * s), round(1350 * s)
            sheet = Image.new("RGB", (tw * len(ims) + 12 * (len(ims) + 1), th + 24), (255, 255, 255))
            for i, im in enumerate(ims):
                sheet.paste(im.resize((tw, th), Image.LANCZOS), (12 + i * (tw + 12), 12))
            sheet.save(outd + "/第%d話_%s_4枚_確認用.jpg" % (ep, paper), quality=90)


if __name__ == "__main__":
    main()
