#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
D06 赛博游园会第二批 · 几何测试图离线图册生成脚本
=====================================================

仅处理 D06 目录：
  输入:  D06/inputs/素材/*.png  （50 张程序绘制的原创几何测试图，只读，绝不覆盖/移动）
  输出:  D06/outputs/  （全部成品）

生成物：
  - index.html          可点击原图的离线图册（可搜索文件名、显示总数 50）
  - contact-sheet.png   缩略图联系表 PNG（保持比例，不拉伸，中文名/空格正常）
  - dimensions.csv      尺寸清单（原文件相对路径、宽、高、sha256）
  - thumbs/*.png        本地缩略图（保持比例，不拉伸）
  - README.md           说明（由本目录手动维护，脚本不覆盖）

用法（在 D06/outputs 目录下）：
  <python> generate.py

重复运行无副作用：只读取 inputs 原图，全部写入 outputs。
"""

import csv
import hashlib
import html
import os
import re
import sys

from PIL import Image, ImageDraw, ImageFont

# ---------------------------------------------------------------------------
# 路径约定
# ---------------------------------------------------------------------------
HERE = os.path.dirname(os.path.abspath(__file__))     # D06/outputs
PROJECT_ROOT = os.path.dirname(HERE)                  # D06
INPUT_DIR = os.path.join(PROJECT_ROOT, "inputs", "素材")
OUTPUT_DIR = HERE
THUMBS_DIR = os.path.join(OUTPUT_DIR, "thumbs")

THUMB_MAX = 320            # 图册缩略图最长边（保持比例 contain）
CONTACT_CELL_W = 200       # 联系表单元格缩略图区域宽度
CONTACT_CELL_H = 150       # 联系表单元格缩略图区域高度
CONTACT_COLS = 10          # 联系表列数（10 x 5 = 50）
CONTACT_ROWS = 5

FONT_CANDIDATES = [
    "/System/Library/Fonts/Supplemental/Arial Unicode.ttf",
    "/System/Library/Fonts/STHeiti Medium.ttc",
    "/System/Library/Fonts/Hiragino Sans GB.ttc",
]


# ---------------------------------------------------------------------------
# 工具函数
# ---------------------------------------------------------------------------
def natural_key(name: str):
    """文件名自然序排序键：数字按数值比较，其余按字符比较。"""
    return [int(part) if part.isdigit() else part
            for part in re.split(r"(\d+)", name)]


def load_font(size: int):
    """加载可渲染中文的系统字体，找不到则回退到默认字体。"""
    for path in FONT_CANDIDATES:
        if os.path.exists(path):
            try:
                return ImageFont.truetype(path, size)
            except Exception:
                continue
    return ImageFont.load_default()


def sha256_of_file(path: str) -> str:
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()


def contain_size(w: int, h: int, box_w: int, box_h: int):
    """按比例缩放至 box 内（contain），保持纵横比、不拉伸。"""
    scale = min(box_w / w, box_h / h)
    tw = max(1, round(w * scale))
    th = max(1, round(h * scale))
    return tw, th


def load_rgb(path: str):
    im = Image.open(path)
    if im.mode in ("RGBA", "LA", "P"):
        im = im.convert("RGBA")
        bg = Image.new("RGBA", im.size, (255, 255, 255, 255))
        bg.alpha_composite(im)
        im = bg.convert("RGB")
    elif im.mode != "RGB":
        im = im.convert("RGB")
    return im


# ---------------------------------------------------------------------------
# 收集素材（按文件名自然序）
# ---------------------------------------------------------------------------
def collect_files():
    files = [f for f in os.listdir(INPUT_DIR)
             if f.lower().endswith(".png") and os.path.isfile(os.path.join(INPUT_DIR, f))]
    files.sort(key=natural_key)
    return files


# ---------------------------------------------------------------------------
# 1) 缩略图 + 尺寸清单
# ---------------------------------------------------------------------------
def make_thumbnails_and_csv(files):
    os.makedirs(THUMBS_DIR, exist_ok=True)
    rows = []
    for name in files:
        full = os.path.join(INPUT_DIR, name)
        im = load_rgb(full)
        w, h = im.size
        digest = sha256_of_file(full)
        rel = os.path.relpath(full, PROJECT_ROOT)   # 相对 D06 根目录

        tw, th = contain_size(w, h, THUMB_MAX, THUMB_MAX)
        im.resize((tw, th), Image.LANCZOS).save(os.path.join(THUMBS_DIR, name), "PNG")

        rows.append({"path": rel, "width": w, "height": h, "sha256": digest,
                     "name": name, "full": full, "thumb_w": tw, "thumb_h": th})
    return rows


def write_csv(rows):
    csv_path = os.path.join(OUTPUT_DIR, "dimensions.csv")
    with open(csv_path, "w", newline="", encoding="utf-8") as f:
        writer = csv.writer(f)
        writer.writerow(["相对路径", "宽", "高", "sha256"])
        for r in rows:
            writer.writerow([r["path"], r["width"], r["height"], r["sha256"]])
    return csv_path


# ---------------------------------------------------------------------------
# 2) 缩略图联系表 PNG
# ---------------------------------------------------------------------------
def make_contact_sheet(rows):
    label_h = 40
    cell_w = CONTACT_CELL_W
    cell_h = CONTACT_CELL_H + label_h
    gap_x, gap_y = 10, 12
    margin = 16
    header_h = 66

    width = margin * 2 + CONTACT_COLS * cell_w + (CONTACT_COLS - 1) * gap_x
    height = header_h + margin + CONTACT_ROWS * cell_h + (CONTACT_ROWS - 1) * gap_y + margin

    sheet = Image.new("RGB", (width, height), (250, 250, 250))
    draw = ImageDraw.Draw(sheet)

    title_font = load_font(26)
    sub_font = load_font(13)
    name_font = load_font(12)
    dim_font = load_font(11)

    draw.text((margin, 14), "几何测试图缩略图联系表", font=title_font, fill=(20, 20, 20))
    draw.text((margin, 46), "共 50 张 · 按文件名自然序排列 · 缩略图保持比例不拉伸",
              font=sub_font, fill=(110, 110, 110))

    for idx, r in enumerate(rows):
        col = idx % CONTACT_COLS
        row = idx // CONTACT_COLS
        x0 = margin + col * (cell_w + gap_x)
        y0 = header_h + margin + row * (cell_h + gap_y)

        # 缩略图区域背景
        draw.rectangle([x0, y0, x0 + cell_w - 1, y0 + CONTACT_CELL_H - 1],
                       fill=(240, 240, 240), outline=(210, 210, 210))

        im = load_rgb(r["full"])
        tw, th = contain_size(im.size[0], im.size[1], CONTACT_CELL_W, CONTACT_CELL_H)
        thumb = im.resize((tw, th), Image.LANCZOS)
        px = x0 + (cell_w - tw) // 2
        py = y0 + (CONTACT_CELL_H - th) // 2
        sheet.paste(thumb, (px, py))

        # 标签：文件名 + 尺寸
        draw.text((x0, y0 + CONTACT_CELL_H + 4), r["name"],
                  font=name_font, fill=(25, 25, 25))
        draw.text((x0, y0 + CONTACT_CELL_H + 22),
                  f'{r["width"]} × {r["height"]}', font=dim_font, fill=(120, 120, 120))

    out = os.path.join(OUTPUT_DIR, "contact-sheet.png")
    sheet.save(out, "PNG")
    return out


# ---------------------------------------------------------------------------
# 3) index.html
# ---------------------------------------------------------------------------
def make_index_html(rows):
    cards = []
    for r in rows:
        name = r["name"]
        thumb_src = "thumbs/" + name          # 相对 index.html
        orig_href = "../inputs/素材/" + name   # 相对 index.html，本地原图相对链接
        esc_name = html.escape(name)
        cards.append(
            '        <a class="card" href="{href}" target="_blank" rel="noopener" data-name="{data}">\n'
            '          <div class="thumb"><img src="{src}" alt="{alt}" loading="lazy"></div>\n'
            '          <div class="meta">\n'
            '            <span class="name" title="{alt}">{alt}</span>\n'
            '            <span class="dims">{w} × {h}</span>\n'
            '          </div>\n'
            '        </a>'.format(
                href=html.escape(orig_href), src=html.escape(thumb_src),
                data=esc_name, alt=esc_name, w=r["width"], h=r["height"]))
    cards_html = "\n".join(cards)
    total = len(rows)

    page = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>几何测试图 · 离线图册</title>
<style>
  :root {{
    --bg: #f5f6f8; --card: #ffffff; --line: #e4e7ec; --text: #1f2329;
    --muted: #8a919c; --accent: #2f6bff;
  }}
  * {{ box-sizing: border-box; }}
  body {{
    margin: 0; font-family: -apple-system, BlinkMacSystemFont, "PingFang SC",
      "Hiragino Sans GB", "Microsoft YaHei", "Noto Sans CJK SC", sans-serif;
    background: var(--bg); color: var(--text);
  }}
  header {{
    position: sticky; top: 0; z-index: 10; background: rgba(245,246,248,.96);
    backdrop-filter: blur(6px); border-bottom: 1px solid var(--line);
    padding: 18px 24px 14px;
  }}
  h1 {{ margin: 0 0 4px; font-size: 20px; font-weight: 650; }}
  .sub {{ color: var(--muted); font-size: 13px; }}
  .toolbar {{ margin-top: 12px; display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }}
  .search {{
    flex: 1 1 240px; max-width: 460px; padding: 9px 12px; font-size: 14px;
    border: 1px solid var(--line); border-radius: 8px; outline: none; background: #fff;
  }}
  .search:focus {{ border-color: var(--accent); box-shadow: 0 0 0 3px rgba(47,107,255,.15); }}
  .badge {{
    font-size: 13px; color: var(--muted); background: #fff; border: 1px solid var(--line);
    padding: 6px 12px; border-radius: 999px; white-space: nowrap;
  }}
  .badge b {{ color: var(--text); }}
  .grid {{
    display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
    gap: 16px; padding: 20px 24px 32px;
  }}
  .card {{
    background: var(--card); border: 1px solid var(--line); border-radius: 12px;
    overflow: hidden; text-decoration: none; color: inherit; display: flex;
    flex-direction: column; transition: box-shadow .15s ease, transform .15s ease;
  }}
  .card:hover {{ box-shadow: 0 6px 20px rgba(30,40,60,.12); transform: translateY(-2px); }}
  .thumb {{
    height: 190px; display: flex; align-items: center; justify-content: center;
    background: #fff; padding: 10px;
  }}
  .thumb img {{ max-width: 100%; max-height: 100%; object-fit: contain; }}
  .meta {{ padding: 10px 12px 12px; border-top: 1px solid var(--line); }}
  .name {{
    display: block; font-size: 13px; word-break: break-all; overflow: hidden;
    text-overflow: ellipsis; white-space: nowrap;
  }}
  .dims {{ display: block; margin-top: 3px; font-size: 12px; color: var(--muted); }}
  .empty {{ padding: 40px; text-align: center; color: var(--muted); }}
</style>
</head>
<body>
<header>
  <h1>几何测试图 · 离线图册</h1>
  <div class="sub">50 张程序绘制的原创几何测试图 · 点击任意缩略图打开原始图片</div>
  <div class="toolbar">
    <input id="search" class="search" type="search" placeholder="按文件名搜索（例如：05、几何）" autocomplete="off">
    <span class="badge" id="total-badge">共 <b>{total}</b> 张</span>
    <span class="badge" id="match-badge">当前显示 <b>{total}</b> 张</span>
  </div>
</header>
<main class="grid" id="grid">
{cards}
</main>
<div class="empty" id="empty" style="display:none">没有匹配的文件名</div>
<script>
(function () {{
  var input = document.getElementById('search');
  var cards = Array.prototype.slice.call(document.querySelectorAll('.card'));
  var total = cards.length;
  var matchBadge = document.getElementById('match-badge');
  var empty = document.getElementById('empty');
  input.addEventListener('input', function () {{
    var q = input.value.trim().toLowerCase();
    var shown = 0;
    cards.forEach(function (c) {{
      var hit = !q || c.getAttribute('data-name').toLowerCase().indexOf(q) !== -1;
      c.style.display = hit ? '' : 'none';
      if (hit) shown++;
    }});
    matchBadge.innerHTML = '当前显示 <b>' + shown + '</b> 张';
    empty.style.display = shown === 0 ? '' : 'none';
  }});
}})();
</script>
</body>
</html>
""".format(total=total, cards=cards_html)

    out = os.path.join(OUTPUT_DIR, "index.html")
    with open(out, "w", encoding="utf-8") as f:
        f.write(page)
    return out


# ---------------------------------------------------------------------------
# 自检
# ---------------------------------------------------------------------------
def self_check(files, rows):
    ok = True
    print("=" * 60)
    print("自检报告")
    print("=" * 60)

    # 1) 数量
    n = len(rows)
    print(f"[数量] 图片总数 = {n}  -> {'OK' if n == 50 else 'FAIL'}")
    ok &= (n == 50)

    # 2) 排序（自然序）
    natural = sorted(files, key=natural_key)
    print(f"[排序] 文件名自然序 = {'OK' if files == natural else 'FAIL'}")
    ok &= (files == natural)

    # 3) 尺寸清单行数与首尾
    csv_path = os.path.join(OUTPUT_DIR, "dimensions.csv")
    with open(csv_path, encoding="utf-8") as f:
        lines = [ln for ln in f.read().splitlines() if ln.strip()]
    print(f"[CSV] 行数(含表头) = {len(lines)} -> {'OK' if len(lines) == 51 else 'FAIL'}")
    ok &= (len(lines) == 51)
    print("      表头:", lines[0])
    print("      首行:", lines[1])

    # 4) 原图相对路径与 sha256 复核
    bad = 0
    for r in rows:
        if not os.path.isfile(r["full"]):
            bad += 1; continue
        if sha256_of_file(r["full"]) != r["sha256"]:
            bad += 1
    print(f"[原图] 全部存在且 sha256 一致 -> {'OK' if bad == 0 else f'{bad} 张异常'}")
    ok &= (bad == 0)

    # 5) 缩略图比例（不拉伸）：缩放后宽高比 ≈ 原图宽高比
    bad = 0
    for r in rows:
        with Image.open(os.path.join(THUMBS_DIR, r["name"])) as im:
            tw, th = im.size
        exp_w, exp_h = contain_size(r["width"], r["height"], THUMB_MAX, THUMB_MAX)
        ratio_ok = abs(tw / th - r["width"] / r["height"]) <= 0.01
        if (tw, th) != (exp_w, exp_h) or not ratio_ok:
            bad += 1
    print(f"[缩略图] 比例一致不拉伸 -> {'OK' if bad == 0 else f'{bad} 张异常'}")
    ok &= (bad == 0)

    # 6) index.html 链接完整性
    idx_path = os.path.join(OUTPUT_DIR, "index.html")
    idx_text = open(idx_path, encoding="utf-8").read()
    cards_count = idx_text.count('class="card"')
    missing = []
    for r in rows:
        if ('href="../inputs/素材/' + r["name"] + '"') not in idx_text:
            missing.append("href:" + r["name"])
        if ('src="thumbs/' + r["name"] + '"') not in idx_text:
            missing.append("src:" + r["name"])
    print(f"[图册] 卡片数 = {cards_count} -> {'OK' if cards_count == 50 else 'FAIL'}")
    print(f"[图册] 原图/缩略图链接齐全 -> {'OK' if not missing else '缺少: ' + str(missing[:5])}")
    ok &= (cards_count == 50) and (not missing)

    # 7) 无绝对本机路径
    leak = "/Users/" in idx_text or PROJECT_ROOT in idx_text
    print(f"[图册] 未写死绝对本机路径 -> {'OK' if not leak else 'FAIL'}")
    ok &= (not leak)

    print("=" * 60)
    print("结论:", "全部通过 ✅" if ok else "存在失败项 ❌")
    print("=" * 60)
    return ok


# ---------------------------------------------------------------------------
def main():
    files = collect_files()
    print(f"发现 {len(files)} 张图片（按自然序）")
    if not files:
        print("未找到素材，退出。", file=sys.stderr)
        sys.exit(1)

    rows = make_thumbnails_and_csv(files)
    csv_path = write_csv(rows)
    sheet_path = make_contact_sheet(rows)
    html_path = make_index_html(rows)

    print("已生成:")
    print("  ", os.path.relpath(html_path, PROJECT_ROOT))
    print("  ", os.path.relpath(sheet_path, PROJECT_ROOT))
    print("  ", os.path.relpath(csv_path, PROJECT_ROOT))
    print("  ", os.path.relpath(THUMBS_DIR, PROJECT_ROOT) + "/*.png (" + str(len(rows)) + " 张)")

    ok = self_check(files, rows)
    sys.exit(0 if ok else 1)


if __name__ == "__main__":
    main()
