#!/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 numpy as np
import csv
import textwrap

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

def add_running_header(fig):
    fig.text(0.06, 0.965, "Online Resource 2 · Supplementary figures and robustness checks",
             fontsize=9, color="0.35")

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

with PdfPages(pdf_path) as pdf:
    # ---------- page 1: improved title page ----------
    fig = plt.figure(figsize=(8.27, 11.69))
    fig.text(0.08, 0.945, "Online Resource 2 (ESM_2.pdf)", fontsize=13)
    fig.text(0.08, 0.900, "Supplementary mesh-resolution robustness checks for", fontsize=11)

    wrapped_title = textwrap.fill(article_title, width=72)
    fig.text(0.08, 0.855, wrapped_title, fontsize=11)

    fig.text(0.08, 0.800, journal_name, fontsize=10)
    fig.text(0.08, 0.765, authors, fontsize=10)
    fig.text(0.08, 0.730, affiliation, fontsize=10)
    fig.text(0.08, 0.695, corr_email, fontsize=10)

    intro = (
        "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."
    )
    fig.text(0.08, 0.620, textwrap.fill(intro, width=88), fontsize=10, va="top")

    bullets = [
        "Fig. S12: center-plane T = 1200 K contour overlays in a local flame-head window",
        "Fig. S13: centerline overpressure profiles at matched late common-window times",
        "Fig. S14: mesh-resolution comparison of Db and dpAhead trends",
        "Fig. S15: spanwise T = 1200 K contour overlays at t = 0.62 ms",
        "Table S5: tabulated mesh-comparison values at 0.52, 0.58, and 0.62 ms",
    ]
    y = 0.525
    for b in bullets:
        fig.text(0.10, y, u"\u2022 " + b, fontsize=10)
        y -= 0.045

    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)

    # ---------- pages 2-5: existing figures ----------
    page_no = 2
    for caption, img_path in items:
        fig = plt.figure(figsize=(8.27, 11.69))
        add_running_header(fig)

        img = trim_white(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, textwrap.fill(caption, width=118), 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

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

    wrapped_header = [
        "Mesh",
        "Last stable\noutput (s)",
        "Db @\n0.52 ms\n(mm)",
        "Db @\n0.58 ms\n(mm)",
        "Db @\n0.62 ms\n(mm)",
        "dpAhead @\n0.52 ms\n(kPa)",
        "dpAhead @\n0.58 ms\n(kPa)",
        "dpAhead @\n0.62 ms\n(kPa)",
        "t(dpAhead >=\n3 kPa) (s)",
    ]

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

    ax = fig.add_axes([0.04, 0.14, 0.92, 0.68])
    ax.axis("off")

    tbl = ax.table(cellText=body, colLabels=wrapped_header, cellLoc="center", loc="center")
    tbl.auto_set_font_size(False)
    tbl.set_fontsize(8)

    widths = [0.10, 0.13, 0.10, 0.10, 0.10, 0.11, 0.11, 0.11, 0.14]

    for (r, c), cell in tbl.get_celld().items():
        if c < len(widths):
            cell.set_width(widths[c])
        cell.set_edgecolor("0.35")
        cell.set_linewidth(0.5)
        if r == 0:
            cell.set_height(0.14)
            cell.set_facecolor("#f2f2f2")
            cell.set_text_props(weight="bold")
            cell.get_text().set_wrap(True)
        else:
            cell.set_height(0.11)
            if r % 2 == 1:
                cell.set_facecolor("#fbfbfb")

    fig.text(
        0.05, 0.08,
        "Values are reported at matched late common-window times (0.52, 0.58, and 0.62 ms). "
        "The table is used to support mesh-resolution robustness within the common stable interval rather than a whole-window late-stage convergence claim.",
        fontsize=8.5
    )
    fig.text(0.50, 0.03, str(page_no), ha="center", va="center", fontsize=9, color="0.35")
    pdf.savefig(fig, dpi=300)
    plt.close(fig)

print(pdf_path)
