#!/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_center"), exist_ok=True)
os.makedirs(os.path.join(out_root, "contour_span"), 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.00062000 + 1e-12])

# ---- PlotOverLine, ParaView-version-compatible ----
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 z = 0.010 ----
sl_center = Slice(Input=reader)
sl_center.SliceType = 'Plane'
sl_center.SliceType.Origin = [0.06, 0.01, 0.01]
sl_center.SliceType.Normal = [0, 0, 1]

c2p_center = CellDatatoPointData(Input=sl_center)

ct_center = Contour(Input=c2p_center)
ct_center.ContourBy = ['POINTS', 'T']
ct_center.Isosurfaces = [1200.0]

# ---- spanwise contours at t = 0.62000 ----
span_z = [0.003, 0.010, 0.017]

manifest = []

for t in times:
    UpdatePipeline(time=t, proxy=reader)
    UpdatePipeline(time=t, proxy=line)
    UpdatePipeline(time=t, proxy=sl_center)
    UpdatePipeline(time=t, proxy=c2p_center)
    UpdatePipeline(time=t, proxy=ct_center)

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

    SaveData(cl, proxy=line)
    SaveData(cc, proxy=ct_center)
    manifest.append([f"{t:.8f}", cl, cc])

# export spanwise contours only at 0.62000
tspan = 0.00062000
for z in span_z:
    sl = Slice(Input=reader)
    sl.SliceType = 'Plane'
    sl.SliceType.Origin = [0.06, 0.01, z]
    sl.SliceType.Normal = [0, 0, 1]

    c2p = CellDatatoPointData(Input=sl)

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

    UpdatePipeline(time=tspan, proxy=reader)
    UpdatePipeline(time=tspan, proxy=sl)
    UpdatePipeline(time=tspan, proxy=c2p)
    UpdatePipeline(time=tspan, proxy=ct)

    zs = f"{z:.3f}"
    out_csv = os.path.join(out_root, "contour_span", f"T1200_z{zs}_t0.00062000.csv")
    SaveData(out_csv, proxy=ct)

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

print(f"exported overlay inputs for {case_name}")
