#!/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 T = 1200 K contour overlays in a local flame-head window for the coarse, baseline, and fine meshes at t = 0.52, 0.58, and 0.62 ms. The same local window is used in all panels. The late common-window bifurcation topology can be compared directly across the three meshes.", f"{ROOT}/plots/Fig_S12.tif"),
    ("Fig. S13. Centerline overpressure profiles in the baseline phi = 1.0 case at t = 0.52, 0.58, and 0.62 ms. The three meshes preserve the same qualitative buildup of the ahead-of-flame compression layer, although the profile amplitude remains mesh-sensitive.", f"{ROOT}/plots/Fig_S13.tif"),
    ("Fig. S14. Mesh-resolution comparison of the precursor metrics within the common stable interval (t <= 0.62 ms): (a) Db(t), (b) dpAhead(t), and (c) trajectories in the (Db, dpAhead) plane.", f"{ROOT}/plots/Fig_S14.tif"),
    ("Fig. S15. T = 1200 K contour overlays at t = 0.62 ms on z = 0.003, 0.010, and 0.017 m for the coarse, baseline, and fine meshes. The center plane remains the location of the clearest branch separation across all three meshes.", f"{ROOT}/plots/Fig_S15.tif"),
]

def trim_white(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:
    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.62 ms.",
             fontsize=10, va="top")
    fig.text(0.10, 0.50, u"\u2022 Fig. S12: center-plane T = 1200 K contour overlays in a local flame-head window", fontsize=10)
    fig.text(0.10, 0.46, u"\u2022 Fig. S13: centerline overpressure profiles at matched late common-window times", fontsize=10)
    fig.text(0.10, 0.42, u"\u2022 Fig. S14: mesh-resolution comparison of Db and dpAhead trends", fontsize=10)
    fig.text(0.10, 0.38, u"\u2022 Fig. S15: spanwise T = 1200 K contour overlays at t = 0.62 ms", fontsize=10)
    fig.text(0.10, 0.34, u"\u2022 Table S5: tabulated mesh-comparison values at 0.52, 0.58, and 0.62 ms", 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)

    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 · Supplementary figures and robustness checks", fontsize=9, color="0.35")
        img = trim_white(Image.open(img_path).convert("RGB"))
        ax = fig.add_axes([0.08, 0.22, 0.84, 0.62])
        ax.imshow(np.asarray(img))
        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

    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 · 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)
