#!/usr/bin/env python3
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from PIL import Image
import csv
import numpy as np

ROOT = "/home/yyq/OpenFOAM/yyq-v2206/run/meshRobustness_ESM2"

plt.rcParams["font.family"] = "sans-serif"
plt.rcParams["font.sans-serif"] = ["Arial","Helvetica","Liberation Sans","DejaVu Sans"]
plt.rcParams["font.size"] = 10

article_title = "Three-Dimensional Flame-Head Bifurcation and Compression-Hydrodynamic Coupling in LES of Premixed Hydrogen-Air Propagation in a Half-Open Channel"
journal_name = "Flow, Turbulence and Combustion"
authors = "Youquan Yuan; Jiandong He*"
affiliation = "College of Mechanics and Aerospace, Inner Mongolia University of Technology, Hohhot, Inner Mongolia, China"
corr_email = "Corresponding author: hjd@imut.edu.cn"

items = [
    ("Fig. S12. Center-plane temperature slices in a local flame-head window (x <= 30 mm, z = 0.010 m) for the coarse, baseline, and fine meshes at t = 0.40, 0.50, and 0.60 ms. The same T = 1200 K front definition and the same color scale are used throughout. The center-plane double-branch topology is recovered on all three meshes within the common stable interval.", f"{ROOT}/plots/Fig_S12.tif"),
    ("Fig. S13. Center-plane streamwise-velocity slices in a local flame-head window (x <= 30 mm, z = 0.010 m) for the coarse, baseline, and fine meshes at t = 0.40, 0.50, and 0.60 ms. The same color scale is used throughout. The branch-tip-favored acceleration pattern remains visible across the three meshes.", f"{ROOT}/plots/Fig_S13.tif"),
    ("Fig. S14. Mesh-resolution comparison of the precursor metrics within the common stable window (t <= 0.60 ms): (a) Db(t), (b) dpAhead(t), and (c) trajectories in the (Db, dpAhead) plane.", f"{ROOT}/plots/Fig_S14.tif"),
    ("Fig. S15. Temperature slices in a local flame-head window (x <= 30 mm) at t = 0.60 ms on z = 0.003, 0.010, and 0.017 m for the coarse, baseline, and fine meshes. In all three meshes, the center plane exhibits the clearest branch separation, while the off-center planes remain narrower and less fully bifurcated.", f"{ROOT}/plots/Fig_S15.tif"),
]

def trim_white_pil(img, thr=248, pad=8):
    arr = np.asarray(img.convert("RGB"))
    mask = np.any(arr < thr, axis=2)
    ys, xs = np.where(mask)
    if len(xs) == 0:
        return img
    x0 = max(0, int(xs.min()) - pad)
    x1 = min(arr.shape[1], int(xs.max()) + pad + 1)
    y0 = max(0, int(ys.min()) - pad)
    y1 = min(arr.shape[0], int(ys.max()) + pad + 1)
    return img.crop((x0, y0, x1, y1))

pdf_path = f"{ROOT}/esm2/ESM_2.pdf"

with PdfPages(pdf_path) as pdf:
    # page 1, same role as ESM_1 title page
    fig = plt.figure(figsize=(8.27, 11.69))
    fig.text(0.08, 0.94, "Online Resource 2 (ESM_2.pdf)", fontsize=13)
    fig.text(0.08, 0.89, "Supplementary mesh-resolution robustness checks for", fontsize=11)
    fig.text(0.08, 0.85, article_title, fontsize=11)
    fig.text(0.08, 0.80, journal_name, fontsize=10)
    fig.text(0.08, 0.76, authors, fontsize=10)
    fig.text(0.08, 0.72, affiliation, fontsize=10)
    fig.text(0.08, 0.68, corr_email, fontsize=10)

    fig.text(0.08, 0.60,
             "This supplementary file contains Fig. S12-S15 and Table S5. "
             "The added materials document the mesh-resolution study for the baseline phi = 1.0 case "
             "within the common stable interval t <= 0.60 ms.",
             fontsize=10, va="top")

    fig.text(0.10, 0.50, u"\u2022 Fig. S12-S13: center-plane temperature and streamwise-velocity slices in a local flame-head window", fontsize=10)
    fig.text(0.10, 0.46, u"\u2022 Fig. S14: mesh-resolution comparison of Db and dpAhead trends", fontsize=10)
    fig.text(0.10, 0.42, u"\u2022 Fig. S15: spanwise temperature slices at t = 0.60 ms", fontsize=10)
    fig.text(0.10, 0.38, u"\u2022 Table S5: tabulated mesh-comparison values in the common stable interval", fontsize=10)

    fig.text(0.50, 0.04, "1", ha="center", va="center", fontsize=9, color="0.35")
    plt.axis("off")
    pdf.savefig(fig, dpi=300)
    plt.close(fig)

    # figure pages
    page_no = 2
    for caption, img_path in items:
        fig = plt.figure(figsize=(8.27, 11.69))
        fig.text(0.06, 0.965, "Online Resource 2 \u00b7 Supplementary figures and robustness checks",
                 fontsize=9, color="0.35")

        img = trim_white_pil(Image.open(img_path).convert("RGB"))
        arr = np.asarray(img)
        ax = fig.add_axes([0.08, 0.22, 0.84, 0.62])
        ax.imshow(arr)
        ax.axis("off")

        fig.text(0.08, 0.13, caption, fontsize=9.5, va="top")
        fig.text(0.50, 0.04, str(page_no), ha="center", va="center", fontsize=9, color="0.35")
        pdf.savefig(fig, dpi=300)
        plt.close(fig)
        page_no += 1

    # table page
    with open(f"{ROOT}/tables/Table_S5.csv", newline="") as f:
        rr = list(csv.reader(f))
    header = rr[0]
    body = rr[1:]

    fig = plt.figure(figsize=(8.27, 11.69))
    fig.text(0.06, 0.965, "Online Resource 2 \u00b7 Supplementary figures and robustness checks",
             fontsize=9, color="0.35")
    fig.text(0.08, 0.90,
             "Table S5. Mesh-resolution comparison for the baseline phi = 1.0 case within the common stable interval.",
             fontsize=9.5)

    ax = fig.add_axes([0.05, 0.10, 0.90, 0.74])
    ax.axis("off")
    tbl = ax.table(cellText=body, colLabels=header, loc="center")
    tbl.auto_set_font_size(False)
    tbl.set_fontsize(8)
    tbl.scale(1.0, 1.45)

    fig.text(0.50, 0.04, str(page_no), ha="center", va="center", fontsize=9, color="0.35")
    pdf.savefig(fig, dpi=300)
    plt.close(fig)

print(pdf_path)
