# -*- coding: utf-8 -*-
"""
一键构建 PDF 书籍（PowerShell 调用）
步骤：make_book.py 生成 book.md → pandoc → tex 后处理 → xelatex ×2
用法：python build_pdf.py
"""
import os
import subprocess
import sys
import io

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))  # 项目根
BUILD = os.path.join(ROOT, "build")
XELATEX = r"C:\Program Files\MiKTeX\miktex\bin\x64\xelatex.exe"

# 生成 book.md（含 emoji/符号替换）
sys.path.insert(0, os.path.join(ROOT, "code"))
import make_book
make_book.main()

# pandoc → tex
tex_path = os.path.join(BUILD, "book.tex")
cmd = [
    "pandoc", os.path.join(BUILD, "book.md"), "-o", tex_path,
    "-V", "documentclass=ctexbook", "-V", 'classoption="11pt,openany"',
    "-V", "colorlinks=true", "-N", "--toc", "--toc-depth=1",
    "-H", os.path.join(ROOT, "code", "preamble_cellbio.tex"),
    "--syntax-highlighting=tango",
    "--metadata", "lang=zh-CN", "--resource-path=.",
]
print(">> pandoc")
r = subprocess.run(cmd, cwd=ROOT, capture_output=True)
out = r.stdout.decode("utf-8", errors="replace")
err = r.stderr.decode("utf-8", errors="replace")
print(out[-400:] if out else "")
if r.returncode != 0:
    print("pandoc FAILED:", err[-800:])
    sys.exit(1)

# tex 后处理：目录只保留章级
make_book.postprocess_tex(tex_path)

# xelatex 两遍
os.chdir(BUILD)
for i in range(2):
    print(f">> xelatex pass {i+1}")
    r = subprocess.run([XELATEX, "-interaction=nonstopmode", "book.tex"],
                       capture_output=True)
    # xelatex 输出可能是 UTF-8 或 GBK 混合，用 errors=replace 兜底
    stdout = r.stdout.decode("utf-8", errors="replace")
    print(stdout[-250:] if stdout else "")
    if "Output written" not in stdout:
        print("xelatex ERROR:", stdout[-800:])
        sys.exit(1)

pdf = os.path.join(BUILD, "book.pdf")
print(f"DONE: {pdf} ({os.path.getsize(pdf)/1024/1024:.1f} MB)")
