#!/usr/bin/env bash
set -eo pipefail
source /opt/openfoam13/etc/bashrc
mkdir -p results constant/triSurface
cp input/Al_Rihla_2022.stl constant/triSurface/Al_Rihla_2022.stl
for app in blockMesh snappyHexMesh checkMesh foamToVTK; do
  command -v "$app" >/dev/null || { echo "Missing application: $app" >&2; exit 2; }
done
foamVersion | tee results/environment.txt
blockMesh > results/blockMesh.log 2>&1
snappyHexMesh > results/snappyHexMesh.log 2>&1
checkMesh 2>&1 | tee results/checkMesh.log
grep -q 'Mesh OK.' results/checkMesh.log || exit 3
checkMesh -allGeometry -allTopology > results/checkMesh_extended.log 2>&1 || true
foamToVTK -constant > results/foamToVTK.log 2>&1
if [ -d VTK ]; then mv VTK results/VTK; fi
cp -r constant/polyMesh results/polyMesh
python3 - <<'PY'
import json, re
from pathlib import Path
standard=Path('results/checkMesh.log').read_text(errors='replace')
extended=Path('results/checkMesh_extended.log').read_text(errors='replace')
snappy=Path('results/snappyHexMesh.log').read_text(errors='replace')
def grab(pattern, text, cast=float):
    m=re.search(pattern,text)
    return cast(m.group(1)) if m else None
summary={
 "mesh_ok": "Mesh OK." in standard,
 "cells": grab(r"cells:\s+(\d+)", standard, int),
 "points": grab(r"points:\s+(\d+)", standard, int),
 "faces": grab(r"faces:\s+(\d+)", standard, int),
 "max_aspect_ratio": grab(r"Max aspect ratio =\s*([0-9.eE+-]+)", standard),
 "max_non_orthogonality_deg": grab(r"Mesh non-orthogonality Max:\s*([0-9.eE+-]+)", standard),
 "max_skewness": grab(r"Max skewness =\s*([0-9.eE+-]+)", standard),
 "extended_failed_checks": grab(r"Failed\s+(\d+)\s+mesh checks", extended, int),
 "prism_layers_requested": 0,
 "notes": "Layer-free intermediate mesh with nested level-2/level-3 wake refinement."
}
Path('results/mesh_summary.json').write_text(json.dumps(summary,indent=2))
print(json.dumps(summary,indent=2))
PY
