///|
/// Opt-in structural FEA intent: FDM-aware material properties, boundary
/// regions, constraints, and loads.
///
/// MoonBit authors immutable structural intent and serializes it to
/// `fea/load-cases.json`. Meshing and solving happen outside the package in
/// `scripts/fea_check.py` (Gmsh + CalculiX), keeping the CAD kernel-free.

///|
/// Orthotropic-homogenized elastic and strength data for a printed or
/// metallic material. Stresses are in MPa, density in kg/m³, and lengths in
/// millimeters (matching `printable/.step`).
pub(all) struct MaterialProperties {
  /// In-plane Young's modulus (MPa).
  e_mpa : Double
  /// In-plane Poisson's ratio.
  nu : Double
  /// In-plane tensile/compressive yield strength (MPa).
  yield_xy_mpa : Double
  /// Interlayer (print Z) tensile strength (MPa). Equals `yield_xy_mpa` for
  /// isotropic metals.
  interlayer_z_mpa : Double
  /// Bulk density (kg/m³).
  density_kg_m3 : Double
}

///|
/// Builds a property set explicitly; prefer the `pla`/`petg`/`pa_cf`/`aluminum_6061`/`steel_mild` presets.
pub fn MaterialProperties::new(
  e_mpa~ : Double,
  nu~ : Double,
  yield_xy_mpa~ : Double,
  interlayer_z_mpa~ : Double,
  density_kg_m3~ : Double,
) -> MaterialProperties {
  { e_mpa, nu, yield_xy_mpa, interlayer_z_mpa, density_kg_m3, }
}

///|
/// Generic PLA.
pub fn MaterialProperties::pla() -> MaterialProperties {
  {
    e_mpa: 3200.0,
    nu: 0.36,
    yield_xy_mpa: 50.0,
    interlayer_z_mpa: 18.0,
    density_kg_m3: 1240.0,
  }
}

///|
/// PETG.
pub fn MaterialProperties::petg() -> MaterialProperties {
  {
    e_mpa: 2100.0,
    nu: 0.38,
    yield_xy_mpa: 45.0,
    interlayer_z_mpa: 16.0,
    density_kg_m3: 1270.0,
  }
}

///|
/// Carbon-fiber-filled nylon (PA-CF), the default high-torque printed part.
pub fn MaterialProperties::pa_cf() -> MaterialProperties {
  {
    e_mpa: 5500.0,
    nu: 0.35,
    yield_xy_mpa: 70.0,
    interlayer_z_mpa: 24.0,
    density_kg_m3: 1180.0,
  }
}

///|
/// 6061-T6 aluminum (isotropic).
pub fn MaterialProperties::aluminum_6061() -> MaterialProperties {
  {
    e_mpa: 68900.0,
    nu: 0.33,
    yield_xy_mpa: 276.0,
    interlayer_z_mpa: 276.0,
    density_kg_m3: 2700.0,
  }
}

///|
/// Mild steel (isotropic).
pub fn MaterialProperties::steel_mild() -> MaterialProperties {
  {
    e_mpa: 205000.0,
    nu: 0.29,
    yield_xy_mpa: 250.0,
    interlayer_z_mpa: 250.0,
    density_kg_m3: 7850.0,
  }
}

///|
/// Resolves a printable material name (case-insensitive substring match) to
/// its property set. Unknown names fall back to PLA.
pub fn MaterialProperties::from_name(name : String) -> MaterialProperties {
  let lower = name.to_lower()
  if lower.contains("carbon fiber nylon") ||
    lower.contains("pa-cf") ||
    lower.contains("pa_cf") {
    MaterialProperties::pa_cf()
  } else if lower.contains("petg") {
    MaterialProperties::petg()
  } else if lower.contains("aluminum") || lower.contains("aluminium") {
    MaterialProperties::aluminum_6061()
  } else if lower.contains("steel") {
    MaterialProperties::steel_mild()
  } else {
    MaterialProperties::pla()
  }
}

///|
/// A named subset of the mesh, in the print-bed coordinate frame of
/// `printable/.step` (millimeters).
pub(all) enum BoundaryRegion {
  /// Mesh nodes on a cylindrical bore at `radius_mm` from the line through
  /// `center_mm` along `axis`, between the axial bounds `z_min_mm` and
  /// `z_max_mm`. `tol_mm` is the radial band half-width.
  CylinderBore(
    center_mm~ : (Double, Double, Double),
    axis~ : (Double, Double, Double),
    radius_mm~ : Double,
    z_min_mm~ : Double,
    z_max_mm~ : Double,
    tol_mm~ : Double,
  )
  /// Mesh nodes on a plane `dot(p, axis) = offset_mm`, within `tol_mm`.
  PlaneFace(
    axis~ : (Double, Double, Double),
    offset_mm~ : Double,
    tol_mm~ : Double,
  )
  /// Mesh nodes inside an axis-aligned box.
  BoxRegion(
    min_mm~ : (Double, Double, Double),
    max_mm~ : (Double, Double, Double),
  )
  /// Mesh nodes on `count` equal-sized holes (diameter `hole_diam_mm`) on a
  /// bolt circle `bcd_mm` in diameter about `center_mm`, first hole at
  /// `start_angle_deg`, limited to the print-frame Z bounds.
  BoltCircle(
    center_mm~ : (Double, Double, Double),
    bcd_mm~ : Double,
    hole_diam_mm~ : Double,
    count~ : Int32,
    start_angle_deg~ : Double,
    z_min_mm~ : Double,
    z_max_mm~ : Double,
    tol_mm~ : Double,
  )
}

///|
/// A structural load applied to a boundary region.
pub(all) enum FeaLoad {
  /// Total force in newtons, distributed evenly across the selected nodes.
  Force(region~ : BoundaryRegion, force_n~ : (Double, Double, Double))
  /// Pure couple in N·m about `axis` through `origin_mm`.
  Torque(
    region~ : BoundaryRegion,
    origin_mm~ : (Double, Double, Double),
    axis~ : (Double, Double, Double),
    torque_nm~ : Double,
  )
  /// Surface pressure in MPa acting inward along the region normal.
  Pressure(region~ : BoundaryRegion, pressure_mpa~ : Double)
}

///|
/// One linear-elastic static load case: material, fixed regions, loads, and
/// meshing/acceptance settings.
pub(all) struct FeaLoadCase {
  /// Load-case name, unique within the exported `load-cases.json`.
  name : String
  /// Part number the case applies to; matches the printable part's part number.
  part_number : String
  /// Homogenized material properties used for the solve.
  material : MaterialProperties
  /// Fixed (constrained) mesh regions; the solver removes these DOFs.
  constraints : Array[BoundaryRegion]
  /// Applied loads; at least one is required for a meaningful solve.
  loads : Array[FeaLoad]
  /// Target element edge length for meshing, in millimeters.
  mesh_size_mm : Double
  /// Print build direction as a unit vector; selects which strength to use for Z-critical criteria.
  print_z_axis : (Double, Double, Double)
  /// Minimum factor of safety the solver requires above the material's failure strength.
  safety_factor_target : Double
}

///|
/// Creates a load case with PLA, a 3 mm mesh, a +Z print axis, and a safety
/// factor target of 2.0.
pub fn FeaLoadCase::new(name : String, part_number~ : String) -> FeaLoadCase {
  {
    name,
    part_number,
    material: MaterialProperties::pla(),
    constraints: [],
    loads: [],
    mesh_size_mm: 3.0,
    print_z_axis: (0.0, 0.0, 1.0),
    safety_factor_target: 2.0,
  }
}

///|
/// Returns a copy of this load case with `material` replaced.
pub fn FeaLoadCase::with_material(
  self : FeaLoadCase,
  material : MaterialProperties,
) -> FeaLoadCase {
  { ..self, material, }
}

///|
/// Returns a copy with `region` appended to the fixed-constraint set.
pub fn FeaLoadCase::with_fixed(
  self : FeaLoadCase,
  region : BoundaryRegion,
) -> FeaLoadCase {
  let constraints = self.constraints.copy()
  constraints.push(region)
  { ..self, constraints, }
}

///|
/// Returns a copy with a concentrated force added, in newtons, distributed over `region`.
pub fn FeaLoadCase::with_force(
  self : FeaLoadCase,
  region : BoundaryRegion,
  force_n : (Double, Double, Double),
) -> FeaLoadCase {
  self.add_load(FeaLoad::Force(region~, force_n~))
}

///|
/// Returns a copy with a concentrated torque added, in N·m about `axis` through `origin_mm`.
pub fn FeaLoadCase::with_torque(
  self : FeaLoadCase,
  region : BoundaryRegion,
  origin_mm~ : (Double, Double, Double),
  axis~ : (Double, Double, Double),
  torque_nm~ : Double,
) -> FeaLoadCase {
  self.add_load(FeaLoad::Torque(region~, origin_mm~, axis~, torque_nm~))
}

///|
/// Returns a copy with an inward surface pressure added, in MPa, over `region`.
pub fn FeaLoadCase::with_pressure(
  self : FeaLoadCase,
  region : BoundaryRegion,
  pressure_mpa : Double,
) -> FeaLoadCase {
  self.add_load(FeaLoad::Pressure(region~, pressure_mpa~))
}

///|
fn FeaLoadCase::add_load(self : FeaLoadCase, load : FeaLoad) -> FeaLoadCase {
  let loads = self.loads.copy()
  loads.push(load)
  { ..self, loads, }
}

///|
/// Returns a copy with the target mesh element size set to `mesh_size_mm` (millimeters).
pub fn FeaLoadCase::with_mesh_size_mm(
  self : FeaLoadCase,
  mesh_size_mm : Double,
) -> FeaLoadCase {
  { ..self, mesh_size_mm, }
}

///|
/// Returns a copy with the print build direction set; used to evaluate interlayer (Z) strength.
pub fn FeaLoadCase::with_print_z_axis(
  self : FeaLoadCase,
  print_z_axis : (Double, Double, Double),
) -> FeaLoadCase {
  { ..self, print_z_axis, }
}

///|
/// Returns a copy with the required factor of safety changed; must be > 0 to be meaningful.
pub fn FeaLoadCase::with_safety_factor_target(
  self : FeaLoadCase,
  safety_factor_target : Double,
) -> FeaLoadCase {
  { ..self, safety_factor_target, }
}

///|
fn fea_material_json(material : MaterialProperties) -> @json.Json {
  inspect_object([
    ("e_mpa", @json.Json::number(material.e_mpa)),
    ("nu", @json.Json::number(material.nu)),
    ("yield_xy_mpa", @json.Json::number(material.yield_xy_mpa)),
    ("interlayer_z_mpa", @json.Json::number(material.interlayer_z_mpa)),
    ("density_kg_m3", @json.Json::number(material.density_kg_m3)),
  ])
}

///|
fn fea_region_json(region : BoundaryRegion) -> @json.Json {
  match region {
    CylinderBore(center_mm~, axis~, radius_mm~, z_min_mm~, z_max_mm~, tol_mm~) =>
      inspect_object([
        ("kind", @json.Json::string("cylinder_bore")),
        ("center_mm", inspect_vec3(center_mm)),
        ("axis", inspect_vec3(axis)),
        ("radius_mm", @json.Json::number(radius_mm)),
        ("z_min_mm", @json.Json::number(z_min_mm)),
        ("z_max_mm", @json.Json::number(z_max_mm)),
        ("tol_mm", @json.Json::number(tol_mm)),
      ])
    PlaneFace(axis~, offset_mm~, tol_mm~) =>
      inspect_object([
        ("kind", @json.Json::string("plane_face")),
        ("axis", inspect_vec3(axis)),
        ("offset_mm", @json.Json::number(offset_mm)),
        ("tol_mm", @json.Json::number(tol_mm)),
      ])
    BoxRegion(min_mm~, max_mm~) =>
      inspect_object([
        ("kind", @json.Json::string("box_region")),
        ("min_mm", inspect_vec3(min_mm)),
        ("max_mm", inspect_vec3(max_mm)),
      ])
    BoltCircle(
      center_mm~,
      bcd_mm~,
      hole_diam_mm~,
      count~,
      start_angle_deg~,
      z_min_mm~,
      z_max_mm~,
      tol_mm~,
    ) =>
      inspect_object([
        ("kind", @json.Json::string("bolt_circle")),
        ("center_mm", inspect_vec3(center_mm)),
        ("bcd_mm", @json.Json::number(bcd_mm)),
        ("hole_diam_mm", @json.Json::number(hole_diam_mm)),
        ("count", @json.Json::number(count.to_double())),
        ("start_angle_deg", @json.Json::number(start_angle_deg)),
        ("z_min_mm", @json.Json::number(z_min_mm)),
        ("z_max_mm", @json.Json::number(z_max_mm)),
        ("tol_mm", @json.Json::number(tol_mm)),
      ])
  }
}

///|
fn fea_load_json(load : FeaLoad) -> @json.Json {
  match load {
    Force(region~, force_n~) =>
      inspect_object([
        ("kind", @json.Json::string("force")),
        ("region", fea_region_json(region)),
        ("force_n", inspect_vec3(force_n)),
      ])
    Torque(region~, origin_mm~, axis~, torque_nm~) =>
      inspect_object([
        ("kind", @json.Json::string("torque")),
        ("region", fea_region_json(region)),
        ("origin_mm", inspect_vec3(origin_mm)),
        ("axis", inspect_vec3(axis)),
        ("torque_nm", @json.Json::number(torque_nm)),
      ])
    Pressure(region~, pressure_mpa~) =>
      inspect_object([
        ("kind", @json.Json::string("pressure")),
        ("region", fea_region_json(region)),
        ("pressure_mpa", @json.Json::number(pressure_mpa)),
      ])
  }
}

///|
fn fea_load_case_json(load_case : FeaLoadCase) -> @json.Json {
  inspect_object([
    ("name", @json.Json::string(load_case.name)),
    ("part_number", @json.Json::string(load_case.part_number)),
    ("material", fea_material_json(load_case.material)),
    ("mesh_size_mm", @json.Json::number(load_case.mesh_size_mm)),
    ("print_z_axis", inspect_vec3(load_case.print_z_axis)),
    ("safety_factor_target", @json.Json::number(load_case.safety_factor_target)),
    (
      "fixed",
      @json.Json::array(
        load_case.constraints.map(fn(region) { fea_region_json(region) }),
      ),
    ),
    (
      "loads",
      @json.Json::array(load_case.loads.map(fn(load) { fea_load_json(load) })),
    ),
  ])
}

///|
/// One load case as a standalone JSON object.
pub fn FeaLoadCase::to_json(self : FeaLoadCase) -> String {
  fea_load_case_json(self).stringify()
}

///|
/// The complete `fea/load-cases.json` document: a schema tag and an ordered
/// array of load cases.
pub fn fea_load_cases_to_json(cases : Array[FeaLoadCase]) -> String {
  inspect_object([
    ("schema", @json.Json::string("gmlewis/cad/fea-load-cases@1")),
    (
      "load_cases",
      @json.Json::array(
        cases.map(fn(load_case) { fea_load_case_json(load_case) }),
      ),
    ),
  ]).stringify()
}