#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
科学线 05/06/07 底图定版（通用版，参数化自 chili04_finalize_imgs.py）

用法: python sci_finalize_imgs.py 05 [--mono]

后处理链（铁律，顺序不能改）：
  1) 逐行纸色估计 -> 加性白平衡统一到暖白 (250,246,236)（不做像素替换，保纸纹/排线）
  2) resize 1080x1920
  3) 墨迹下缘以下逐行把底色中位数平移到暖白（吃 AI 直出的纯白/橙带）
  4) 去右下角「AI生成」水印（**必须在纸色统一之后**，否则贴片显亮块）
  5) 墨迹最下缘 <= 1550（底部 12% 是视频号 UI 遮挡区），超线整体上移补纸色
"""
import glob
import json
import os
import sys

import numpy as np
from PIL import Image, ImageDraw, ImageFont

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

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from sci_cfg import ep_paths, EPS, HERE

EP = sys.argv[1]
P = ep_paths(EP)
CFG = EPS[EP]
RAW, OUT = P["raw"], P["assets"]
os.makedirs(OUT, exist_ok=True)

W, H = 1080, 1920
PAPER = np.array([250, 246, 236], dtype=np.float32)
LIMIT = 1550
NAMES = CFG["imgs"]
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)
    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
    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)
    a = np.clip(a + row_paper_color(a)[:, None, :], 0, 255)
    return Image.fromarray(a.astype(np.uint8))


def ink_bottom(im):
    """暗像素法：只把亮度 <165 的墨迹计入，避免偏黄/偏橙纸面被误判成墨迹。"""
    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，保留像素间纸纹。

    ⚠ 起点不能用 ink_bottom()：整幅偏灰的图（如 07 snow01）底部暗点会把
    ink_bottom 误判推到 y≈1845，导致压白只覆盖最底一小段、UI 遮挡区仍是灰的。
    规矩是墨迹下缘 ≤ LIMIT(1550)、底部12%(y>1690)不得有内容，
    故固定从 LIMIT+10 起压白，覆盖整个遮挡区。
    """
    a = np.asarray(im.convert("RGB"), dtype=np.float32)
    h = a.shape[0]
    y0 = min(LIMIT + 10, h - 1)
    fade = 60
    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 global_balance(im):
    """全局纸色二次校正：逐行估计对「整幅偏灰」的图不够（tree07 实测 top=(236,229,219)，
    离暖白还差 14~17），这里用整幅最亮 12% 像素的中位数做一次加性平移，
    仍是加性平移（不做像素替换），纸纹与排线层次保留。"""
    a = np.asarray(im.convert("RGB"), dtype=np.float32)
    lum = a.mean(axis=2)
    thr = np.percentile(lum, 88)
    pool = a[lum >= thr]
    if len(pool) < 500:
        return im
    base = np.median(pool, axis=0)
    corr = np.clip(PAPER - base, -26, 26)
    a = np.clip(a + corr[None, 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 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 = []
    for nm in NAMES:
        cands = sorted(glob.glob(os.path.join(RAW, nm, "*.png")))
        assert len(cands) == 1, "%s 目录里应有 1 张原图，实际 %d" % (nm, len(cands))
        files.append(cands[0])
    assert len(files) == len(NAMES), "期望 %d 张原图，实际 %d" % (len(NAMES), len(files))
    report = []
    cols = 5
    rows = (len(NAMES) + cols - 1) // cols
    sheet = Image.new("RGB", (270 * cols, (472 + 26) * rows), (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 = global_balance(im)
        # 底部纸色压暖白必须放在 global_balance 之后：
        # 否则 global_balance 的整幅加性平移会把已对齐的墨迹下缘以下纸色又推回暖灰
        # （07 snow01 paper_bottom 曾=(233,225,215)，底部12%非纸色 51~59%）
        im = flatten_bottom_paper(im)
        im = remove_wm(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)
        t = a[40:180, 20:160].reshape(-1, 3)
        b = a[H - 160:H - 20, W // 2 - 100:W // 2 + 100].reshape(-1, 3)
        report.append({"name": name, "src": os.path.basename(f), "ink_bottom": bot,
                       "action": action,
                       "paper_top": [round(float(v)) for v in t.mean(axis=0)],
                       "paper_bottom": [round(float(v)) for v in b.mean(axis=0)]})
        print("%-10s inkbot=%d %-16s top=%s bot=%s" %
              (name, bot, action, tuple(int(v) for v in t.mean(axis=0)),
               tuple(int(v) for v in b.mean(axis=0))))
        x, y = (i % cols) * 270, (i // cols) * (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, "sci%s_final_sheet%s.png" % (EP, suffix))
    sheet.save(sheet_path)
    json.dump(report, open(os.path.join(HERE, "sci%s_final_imgs_report%s.json" % (EP, suffix)),
                           "w", encoding="utf-8"), ensure_ascii=False, indent=2)
    print("sheet ->", sheet_path)


if __name__ == "__main__":
    main()
