#!/bin/bash
set -e
cd $(dirname "$0")

run_and_tail() {
  label="$1"
  log_file="$2"
  shift 2
  echo "Running $label."
  "$@" > "$log_file" 2>&1 || {
    code=$?
    echo "$label failed with exit code $code."
    if [ -f "$log_file" ]; then
      if grep -n -B 20 -A 100 -E "FOAM FATAL|segmentation fault|divide by zero|core dumped|--> FOAM" "$log_file"; then
        true
      else
        tail -n 160 "$log_file" || true
      fi
    fi
    if [ "$label" = "blockMesh" ] && [ -f system/blockMeshDict ]; then
      echo "--- blockMeshDict tail ---"
      tail -n 140 system/blockMeshDict || true
    fi
    exit "$code"
  }
}

apply_snappy_budget_profile() {
  profile="$1"
  region_level="1"
  surface_level="1"
  transition_cells="4"
  if [ "100000" -ge 100000 ]; then
    surface_level="2"
  fi
  if [ "$profile" = "minimum" ]; then
    region_level="0"
    surface_level="1"
    transition_cells="5"
  fi
  if [ "$profile" = "emergency" ]; then
    region_level="0"
    surface_level="1"
    transition_cells="6"
  fi

  if [ -f system/snappyHexMeshDict.primary ]; then
    cp system/snappyHexMeshDict.primary system/snappyHexMeshDict
  fi

  awk     -v regionLevel="$region_level"     -v surfaceLevel="$surface_level"     -v transitionCells="$transition_cells" '
      /^[[:space:]]*level[[:space:]]*\([0-9]+[[:space:]]+[0-9]+\);/ {
        indent = substr($0, 1, match($0, /[^[:space:]]/) - 1);
        print indent "level (" surfaceLevel " " surfaceLevel ");";
        next;
      }
      /^[[:space:]]*level[[:space:]]+[0-9]+;/ {
        indent = substr($0, 1, match($0, /[^[:space:]]/) - 1);
        print indent "level " surfaceLevel ";";
        next;
      }
      /^[[:space:]]*levels[[:space:]]*\(\(/ {
        indent = substr($0, 1, match($0, /[^[:space:]]/) - 1);
        print indent "levels ((1E15 " regionLevel "));";
        next;
      }
      /^[[:space:]]*nCellsBetweenLevels[[:space:]]+/ {
        indent = substr($0, 1, match($0, /[^[:space:]]/) - 1);
        print indent "nCellsBetweenLevels " transitionCells ";";
        next;
      }
      { print }
    ' system/snappyHexMeshDict > system/snappyHexMeshDict.tmp && mv system/snappyHexMeshDict.tmp system/snappyHexMeshDict
}

coarsen_block_mesh_for_budget() {
  current_cells="${1:-0}"
  profile="${2:-emergency}"
  scale=$(awk -v current="$current_cells" -v target="100000" -v profile="$profile" 'BEGIN {
    c = current + 0;
    t = target + 0;
    if (c <= 0 || t <= 0) {
      s = 0.70;
    } else {
      s = (t / c) ^ (1.0 / 3.0);
      if (profile == "emergency") s *= 0.68;
      else s *= 0.82;
    }
    if (s > 0.86) s = 0.86;
    if (s < 0.30) s = 0.30;
    printf "%.6f", s;
  }')
  echo "Coarsening blockMesh divisions with scale $scale to stay under strict cell budget."
  awk -v scale="$scale" '
    /hex[[:space:]]*\([0-9]+[[:space:]]+[0-9]+[[:space:]]+[0-9]+[[:space:]]+[0-9]+[[:space:]]+[0-9]+[[:space:]]+[0-9]+[[:space:]]+[0-9]+[[:space:]]+[0-9]+\)[[:space:]]*\([0-9]+[[:space:]]+[0-9]+[[:space:]]+[0-9]+\)/ {
      if (match($0, /\([0-9]+[[:space:]]+[0-9]+[[:space:]]+[0-9]+\)[[:space:]]*simpleGrading/)) {
        dims = substr($0, RSTART + 1, RLENGTH - length(") simpleGrading") - 1);
        split(dims, d, /[[:space:]]+/);
        nx = int(d[1] * scale); ny = int(d[2] * scale); nz = int(d[3] * scale);
        if (nx < 4) nx = 4; if (ny < 4) ny = 4; if (nz < 4) nz = 4;
        sub(/\([0-9]+[[:space:]]+[0-9]+[[:space:]]+[0-9]+\)[[:space:]]*simpleGrading/, "(" nx " " ny " " nz ") simpleGrading");
      }
    }
    { print }
  ' system/blockMeshDict > system/blockMeshDict.tmp && mv system/blockMeshDict.tmp system/blockMeshDict
}

rerun_snappy_with_profile() {
  profile="$1"
  echo "Mesh cells exceed strict target; retrying with $profile refinement profile."
  apply_snappy_budget_profile "$profile"
  if [ "$profile" = "emergency" ]; then
    coarsen_block_mesh_for_budget "${MESH_CELL_COUNT:-0}" "$profile"
  fi
  run_and_tail "blockMesh" "log.blockMesh" blockMesh
  run_and_tail "snappyHexMesh" "log.snappyHexMesh" snappyHexMesh -overwrite
  run_and_tail "checkMesh" "checkMesh.log" checkMesh
  MESH_CELL_COUNT=$(awk '/^[[:space:]]*cells:/ {print $2; exit}' checkMesh.log)
  echo "Mesh cells after $profile profile: ${MESH_CELL_COUNT:-unknown} / strict target 100000"
}

MESH_TYPE="${MESH_TYPE:-snappy}"
IS_CONTINUE="${IS_CONTINUE:-0}"

if [ "$IS_CONTINUE" = "1" ]; then
  echo "Continue mode: reusing existing mesh."
else
  if [ "$MESH_TYPE" = "block" ]; then
    run_and_tail "blockMesh" "log.blockMesh" blockMesh
  elif [ "$MESH_TYPE" = "snappy" ]; then
    echo "Running blockMesh and snappyHexMesh."
    run_and_tail "blockMesh" "log.blockMesh" blockMesh
    FEATURE_FILE="constant/triSurface/object.eMesh"
    rm -f "$FEATURE_FILE"
    if command -v surfaceFeatureExtract >/dev/null 2>&1; then
      echo "Running surfaceFeatureExtract."
      surfaceFeatureExtract > log.surfaceFeatureExtract 2>&1 || {
        echo "surfaceFeatureExtract failed; continuing with implicit feature snapping."
        tail -n 30 log.surfaceFeatureExtract
      }
    else
      echo "surfaceFeatureExtract command was not found; continuing with implicit feature snapping."
    fi
    if [ ! -s "$FEATURE_FILE" ] && [ -s "constant/extendedFeatureEdgeMesh/object.eMesh" ]; then
      cp "constant/extendedFeatureEdgeMesh/object.eMesh" "$FEATURE_FILE"
    fi
    if [ -s "$FEATURE_FILE" ]; then
      echo "Enabling explicit feature snapping with object.eMesh."
      awk -v f="object.eMesh" -v lvl="2" '
        /^[[:space:]]*features[[:space:]]*\(\);/ {
          print "    features";
          print "    (";
          print "        {";
          print "            file \"" f "\";";
          print "            level " lvl ";";
          print "        }";
          print "    );";
          next;
        }
        /^[[:space:]]*explicitFeatureSnap[[:space:]]+false;/ {
          print "    explicitFeatureSnap true;";
          next;
        }
        { print }
      ' system/snappyHexMeshDict > system/snappyHexMeshDict.tmp && mv system/snappyHexMeshDict.tmp system/snappyHexMeshDict
    else
      echo "Feature file object.eMesh was not created; using implicit feature snapping only."
    fi
    cp system/snappyHexMeshDict system/snappyHexMeshDict.primary
    run_and_tail "snappyHexMesh" "log.snappyHexMesh" snappyHexMesh -overwrite
  elif [ "$MESH_TYPE" = "external" ]; then
    echo "External mesh mode selected; add converter logic here if needed."
  else
    echo "Unknown mesh type: $MESH_TYPE"
    exit 1
  fi

  run_and_tail "checkMesh" "checkMesh.log" checkMesh
  MESH_CELL_COUNT=$(awk '/^[[:space:]]*cells:/ {print $2; exit}' checkMesh.log)
  echo "Mesh cells: ${MESH_CELL_COUNT:-unknown} / strict target 100000"
  if [ -n "$MESH_CELL_COUNT" ] && [ "$MESH_CELL_COUNT" -gt "100000" ]; then
    rerun_snappy_with_profile "compact"
  fi
  if [ -n "$MESH_CELL_COUNT" ] && [ "$MESH_CELL_COUNT" -gt "100000" ]; then
    rerun_snappy_with_profile "minimum"
  fi
  EMERGENCY_ATTEMPT=0
  while [ -n "$MESH_CELL_COUNT" ] && [ "$MESH_CELL_COUNT" -gt "100000" ] && [ "$EMERGENCY_ATTEMPT" -lt 5 ]; do
    EMERGENCY_ATTEMPT=$((EMERGENCY_ATTEMPT + 1))
    echo "Emergency mesh coarsening attempt $EMERGENCY_ATTEMPT."
    rerun_snappy_with_profile "emergency"
  done
  if [ -z "$MESH_CELL_COUNT" ]; then
    echo "Unable to read mesh cell count from checkMesh.log; continuing with the generated mesh instead of stopping."
  fi
  if [ -n "$MESH_CELL_COUNT" ] && [ "$MESH_CELL_COUNT" -gt "100000" ]; then
    echo "Warning: mesh cell count still exceeds strict target (100000) after emergency coarsening."
    echo "Continuing with the coarsest object-recognition mesh instead of stopping."
  fi
  postProcess -case . -func "writeCellCentres"
fi

postProcess -case . -func "writeCellCentres"

SOLVER_EXIT_CODE=0
if command -v foamRun >/dev/null 2>&1; then
  echo "Running foamRun -solver incompressibleFluid."
  foamRun -solver incompressibleFluid > log.simpleFoam 2>&1 || SOLVER_EXIT_CODE=$?
else
  echo "Running simpleFoam."
  simpleFoam > log.simpleFoam 2>&1 || SOLVER_EXIT_CODE=$?
fi

echo "Solver exit code: $SOLVER_EXIT_CODE"
if [ -n "$SOLVER_EXIT_CODE" ] && [ "$SOLVER_EXIT_CODE" -ne 0 ]; then
  echo "Solver failed."
  tail -n 50 log.simpleFoam
  exit 1
fi

postProcess -case . -func Q -latestTime > log.Q 2>&1 || echo "Q field generation skipped; see log.Q"
