#!/usr/bin/env pvpython
from paraview.simple import *
import os, sys, csv

case_dir = sys.argv[1]
out_root = sys.argv[2]

case_name = os.path.basename(case_dir)
foam = os.path.join(case_dir, case_name + ".foam")

os.makedirs(os.path.join(out_root, "centerline"), exist_ok=True)
os.makedirs(os.path.join(out_root, "contour"), exist_ok=True)

reader = OpenDataFile(foam)
try:
    reader.MeshRegions = ['internalMesh']
except:
    pass
try:
    reader.CellArrays = ['T','p','Qdot','kappa','U']
except:
    pass

scene = GetAnimationScene()
scene.UpdateAnimationUsingDataTimeSteps()

times = sorted([float(t) for t in reader.TimestepValues if float(t) <= 0.00060000 + 1e-12])

# ---- PlotOverLine: ParaView-version-compatible configuration ----
line = PlotOverLine(Input=reader)
configured = False

try:
    line.Point1 = [0.0, 0.01, 0.01]
    line.Point2 = [0.24, 0.01, 0.01]
    line.Resolution = 1200
    configured = True
except Exception:
    pass

if not configured:
    try:
        line.Source.Point1 = [0.0, 0.01, 0.01]
        line.Source.Point2 = [0.24, 0.01, 0.01]
        line.Source.Resolution = 1200
        configured = True
    except Exception:
        pass

if not configured:
    raise RuntimeError("Could not configure PlotOverLine for this ParaView version")

# ---- center-plane contour ----
sl = Slice(Input=reader)
sl.SliceType = 'Plane'
sl.SliceType.Origin = [0.06, 0.01, 0.01]
sl.SliceType.Normal = [0, 0, 1]

c2p = CellDatatoPointData(Input=sl)

ct = Contour(Input=c2p)
ct.ContourBy = ['POINTS', 'T']
ct.Isosurfaces = [1200.0]

manifest = []

for t in times:
    UpdatePipeline(time=t, proxy=reader)
    UpdatePipeline(time=t, proxy=line)
    UpdatePipeline(time=t, proxy=sl)
    UpdatePipeline(time=t, proxy=c2p)
    UpdatePipeline(time=t, proxy=ct)

    cl = os.path.join(out_root, "centerline", f"centerline_t{t:.8f}.csv")
    co = os.path.join(out_root, "contour", f"T1200_z010_t{t:.8f}.csv")

    SaveData(cl, proxy=line)
    SaveData(co, proxy=ct)

    manifest.append([f"{t:.8f}", cl, co])

with open(os.path.join(out_root, "manifest.csv"), "w", newline="") as f:
    w = csv.writer(f)
    w.writerow(["time_s", "centerline_csv", "contour_csv"])
    w.writerows(manifest)

print(f"exported {len(times)} times for {case_name}")
