#!/usr/bin/env python3
import subprocess, csv

cases = {
    "coarse":   "/home/yyq/OpenFOAM/yyq-v2206/run/S10_phi1p0_screening_m256x24x24",
    "baseline": "/home/yyq/OpenFOAM/yyq-v2206/run/S10_phi1p0_screening",
    "fine":     "/home/yyq/OpenFOAM/yyq-v2206/run/S10_phi1p0_screening_m384x36x36",
}
targets = [0.00040000, 0.00050000, 0.00060000]
out_csv = "/home/yyq/OpenFOAM/yyq-v2206/run/meshRobustness_ESM2/tables/matched_times.csv"

def get_times(case):
    txt = subprocess.check_output(
        ["bash","-lc", f"source /usr/lib/openfoam/openfoam2206/etc/bashrc && foamListTimes -case {case} -noZero"],
        text=True
    )
    vals = []
    for s in txt.split():
        try:
            vals.append(float(s))
        except:
            pass
    return sorted(set(vals))

with open(out_csv, "w", newline="") as f:
    w = csv.writer(f)
    w.writerow(["case_key","case_dir","target_s","target_ms","actual_s","abs_err_s"])
    for key, case in cases.items():
        times = get_times(case)
        for t in targets:
            a = min(times, key=lambda x: abs(x - t))
            w.writerow([key, case, f"{t:.8f}", f"{t*1e3:.2f}", f"{a:.8f}", f"{abs(a-t):.8e}"])
            print(f"{key:8s}  target={t:.8f}  actual={a:.8f}  err={abs(a-t):.3e}")
