#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
04 辣椒 8 张静态底图定版（1080×1920 满幅版式 v3 + 花酱 id=214「加表面细节」新指示）

后处理链：
  1) 逐行纸色估计 -> 加性白平衡统一到暖白 (250,246,236)。
     用「加性偏移」而非像素替换，保留纸纹/排线/明暗层次（bee02 踩过三次色块的坑）。
     逐行平滑还能消掉 AI 直出常见的上下纸色渐变与第 1 张的纯白硬分界。
  2) 右下角「AI生成」水印：TARGET 纸色覆盖 + 双向羽化（AI 标识只允许片头 3 秒）。
  3) resize 1080×1920；墨迹最下缘 <= 1548（花酱 id=183 安全线，留 2px 余量），
     超线整体上移补纸色，不硬裁内容。
  4) 可选 --mono：去色转黑白线描（花酱若要「细节加满但保持黑白」，一条命令切换）。

输出：D:/WorkBuddyProd/chili04/assets_chili04/chili{01,02,04,05,06,07,08,09}.png
"""
import glob, json, os, sys
import numpy as np
from PIL import Image, ImageDraw, ImageFont

try:
    sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except Exception:
    pass

RAW = r"D:/WorkBuddyProd/chili04/imgs_raw"
OUT = r"D:/WorkBuddyProd/chili04/assets_chili04"
HERE = r"D:/Download/muse_exchange"
os.makedirs(OUT, exist_ok=True)

W, H = 1080, 1920
PAPER = np.array([250, 246, 236], dtype=np.float32)
LIMIT = 1548
NAMES = ["chili01", "chili02", "chili04", "chili05",
         "chili06", "chili07", "chili08", "chili09"]  # 3 号 TRPV1 不渲（花酱供动效）
MONO = "--mono" in sys.argv


def row_paper_color(a):
    """逐行估计纸色：取该行亮度最高的 25% 像素中位数（纸是画面最亮的部分），
    再与左右边缘 6% 的中位数取平均，抗墨迹污染。"""
    h, w = a.shape[:2]
    out = np.zeros((h, 3), dtype=np.float32)
    for y in range(h):
        row = a[y]
        lum = row.sum(axis=1)
        hi = row[lum >= np.percentile(lum, 75)]
        edge = np.concatenate([a[y, :int(w * .06)], a[y, int(w * .94):]], axis=0)
        out[y] = .7 * np.median(hi, axis=0) + .3 * np.median(edge, axis=0)
    # 51 行滑动平均，消除逐行抖动（防条纹）
    k = 51
    pad = np.pad(out, ((k // 2, k // 2 + 1), (0, 0)), mode="edge")
    cs = np.cumsum(pad, axis=0)
    smooth = (cs[k:] - cs[:-k]) / k
    assert smooth.shape[0] == h, "平滑后行数不对"
    # 限制校正幅度，避免内容区被洗白（放宽到 48 以吃掉 AI 直出的偏橙暗角）
    corr = np.clip(PAPER - smooth, -48, 48)
    return corr.astype(np.float32)


def white_balance(im):
    a = np.asarray(im.convert("RGB"), dtype=np.float32)
    corr = row_paper_color(a)
    a = np.clip(a + corr[:, None, :], 0, 255)
    return Image.fromarray(a.astype(np.uint8))


def remove_wm(im):
    """右下角水印区：TARGET 纸色 + 左右/上下羽化。"""
    w, h = im.size
    x0, y0 = w - 320, h - 110
    patch = Image.new("RGB", (w - x0, h - y0), tuple(int(v) for v in PAPER))
    mask = Image.new("L", patch.size, 255)
    mp = mask.load()
    fw, fh = 55, 38
    for x in range(patch.size[0]):
        for y in range(patch.size[1]):
            ax = min(255, int(255 * x / fw)) if x < fw else 255
            ay = min(255, int(255 * y / fh)) if y < fh else 255
            mp[x, y] = min(ax, ay)
    im.paste(patch, (x0, y0), mask)
    return im


def remove_corner_mark(im):
    """chili02 左上角有一小片紫色杂质（AI 直出），纸色羽化覆盖。"""
    patch = Image.new("RGB", (130, 90), tuple(int(v) for v in PAPER))
    mask = Image.new("L", patch.size, 255)
    mp = mask.load()
    for x in range(patch.size[0]):
        for y in range(patch.size[1]):
            ax = 255 - min(255, int(255 * x / 60)) if x > patch.size[0] - 60 else 255
            ay = 255 - min(255, int(255 * y / 45)) if y > patch.size[1] - 45 else 255
            mp[x, y] = min(ax, ay)
    im.paste(patch, (0, 0), mask)
    return im


def ink_bottom(im):
    """暗像素法：只把亮度 <165 的墨迹计入，避免偏黄/偏橙纸面被误判成墨迹
    （上一版用「离 TARGET 远」判，chili07 的暖色暗角被算成 inkbot=1919 误触发上移）。"""
    a = np.asarray(im.convert("RGB"), dtype=np.int16)
    lum = a.mean(axis=2)
    rows = np.where((lum < 165).sum(axis=1) >= 8)[0]
    return int(rows.max()) if len(rows) else 0


def flatten_bottom_paper(im):
    """墨迹下缘以下全是空白纸面：逐行把底色精确对齐 TARGET，保留像素间纸纹。
    AI 直出常把「底部留白」画成纯白或橙色矩形（chili01 硬分界 / chili07 橙带），
    逐行加性校正吃不掉这种跳变；这里用「行中位数 -> TARGET」平移，
    不做像素替换，且每行都对齐同一个目标色，因此不会引入条纹或新硬边。
    渐变区 80px 从 0 过渡到 1，避免处理边界跳变。"""
    a = np.asarray(im.convert("RGB"), dtype=np.float32)
    h = a.shape[0]
    y0 = min(ink_bottom(im) + 12, h - 1)
    fade = 80
    for y in range(max(0, y0 - fade), h):
        t = min(1.0, max(0.0, (y - (y0 - fade)) / float(fade)))
        row = a[y]
        base = np.median(row, axis=0)
        a[y] = np.clip(row + t * (PAPER - base), 0, 255)
    return Image.fromarray(a.astype(np.uint8))


def fix_ink_bottom(im):
    bot = ink_bottom(im)
    if bot <= LIMIT:
        return im, bot, "ok"
    n = bot - LIMIT
    out = Image.new("RGB", (W, H), tuple(int(v) for v in PAPER))
    out.paste(im.crop((0, n, W, H)), (0, 0))
    return out, ink_bottom(out), "shift_up_%d" % n


def make_mono(im):
    """去色：保留排线/明暗层次，压一点亮度让黑线更实。"""
    a = np.asarray(im.convert("RGB"), dtype=np.float32)
    g = .299 * a[..., 0] + .587 * a[..., 1] + .114 * a[..., 2]
    g = np.clip((g - 128) * 1.12 + 128 + 6, 0, 255)
    return Image.fromarray(np.dstack([g, g, g]).astype(np.uint8))


def main():
    files = sorted(glob.glob(os.path.join(RAW, "*.png")))
    assert len(files) == 8, "期望 8 张原图，实际 %d" % len(files)
    report = []
    sheet = Image.new("RGB", (270 * 4, (472 + 26) * 2), (235, 231, 222))
    try:
        font = ImageFont.truetype("C:/Windows/Fonts/arial.ttf", 18)
    except Exception:
        font = ImageFont.load_default()

    for i, f in enumerate(files):
        im = Image.open(f).convert("RGB")
        im = white_balance(im)
        im = im.resize((W, H), Image.LANCZOS)
        im = flatten_bottom_paper(im)
        # 去水印放在纸色统一之后：此时全图纸面已是 TARGET，贴片才不会显出亮块
        im = remove_wm(im)
        if NAMES[i] == "chili02":
            im = remove_corner_mark(im)
        if MONO:
            im = make_mono(im)
        im, bot, action = fix_ink_bottom(im)
        name = NAMES[i] + ("_mono" if MONO else "")
        path = os.path.join(OUT, name + ".png")
        im.save(path)
        # 纸色残留抽检
        a = np.asarray(im, dtype=np.float32)
        assert a.shape[0] == H and a.shape[1] == W, "%s 尺寸异常 %s" % (name, a.shape)
        t = a[40:180, 20:160].reshape(-1, 3)
        b = a[H - 160:H - 20, W // 2 - 100:W // 2 + 100].reshape(-1, 3)
        top = t.mean(axis=0) if len(t) else PAPER
        bottom = b.mean(axis=0) if len(b) else PAPER
        report.append({"name": name, "src": os.path.basename(f), "ink_bottom": bot,
                       "action": action, "paper_top": [round(float(v)) for v in top],
                       "paper_bottom": [round(float(v)) for v in bottom]})
        print("%-12s inkbot=%d %-16s paper_top=%s paper_bot=%s" %
              (name, bot, action, tuple(int(v) for v in top), tuple(int(v) for v in bottom)))
        x, y = (i % 4) * 270, (i // 4) * (472 + 26)
        sheet.paste(im.resize((270, 472), Image.LANCZOS), (x, y))
        ImageDraw.Draw(sheet).text((x + 6, y + 475), name, fill=(30, 30, 30), font=font)

    suffix = "_mono" if MONO else ""
    sheet_path = os.path.join(HERE, "chili04_final_sheet%s.png" % suffix)
    sheet.save(sheet_path)
    json.dump(report, open(os.path.join(HERE, "chili04_final_imgs_report%s.json" % suffix), "w",
                           encoding="utf-8"), ensure_ascii=False, indent=2)
    print("sheet ->", sheet_path)


if __name__ == "__main__":
    main()
