"""
board-coach 交互态像素级对比脚本。

用法：
    python scripts/ops/compare_interactive.py <h5_filename> <mp_filename>

功能：
    1. 读取 H5 截图（DPR=3, 宽 1290px）和 MP 截图（DPR=1.5, 宽 645px）
    2. MP 截图 resize 到宽度 1290px（×2 缩放，LANCZOS）
    3. 裁剪两者到相同高度（取较短者）
    4. 保存为 cmp-h5.png 和 cmp-mp.png 供外部 diff 工具使用
"""

import sys
from pathlib import Path
from PIL import Image

ROOT = Path(__file__).resolve().parents[2]
SCREENSHOTS_DIR = ROOT / "docs" / "h5_ui" / "screenshots"


def main():
    if len(sys.argv) != 3:
        print(f"用法: python {sys.argv[0]} <h5_filename> <mp_filename>")
        sys.exit(1)

    h5_name = sys.argv[1]
    mp_name = sys.argv[2]

    h5_path = SCREENSHOTS_DIR / h5_name
    mp_path = SCREENSHOTS_DIR / mp_name

    if not h5_path.exists():
        print(f"错误: H5 截图不存在 → {h5_path}")
        sys.exit(1)
    if not mp_path.exists():
        print(f"错误: MP 截图不存在 → {mp_path}")
        sys.exit(1)

    h5_img = Image.open(h5_path)
    mp_img = Image.open(mp_path)

    print(f"H5: {h5_img.size[0]}×{h5_img.size[1]}")
    print(f"MP: {mp_img.size[0]}×{mp_img.size[1]}")

    # MP ×2 缩放到 1290px 宽
    target_width = 1290
    mp_scale = target_width / mp_img.size[0]
    mp_new_height = int(mp_img.size[1] * mp_scale)
    mp_resized = mp_img.resize((target_width, mp_new_height), Image.LANCZOS)
    print(f"MP resized: {mp_resized.size[0]}×{mp_resized.size[1]}")

    # H5 保持原宽（应已是 1290px）
    h5_resized = h5_img
    if h5_img.size[0] != target_width:
        h5_scale = target_width / h5_img.size[0]
        h5_new_height = int(h5_img.size[1] * h5_scale)
        h5_resized = h5_img.resize((target_width, h5_new_height), Image.LANCZOS)
        print(f"H5 resized: {h5_resized.size[0]}×{h5_resized.size[1]}")

    # 裁剪到相同高度（取较短者）
    min_height = min(h5_resized.size[1], mp_resized.size[1])
    h5_cropped = h5_resized.crop((0, 0, target_width, min_height))
    mp_cropped = mp_resized.crop((0, 0, target_width, min_height))
    print(f"裁剪后尺寸: {target_width}×{min_height}")

    # 保存
    out_h5 = SCREENSHOTS_DIR / "cmp-h5.png"
    out_mp = SCREENSHOTS_DIR / "cmp-mp.png"
    h5_cropped.save(out_h5)
    mp_cropped.save(out_mp)
    print(f"已保存: {out_h5.name}, {out_mp.name}")


if __name__ == "__main__":
    main()
