#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""04 chili01 重画 v2（花酱 id=227/228）：圆头大辣椒 -> 尖头红辣椒 + 缩小

⚠ 无擦除路线：v1 用「擦掉旧主体」反复留下白椭圆 / 同心圆 / 水平条带，
  本版**根本不擦**——重新生成一张纯净暖白纸底，把原图的火焰/舌头/问号
  按墨线透明度抠出贴回，再贴辣椒。画面里不存在被擦过的区域。

⚠ 不花钱硬规矩：不调用付费 ImageGen。辣椒从同批已定稿 chili08（鸟叼那根，
  完整无鸟爪、尖头深红带绿蒂）抠出，形状与后面几张 100% 一致。

后处理：归一化卷积估计纸色场 -> 加性统一暖白(250,246,236) -> 墨线 alpha 合成
        -> 暗像素法查墨迹下缘 <=1550。

输出：assets_chili04/chili01.png（覆盖）、交换目录 chili01.png、
      chili01_redraw_compare.png、chili01_pepper_cutout.png
"""
import os, sys, shutil
import numpy as np
from PIL import Image, ImageDraw
from scipy import ndimage
from scipy.ndimage import gaussian_filter

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):
    return a.mean(axis=2) < 165     # 暗像素法（花酱三铁律）


def make_paper(a):
    """归一化卷积估计「无墨背景场」→ 统一暖白 → 加细微纸纹噪声。"""
    h, w = a.shape[:2]
    clean = (~ink_mask(a)).astype(np.float32)
    num = np.stack([gaussian_filter(a[:, :, c] * clean, 60) for c in range(3)], axis=2)
    den = np.maximum(gaussian_filter(clean, 60)[:, :, None], 1e-6)
    bg = num / den
    # 逐行加性统一到暖白（保留极缓的纸色起伏，不做像素替换）
    for y in range(h):
        bg[y] += np.clip(PAPER - np.median(bg[y], axis=0), -22, 22)
    rng = np.random.default_rng(20261115)
    return np.clip(bg + rng.normal(0, 1.0, size=(h, w, 1)), 0, 255).astype(np.float32)


def element_alpha(a):
    """保留除「圆头大主体」外所有墨线元素（火焰 x4 / 舌头 / 问号 / 问号点）。"""
    ink = ink_mask(a)
    dil = ndimage.binary_dilation(ink, iterations=2)
    lab, n = ndimage.label(dil)
    sizes = ndimage.sum(dil, lab, range(1, n + 1))
    big = 1 + int(np.argmax(sizes))                 # 最大域 = 旧圆头主体，丢弃
    keep = [i + 1 for i, s in enumerate(sizes) if s > 800 and (i + 1) != big]
    elems = np.isin(lab, keep)
    # 把贴着墨线的浅灰排线也纳入（保留手绘肌理），但纸色区域保持透明
    near = ndimage.distance_transform_edt(~elems) <= 18
    lum = a.mean(axis=2)
    alpha = np.clip((235 - lum) / 70.0, 0, 1)      # 墨线=1，浅排线渐变，纸=0
    alpha *= (elems | (near & (lum < 232)))
    return gaussian_filter(alpha, 0.6)[:, :, None]


def extract_pepper(src08):
    """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)
    dark = (a.mean(axis=2) < 150) & ndimage.binary_dilation(red, iterations=3) & roi
    mask = ndimage.binary_fill_holes(ndimage.binary_closing(red | green | dark, iterations=2))
    mask = ndimage.binary_dilation(mask, iterations=2)
    lab, n = ndimage.label(mask)
    sizes = ndimage.sum(mask, lab, range(1, n + 1))
    mask = lab == (1 + int(np.argmax(sizes)))
    alpha = np.clip(ndimage.gaussian_filter(mask.astype(np.float32), 1.0) * 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)
    src = Image.open(bak).convert("RGB")            # 幂等：始终从原始备份重做
    a = np.asarray(src, dtype=np.float32)

    paper = make_paper(a)
    alpha = element_alpha(a)
    comp = np.clip(paper * (1 - alpha) + a * alpha, 0, 255)
    base = Image.fromarray(comp.astype(np.uint8))
    print("paper/elems ready alpha_max=%.2f ink_elems=%d" %
          (alpha.max(), int((alpha > .5).sum())), flush=True)

    im08 = Image.open(os.path.join(ASSETS, "chili08.png")).convert("RGB")
    pepper, box = extract_pepper(im08)
    pepper.save(os.path.join(HERE, "chili01_pepper_cutout.png"))
    pepper = pepper.resize((406, 330), Image.LANCZOS)   # 旧主体 657×867，明显缩小
    base.paste(pepper, (190, 300), pepper)
    print("pepper box=%s resized=%s pasted=(190,300)" % (box, pepper.size), flush=True)

    out = np.asarray(base.convert("RGB"), dtype=np.float32)
    inkbot = int(np.where(ink_mask(out).sum(axis=1) >= 8)[0].max())
    print("inkbot=%d (limit 1550)" % inkbot, 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"))

    old = src.resize((405, 720))
    new = final.resize((405, 720))
    cmp = Image.new("RGB", (810, 750), tuple(PAPER.astype(int)))
    cmp.paste(old, (0, 30)); cmp.paste(new, (405, 30))
    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("saved chili01.png / compare / cutout", flush=True)


if __name__ == "__main__":
    main()
