#!/usr/bin/env python3.12
"""竖图拼接成横向配图 — 豆包生成前的首选兜底

用法：
  python3.12 scripts/stitch_vertical_to_landscape.py <section> <idx> <img1> [img2 ...] \
      [--out images/MMDD/section_idx.jpg] [--height 700] [--width 750] [--quality 90]

示例（1126 品牌热点第3条 = brand_hotspots 索引 2）：
  python3.12 scripts/stitch_vertical_to_landscape.py brand_hotspots 2 /tmp/a.jpg /tmp/b.jpg /tmp/c.jpg

原理：
  1. 逐张等比缩放到统一高度 H（默认 700）
  2. 横向按顺序拼接 → W_total = sum(各张缩放后宽度)
  3. 整体等比缩放到目标宽度（默认 750），JPEG quality 90
  4. 若拼接后总宽 < 目标宽，则按原高度不放大（避免糊）

适用：原文页里有可用图但全是竖图（海报/鞋款/现场照），且内容是横向排版能容纳的。
优先于豆包生成——不要先调 regen_no_person.py。
"""
import sys, os
from PIL import Image


def stitch(paths, out, height=700, width=750, quality=90, gap=0, bg='white'):
    ims = []
    for p in paths:
        im = Image.open(p)
        im.load()
        ims.append(im.convert('RGB'))
    if not ims:
        raise SystemExit('no input images')

    scaled = []
    for im in ims:
        nh = height
        nw = max(1, round(im.width * nh / im.height))
        scaled.append(im.resize((nw, nh), Image.LANCZOS))

    total_w = sum(s.width for s in scaled) + gap * (len(scaled) - 1)
    canvas = Image.new('RGB', (total_w, height), bg)
    x = 0
    for s in scaled:
        canvas.paste(s, (x, 0))
        x += s.width + gap

    if total_w > width:
        nh = max(1, round(height * width / total_w))
        canvas = canvas.resize((width, nh), Image.LANCZOS)

    os.makedirs(os.path.dirname(out) or '.', exist_ok=True)
    canvas.save(out, 'JPEG', quality=quality)
    return canvas.size, os.path.getsize(out)


if __name__ == '__main__':
    import argparse
    ap = argparse.ArgumentParser(add_help=True)
    ap.add_argument('section')
    ap.add_argument('idx', type=int)
    ap.add_argument('images', nargs='+')
    ap.add_argument('--out', default=None)
    ap.add_argument('--mmdd', default=os.environ.get('MMDD', ''))
    ap.add_argument('--height', type=int, default=700)
    ap.add_argument('--width', type=int, default=750)
    ap.add_argument('--quality', type=int, default=90)
    ap.add_argument('--gap', type=int, default=0)
    a = ap.parse_args()

    out = a.out or (f'images/{a.mmdd}/{a.section}_{a.idx}.jpg' if a.mmdd else f'/tmp/{a.section}_{a.idx}_stitched.jpg')

    size, nbytes = stitch(
        a.images, out,
        height=a.height,
        width=a.width,
        quality=a.quality,
        gap=a.gap,
    )
    print(f'✅ {out}  {size[0]}x{size[1]}  {nbytes // 1024}KB  源 {len(a.images)} 张')
    # 合规自检
    w, h = size
    if not (w >= 500 and h < w * 1.05 and nbytes > 15000):
        print('⚠️ 不合规！检查宽度/方向/体积')
        raise SystemExit(2)
