#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""把多张方形底图羽化拼接成高分辨率竖版底图（解决 API 只出 1024×1024 的问题）

背景：MiniMax image-01 忽略 image_size，恒返回 1024×1024。
      直接铺 1080×2877 要放大 2.81× → 发虚。
      拼接 3 张同主题方图 → 1024×2712，铺满只需放大 1.06× → 清晰。
"""
import os
import sys
import numpy as np
from PIL import Image

BG = '/Users/liuxinyuan/Desktop/Hermes输出-工作类/对外物料/科研朋友圈_20261009/bg'
OUT = os.path.join(BG, '海报底图_竖版拼接.png')
OVERLAP = 200

# 上：绿叶构图 / 中：柔和光斑（正文留白区）/ 下：抽象叶脉（无昆虫，接底部）
STACK = ['bg_热带植物.png', 'bg_叶影光斑_竖版.png', 'bg_抽象叶脉.png']


def stitch(paths, overlap=OVERLAP):
    ims = [np.asarray(Image.open(os.path.join(BG, p)).convert('RGB'), dtype=np.float32) for p in paths]
    W = max(im.shape[1] for im in ims)
    H = sum(im.shape[0] for im in ims) - overlap * (len(ims) - 1)
    out = np.zeros((H, W, 3), dtype=np.float32)
    y = 0
    for i, im in enumerate(ims):
        h, w = im.shape[0], im.shape[1]
        x0 = (W - w) // 2
        if i == 0:
            out[0:h, x0:x0 + w] = im
            y = h
            continue
        a = np.linspace(0, 1, overlap, dtype=np.float32)[:, None, None]   # 上→下 0→1
        out[y - overlap:y, x0:x0 + w] = out[y - overlap:y, x0:x0 + w] * (1 - a) + im[:overlap] * a
        out[y:y + h - overlap, x0:x0 + w] = im[overlap:]
        y = y + h - overlap
    return Image.fromarray(np.clip(out, 0, 255).astype('uint8'))


def clean_patch(im, box, sample=25, blur=6):
    """在柔焦区域无痕去掉小杂物：用补丁上下方条带的颜色做纵向渐变插值填充"""
    from PIL import ImageFilter
    a = np.asarray(im.convert('RGB'), dtype=np.float32)
    x0, y0, x1, y1 = box
    top = a[y0 - sample:y0, x0:x1].mean(axis=0)      # 每列的上方参考色
    bot = a[y1:y1 + sample, x0:x1].mean(axis=0)      # 每列的下方参考色
    h = y1 - y0
    for k in range(h):
        t = k / float(h - 1)
        a[y0 + k, x0:x1] = top * (1 - t) + bot * t
    out = Image.fromarray(np.clip(a, 0, 255).astype('uint8'))
    patch = out.crop(box).filter(ImageFilter.GaussianBlur(blur))
    out.paste(patch, (x0, y0))
    return out


if __name__ == '__main__':
    for p in STACK:
        if not os.path.exists(os.path.join(BG, p)):
            print('❌ 缺文件', p); sys.exit(1)
    im = stitch(STACK)
    im.save(OUT)
    print('✅ %s  %dx%d  %d KB' % (OUT, im.width, im.height, os.path.getsize(OUT) // 1024))
    for target in [(1080, 2877), (1080, 3074)]:
        sc = max(target[0] / im.width, target[1] / im.height)
        print('   铺到 %dx%d → 放大 %.2f×（越小越清晰）' % (target[0], target[1], sc))
    print('   对比：单张方图铺同样尺寸 → 放大 %.2f×' % max(1080 / 1024, 2877 / 1024))
