#!/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 (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 flame head is recovered on all three meshes within the common stable window.", f"{ROOT}/plots/Fig_S12.tif"),
    ("Fig. S13  Center-plane streamwise-velocity slices (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. In all three meshes, the branch tips remain dynamically favored relative to the recessed center.", 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 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"),
]

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

with PdfPages(pdf_path) as pdf:
    # Title / metadata page
    fig = plt.figure(figsize=(8.27, 11.69))
    fig.text(0.08, 0.93, "Online Resource 2", fontsize=14, fontweight="bold")
    fig.text(0.08, 0.88, article_title, fontsize=12, fontweight="bold")
    fig.text(0.08, 0.83, journal_name, fontsize=11)
    fig.text(0.08, 0.79, authors, fontsize=10)
    fig.text(0.08, 0.75, affiliation, fontsize=10)
    fig.text(0.08, 0.71, corr_email, fontsize=10)
    fig.text(
        0.08, 0.62,
        "This file contains the supplementary mesh-resolution study for the baseline phi = 1.0 case, including Fig. S12-S15 and Table S5. The comparisons are restricted to the common stable interval t <= 0.60 ms.",
        fontsize=10, va="top"
    )
    plt.axis("off")
    pdf.savefig(fig, dpi=300)
    plt.close(fig)

    # Figure pages
    for caption, img_path in items:
        fig = plt.figure(figsize=(8.27, 11.69))
        fig.text(0.06, 0.95, "Online Resource 2", fontsize=12, fontweight="bold")
        fig.text(0.06, 0.915, article_title, fontsize=9)
        fig.text(0.06, 0.895, journal_name + " | " + authors, fontsize=8)

        img = np.asarray(Image.open(img_path).convert("RGB"))
        ax = fig.add_axes([0.06, 0.26, 0.88, 0.58])
        ax.imshow(img)
        ax.axis("off")

        fig.text(0.06, 0.18, caption, fontsize=10, va="top")
        pdf.savefig(fig, dpi=300)
        plt.close(fig)

    # 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.95, "Online Resource 2", fontsize=12, fontweight="bold")
    fig.text(0.06, 0.915, article_title, fontsize=9)
    fig.text(0.06, 0.895, journal_name + " | " + authors, fontsize=8)
    fig.text(0.06, 0.865, "Table S5  Mesh-resolution comparison for the baseline phi = 1.0 case within the common stable window.", fontsize=10)

    ax = fig.add_axes([0.05, 0.08, 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.4)

    pdf.savefig(fig, dpi=300)
    plt.close(fig)

print(pdf_path)
