#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""04 chili01 重画（花酱 id=227/228）：圆头大辣椒 -> 与后图一致的尖头红辣椒，并缩小

⚠ 不花钱硬规矩：不调用付费 ImageGen。改用**同一批已定稿手绘素材**程序化重排：
  - 辣椒本体从 chili06（鸟脚下那根完整深红尖头辣椒）抠出，形状 100% 与后面一致；
  - 保留 chili01 原有的火焰 / 舌头 / 问号墨线元素与纸纹；
  - 旧圆头大主体用「逐行纸色中位数」擦除（不做像素替换、不留色块），
    只擦主体连通域，不碰右上火焰。

后处理沿用三铁律：暗像素法判墨迹（亮度<165）、纸色统一到暖白(250,246,236)、
墨迹最下缘 <=1550。

输出：
  D:/WorkBuddyProd/chili04/assets_chili04/chili01.png  （覆盖；原图备份 backup_chili01_old.png）
  D:/Download/muse_exchange/chili01.png               （交换目录，供花酱验）
  D:/Download/muse_exchange/chili01_redraw_compare.png（新旧对比）
"""
import os, sys, shutil
import numpy as np
from PIL import Image, ImageFilter
from scipy import ndimage

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

ASSETS = r"D:/WorkBuddyProd/chili04/assets_chili04"
PROD = r"D:/WorkBuddyProd/chili04"
HERE = r"D:/Download/muse_exchange"
PAPER = np.array([250, 246, 236], dtype=np.float32)


def ink_mask(a):
    """暗像素法（花酱三铁律）：亮度 < 165，避免偏橙暗角误判。"""
    return a.mean(axis=2) < 165


def row_paper_fill(src, erase):
    """逐行从**本图左右边缘的真实纸像素**取样本平铺填充 erase 区。

    ⚠ 不能用「统一 PAPER 暖白」或「拉到中位数」：上部纸色本身偏米黄，
    那样擦除区会变成明显偏亮的白椭圆（第二版踩过）。用同行真实纸像素，
    逐行色偏/纸纹/暗角全部与周围一致。
    """
    a = src.copy()
    h, w = a.shape[:2]
    lum = a.mean(axis=2)
    # 底部纯纸区（墨迹下缘 1548 以下）当无周期纸纹来源；逐行色偏仍由本行边缘决定
    ps, pe = 1580, min(h, 1900)
    paper = a[ps:pe].copy()
    pmed = np.median(paper, axis=1)
    rng = np.random.default_rng(20261115)
    dt = ndimage.distance_transform_edt(erase)   # 边缘 4px 羽化，消除硬边
    for y in range(h):
        ys = np.where(erase[y])[0]
        if not len(ys):
            continue
        pool = np.concatenate([np.arange(0, int(w * .07)), np.arange(int(w * .93), w)])
        pool = pool[lum[y, pool] > 185]
        base = np.median(a[y, pool], axis=0) if len(pool) > 20 else PAPER
        # ⚠ 行号随机、列取整行真实纸像素：不能用等间隔取样，否则会出现同心圆摩尔纹（第三版踩过）
        sy = int(rng.integers(0, paper.shape[0]))
        row = np.clip(paper[sy, ys] - pmed[sy] + base, 0, 255)
        al = np.clip(dt[y, ys] / 4.0, 0, 1)[:, None]
        a[y, ys] = a[y, ys] * (1 - al) + row * al
    return a


def extract_pepper(src08):
    """从 **chili08** 抠鸟叼着的那根完整深红尖头辣椒（含绿蒂、黑色轮廓、高光）。

    ⚠ 不用 chili06 那根：鸟爪站在辣椒上，抠图会把整只爪子带进来（第二版踩过）。
    chili08 的辣椒只在左上端与鸟嘴轻触，主体完整无遮挡，且正是后面几张用的造型。
    """
    a = np.asarray(src08.convert("RGB"), dtype=np.float32)
    r, g, b = a[:, :, 0], a[:, :, 1], a[:, :, 2]
    roi = np.zeros(a.shape[:2], bool)
    roi[215:515, 390:670] = True
    red = (r > g * 1.20) & (r > b * 1.20) & (r > 48) & (r < 240) & roi
    green = (g > r * 1.08) & (g > b * 1.02) & (g > 65) & roi
    green &= ndimage.binary_dilation(red, iterations=12)
    # 只收回紧贴红色的黑色轮廓（3px），避免把鸟嘴/远处墨线带进来
    dark = (a.mean(axis=2) < 150) & ndimage.binary_dilation(red, iterations=3) & roi
    mask = red | green | dark
    mask = ndimage.binary_closing(mask, iterations=2)
    mask = ndimage.binary_fill_holes(mask)
    mask = ndimage.binary_dilation(mask, iterations=2)
    lab, n = ndimage.label(mask)
    sizes = ndimage.sum(mask, lab, range(1, n + 1))
    keep = 1 + int(np.argmax(sizes))
    mask = lab == keep
    alpha = ndimage.gaussian_filter(mask.astype(np.float32), 1.0)
    alpha = np.clip(alpha * 255, 0, 255).astype(np.uint8)
    ys, xs = np.where(mask)
    box = (xs.min(), ys.min(), xs.max() + 1, ys.max() + 1)
    rgba = np.dstack([a.astype(np.uint8), alpha])
    return Image.fromarray(rgba[box[1]:box[3], box[0]:box[2]], "RGBA"), box


def main():
    p01 = os.path.join(ASSETS, "chili01.png")
    bak = os.path.join(PROD, "backup_chili01_old.png")
    if not os.path.exists(bak):
        shutil.copyfile(p01, bak)
    # ⚠ 幂等：始终从备份的原始图重做，绝不拿上一轮输出当输入
    im01 = Image.open(bak).convert("RGB")
    im06 = Image.open(os.path.join(ASSETS, "chili08.png")).convert("RGB")
    a = np.asarray(im01, dtype=np.float32)

    # 1) 找主体连通域（最大墨迹域 = 圆头大辣椒），只擦它
    dil = ndimage.binary_dilation(ink_mask(a), iterations=2)
    lab, n = ndimage.label(dil)
    sizes = ndimage.sum(dil, lab, range(1, n + 1))
    big = 1 + int(np.argmax(sizes))
    # 只擦主体连通域**连同其内部**（fill_holes 把封闭墨线轮廓里的浅灰排线/留白一起覆盖），
    # 不碰右上火焰等独立元素。⚠ 用膨胀后的连通域会只擦深墨线、留下浅排线白椭圆（第一版踩过）。
    filled = ndimage.binary_fill_holes(lab == big)
    erase = ndimage.binary_dilation(filled, iterations=6)
    ys, xs = np.where(filled)
    print("erase bbox=(%d,%d,%d,%d) area=%d filled=%d" %
          (xs.min(), ys.min(), xs.max(), ys.max(), int(sizes.max()), int(filled.sum())), flush=True)

    # 2) 擦成纸色（逐行纸色中位数，保留纸纹）
    cleaned = np.clip(row_paper_fill(a, erase), 0, 255).astype(np.uint8)
    base = Image.fromarray(cleaned)

    # 3) 抠 chili08 辣椒 + 放大到约 400px 宽（仍明显小于旧主体 657×867，不占满画面）
    pepper, box = extract_pepper(im06)
    print("pepper box=%s size=%s" % (box, pepper.size), flush=True)
    # 抠图单独留档，供花酱/刚检查有没有带进鸟爪等残留
    pepper.save(os.path.join(HERE, "chili01_pepper_cutout.png"))
    scale = 1.55
    nw, nh = int(pepper.width * scale), int(pepper.height * scale)
    pepper = pepper.resize((nw, nh), Image.LANCZOS)
    print("pepper resized=%s" % (pepper.size,), flush=True)

    # 4) 贴到原主体区偏上中部（不占满画面；下方留给问号）
    px, py = 190, 300
    base.paste(pepper, (px, py), pepper)

    # 5) 逐行加性白平衡（与 chili04_finalize_imgs.py 其它 7 张定稿图同一道）：
    #    把整图低频纸色统一到暖白，顺带抹平擦除区与周围的椭圆色差。
    #    用加性偏移而非像素替换，纸纹/排线/明暗层次全部保留。
    out = np.asarray(base.convert("RGB"), dtype=np.float32)
    h2, w2 = out.shape[:2]
    est = np.zeros((h2, 3), np.float32)
    for y in range(h2):
        row = out[y]
        lum = row.sum(axis=1)
        hi = row[lum >= np.percentile(lum, 75)]
        edge = np.concatenate([out[y, :int(w2 * .06)], out[y, int(w2 * .94):]], axis=0)
        est[y] = .7 * np.median(hi, axis=0) + .3 * np.median(edge, axis=0)
    k = 51
    pad = np.pad(est, ((k // 2, k // 2 + 1), (0, 0)), mode="edge")
    cs = np.cumsum(pad, axis=0)
    smooth = (cs[k:] - cs[:-k]) / k
    corr = np.clip(PAPER - smooth, -48, 48).astype(np.float32)
    out = np.clip(out + corr[:, None, :], 0, 255)
    inkbot = int(np.where(ink_mask(out).sum(axis=1) >= 8)[0].max())
    print("inkbot=%d (limit 1550) wb_corr_max=%.1f" % (inkbot, np.abs(corr).max()), flush=True)
    assert inkbot <= 1550, "墨迹下缘越线: %d" % inkbot

    final = Image.fromarray(out.astype(np.uint8))
    final.save(p01)
    final.save(os.path.join(HERE, "chili01.png"))
    print("saved %s / exchange chili01.png" % p01, flush=True)

    # 6) 新旧对比图（供花酱验）
    old = Image.open(bak).convert("RGB").resize((405, 720))
    new = final.resize((405, 720))
    cmp = Image.new("RGB", (810, 750), (250, 246, 236))
    cmp.paste(old, (0, 30)); cmp.paste(new, (405, 30))
    from PIL import ImageDraw
    d = ImageDraw.Draw(cmp)
    d.text((12, 8), "OLD (round, oversized)", fill=(30, 30, 30))
    d.text((417, 8), "NEW (pointed, smaller)", fill=(30, 30, 30))
    cmp.save(os.path.join(HERE, "chili01_redraw_compare.png"))
    print("compare saved", flush=True)


if __name__ == "__main__":
    main()
