///|
#derive(Eq, @debug.Debug)
pub(all) suberror NestError {
  PlacementFailed(String)
  JsonError(String)
}

///|
/// Optional decimal precision. `None` uses three fractional digits.
#derive(Eq, @debug.Debug)
pub(all) struct Precision {
  digits : Int32?
}

///|
/// Rotation stride in degrees. Zero means every five degrees.
#derive(Eq, @debug.Debug)
pub(all) struct RotationPolicy {
  step_degrees : Int32
}

///|
/// Whether an instance was supplied or generated by the search.
#derive(Eq, @debug.Debug)
pub(all) enum PlacementOrigin {
  Fixed
  Searched
}

///|
/// Maps one placed instance to its output contours.
#derive(Eq, @debug.Debug)
pub(all) struct Placement {
  instance_id : Int32
  sheet : Int32
  part : Int32
  contour_index : Int32
  rotation_degrees : Int32
  mirrored : Bool
  source_x : Double
  source_y : Double
  origin : PlacementOrigin
}

///|
/// A fixed instance translation in normalized part coordinates.
#derive(Eq, @debug.Debug)
pub(all) struct FixedPlacement {
  part : Int32
  sheet : Int32
  rotation_degrees : Int32
  mirrored : Bool
  translation_x : Int64
  translation_y : Int64
}

///|
/// Material that is already unavailable on a sheet.
#derive(Eq, @debug.Debug)
pub(all) struct PreoccupiedRegion {
  sheet : Int32
  contours : @moonclip.Paths64
}

///|
/// A sheet stock specification and inventory quantity.
#derive(Eq, @debug.Debug)
pub(all) struct SheetSpec {
  id : String
  stock : Stock
  quantity : Int32
  cost : Double
}

///|
/// A stable instance record independent of output contour numbering.
#derive(Eq, @debug.Debug)
pub(all) struct Instance {
  instance_id : Int32
  part : Int32
  part_instance_index : Int32
  sheet : Int32
  rotation_degrees : Int32
  mirrored : Bool
  translation_x : Int64
  translation_y : Int64
  source_anchor_x : Int64
  source_anchor_y : Int64
  final_anchor_x : Int64
  final_anchor_y : Int64
  contour_indices : Array[Int32]
  hole_indices : Array[Int32]
  origin : PlacementOrigin
}

///|
/// Why a requested instance could not be placed.
#derive(Eq, @debug.Debug)
pub(all) enum UnplacedReason {
  TooLarge
  NoAllowedRotation
  NoAllowedSheet
  FixedConflict
  BudgetExhausted
  InvalidGeometry
  Occupied
}

///|
/// A structured unplaced instance entry.
#derive(Eq, @debug.Debug)
pub(all) struct UnplacedInstance {
  part : Int32
  part_instance_index : Int32
  reason : UnplacedReason
}

///|
/// Aggregate material quantity for one part type.
#derive(Eq, @debug.Debug)
pub(all) struct PartTotal {
  part : Int32
  count : Int32
  area2 : Int64
}

///|
/// Material and utilization report for a complete layout.
#derive(Eq, @debug.Debug)
pub(all) struct MaterialReport {
  width : Double
  height : Double
  hole_area2 : Int64
  gap_area2 : Int64
  unused_area2 : Int64
  part_totals : Array[PartTotal]
}

///|
pub fn MaterialReport::default() -> MaterialReport {
  {
    width: 0.0,
    height: 0.0,
    hole_area2: 0L,
    gap_area2: 0L,
    unused_area2: 0L,
    part_totals: [],
  }
}

///|
/// Deterministic compaction statistics.
#derive(Eq, @debug.Debug)
pub(all) struct CompressionReport {
  before_width : Double
  before_height : Double
  after_width : Double
  after_height : Double
  iterations : Int32
}

///|
pub fn CompressionReport::default() -> CompressionReport {
  {
    before_width: 0.0,
    before_height: 0.0,
    after_width: 0.0,
    after_height: 0.0,
    iterations: 0,
  }
}

///|
/// Per-sheet layout summary and unused material.
#derive(Eq, @debug.Debug)
pub(all) struct SheetLayout {
  sheet : Int32
  sheet_id : String
  instance_ids : Array[Int32]
  contour_indices : Array[Int32]
  width : Double
  height : Double
  material_area2 : Int64
  used_area2 : Int64
  hole_area2 : Int64
  gap_area2 : Int64
  unused_area2 : Int64
  utilization : Double
  unused : @moonclip.Paths64
}

///|
/// Corner strategy used when expanding material for clearance.
#derive(Eq, @debug.Debug)
pub(all) enum GapJoin {
  Round
  Bevel
  Miter
  Square
}

///|
/// Independent sheet edge margins in input units.
#derive(Eq, @debug.Debug)
pub(all) struct SheetMargin {
  top : Double
  right : Double
  bottom : Double
  left : Double
}

///|
/// A symmetric clearance override between two part types.
#derive(Eq, @debug.Debug)
pub(all) struct PairGap {
  first : Int32
  second : Int32
  gap : Double
}

///|
/// Semantic role of a sheet quality region.
#derive(Eq, @debug.Debug)
pub(all) enum QualityKind {
  Forbidden
  PartRestricted
  HighValue
  Defect
}

///|
/// A sheet region that participates in feasibility or scoring.
#derive(Eq, @debug.Debug)
pub(all) struct QualityRegion {
  sheet : Int32
  kind : QualityKind
  contours : @moonclip.Paths64
  parts : Array[Int32]
  weight : Double
}

///|
/// Part ordering used by a deterministic search strategy.
#derive(Eq, @debug.Debug)
pub(all) enum PartOrder {
  Area
  LongestSide
  Perimeter
  BoundsArea
}

///|
/// Gravity direction used for candidate scoring and compaction.
#derive(Eq, @debug.Debug)
pub(all) enum Gravity {
  LeftBottom
  RightBottom
  LeftTop
  RightTop
}

///|
/// Candidate scoring formula.
#derive(Eq, @debug.Debug)
pub(all) enum CandidateScoring {
  Distance
  BoundsArea
  Utilization
  FutureSpace
  Composite
}

///|
/// One deterministic search strategy.
#derive(Eq, @debug.Debug)
pub(all) struct SearchStrategy {
  order : PartOrder
  gravity : Gravity
  scoring : CandidateScoring
}

///|
pub fn SearchStrategy::default() -> SearchStrategy {
  {
    order: PartOrder::Area,
    gravity: Gravity::LeftBottom,
    scoring: CandidateScoring::Distance,
  }
}

///|
/// A nested suite: inner parts may occupy holes in the outer part.
#derive(Eq, @debug.Debug)
pub(all) struct SuiteSpec {
  id : String
  outer : Int32
  inner : Array[Int32]
}

///|
/// Resolved suite hierarchy in a layout.
#derive(Eq, @debug.Debug)
pub(all) struct SuiteLayout {
  suite_id : String
  outer_instance : Int32
  inner_instances : Array[Int32]
}

///|
/// Explicit search limits. Zero disables the corresponding limit; beam width
/// defaults to one.
#derive(Eq, @debug.Debug)
pub(all) struct SearchBudget {
  max_nodes : Int32
  max_backtracks : Int32
  beam_width : Int32
  workers : Int32
  max_milliseconds : Int64
  max_candidates : Int32
}

///|
pub fn SearchBudget::default() -> SearchBudget {
  {
    max_nodes: 0,
    max_backtracks: 0,
    beam_width: 1,
    workers: 1,
    max_milliseconds: 0L,
    max_candidates: 0,
  }
}

///|
/// Summary of one strategy run on one sheet.
#derive(Eq, @debug.Debug)
pub(all) struct StrategySummary {
  sheet : Int32
  strategy_index : Int32
  placed : Int32
  unplaced : Int32
  area2 : Int64
  width : Double
  height : Double
  quality_cost : Int64
}

///|
/// Optional per-part rules. Defaults inherit the problem-wide policy.
#derive(Eq, @debug.Debug)
pub(all) struct PartRules {
  rotations : Array[Int32]?
  mirror : Bool
  priority : Int32
  sheets : Array[Int32]?
  min_quantity : Int32
  group : String?
  label : String?
  metadata : Array[(String, String)]
  grain_degrees : Int32?
  grain_tolerance_degrees : Int32
  rotation_setup_cost : Double
  edge_clearance : Double
}

///|
pub fn PartRules::default() -> PartRules {
  {
    rotations: None,
    mirror: false,
    priority: 0,
    sheets: None,
    min_quantity: 0,
    group: None,
    label: None,
    metadata: [],
    grain_degrees: None,
    grain_tolerance_degrees: 0,
    rotation_setup_cost: 0.0,
    edge_clearance: 0.0,
  }
}

///|
/// A part definition. Contours are filled islands and holes are excluded.
#derive(Eq, @debug.Debug)
pub(all) struct Part {
  id : String
  quantity : Int32
  contours : Array[@moonclip.Path64]
  holes : Array[@moonclip.Path64]
  gap : Double?
  rules : PartRules
}

///|
/// Sheet outline and unavailable holes.
#derive(Eq, @debug.Debug)
pub(all) struct Stock {
  contour : @moonclip.Path64
  holes : Array[@moonclip.Path64]
}

///|
/// Machine envelope used to validate stock dimensions before nesting.
#derive(Eq, @debug.Debug)
pub(all) struct MachineSpec {
  id : String
  max_width : Double
  max_height : Double
}

///|
/// Weighted cutting-path objective and machine clearance parameters.
#derive(Eq, @debug.Debug)
pub(all) struct CuttingConfig {
  rapid_weight : Double
  cut_weight : Double
  pierce_weight : Double
  pierce_cost : Double
  safe_height : Double
  lead_in : Double
  lead_out : Double
}

///|
pub fn CuttingConfig::default() -> CuttingConfig {
  {
    rapid_weight: 1.0,
    cut_weight: 0.1,
    pierce_weight: 1.0,
    pierce_cost: 1.0,
    safe_height: 0.0,
    lead_in: 0.0,
    lead_out: 0.0,
  }
}

///|
/// A production machine available at a specific minute.
#derive(Eq, @debug.Debug)
pub(all) struct ProductionMachine {
  id : String
  available_minute : Int32
}

///|
/// One production order for a part type.
#derive(Eq, @debug.Debug)
pub(all) struct ProductionJob {
  id : String
  part : Int32
  quantity : Int32
  due_minute : Int32
  priority : Int32
  setup_group : String
  duration_minutes : Int32
  setup_minutes : Int32
}

///|
/// Deterministic due-date and setup-cost scheduling configuration.
#derive(Eq, @debug.Debug)
pub(all) struct ProductionConfig {
  machines : Array[ProductionMachine]
  jobs : Array[ProductionJob]
  due_weight : Double
  setup_weight : Double
}

///|
pub fn ProductionConfig::default() -> ProductionConfig {
  { machines: [], jobs: [], due_weight: 1.0, setup_weight: 1.0, }
}

///|
/// A complete nesting problem.
#derive(Eq, @debug.Debug)
pub(all) struct Problem {
  sheet : Stock
  sheets : Array[SheetSpec]?
  parts : Array[Part]
  gap : Double
  margin : Double
  sheet_margin : SheetMargin?
  pair_gaps : Array[PairGap]
  hole_clearance : Double
  join : GapJoin
  fixed : Array[FixedPlacement]
  preoccupied : Array[PreoccupiedRegion]
  quality_regions : Array[QualityRegion]
  strategies : Array[SearchStrategy]?
  budget : SearchBudget
  suites : Array[SuiteSpec]
  precision : Precision?
  rotations : RotationPolicy
  machine : MachineSpec?
  cutting : CuttingConfig?
  production : ProductionConfig?
}

///|
/// A complete layout. `area2` is twice the occupied material area in the
/// configured integer grid, including negative hole contours.
#derive(Eq, @debug.Debug)
pub(all) struct Layout {
  width : Double
  height : Double
  area2 : Int64
  quality_cost : Int64
  contours : Array[@moonclip.Path64]
  placements : Array[Placement]
  instances : Array[Instance]
  sheets : Array[SheetLayout]
  unplaced : Array[Int32]
  unplaced_details : Array[UnplacedInstance]
  report : MaterialReport
  compression : CompressionReport
  winning_strategy : Int32
  strategy_summaries : Array[StrategySummary]
  budget : SearchBudget
  nodes : Int32
  backtracks : Int32
  budget_exhausted : Bool
  suites : Array[SuiteLayout]
  iterations : Int32
  trials : Int32
  cache_hits : Int32
  precision : Precision
}

///|
/// Reversible coordinate transform for one placed instance. All anchors and
/// translations use the configured integer grid.
#derive(Eq, @debug.Debug)
pub(all) struct PlacementTransform {
  instance_id : Int32
  part : Int32
  rotation_degrees : Int32
  mirrored : Bool
  source_anchor_x : Int64
  source_anchor_y : Int64
  rotated_anchor_x : Int64
  rotated_anchor_y : Int64
  translation_x : Int64
  translation_y : Int64
  output_origin_x : Int64
  output_origin_y : Int64
  origin : PlacementOrigin
}

///|
/// A layout together with the coordinate transforms that produced it.
#derive(Eq, @debug.Debug)
pub(all) struct NestingResult {
  layout : Layout
  transforms : Array[PlacementTransform]
}

///|
/// A structured geometry validation finding.
#derive(Eq, @debug.Debug)
pub(all) enum GeometryIssue {
  CoordinateRange
  DuplicatePoint
  ZeroArea
  SelfIntersection
  HoleOutside
  HoleIntersection
  IslandOverlap
  QuantizedCollapse
}

///|
/// A geometry diagnostic tied to a source object and ring index.
#derive(Eq, @debug.Debug)
pub(all) struct GeometryDiagnostic {
  subject : String
  ring : String
  contour_index : Int32
  issue : GeometryIssue
  message : String
}

///|
/// Origin of a generated placement candidate.
#derive(Eq, @debug.Debug)
pub(all) enum CandidateSource {
  SheetCorner
  VertexContact
  NfpEdge
  HoleInterior
  FixedPoint
}

///|
/// Work counters for a nesting run.
#derive(@debug.Debug)
pub(all) struct Stats {
  mut iterations : Int32
  mut placements : Int32
  mut rejected : Int32
  mut nfps : Int32
  mut candidates : Int32
  mut nodes : Int32
  mut backtracks : Int32
  mut budget_exhausted : Bool
  mut elapsed_ms : Double
  mut cache_hits : Int32
  mut started_at : @bench.Timestamp
}

///|
#derive(Eq, @debug.Debug)
pub(all) enum Contact {
  Clear
  Touch
  Overlap
}

///|
/// A no-fit polygon for one ordered pair of part types and rotations.
#derive(Eq, @debug.Debug)
pub(all) struct NoFitPolygon {
  moving : Int32
  stationary : Int32
  moving_degrees : Int32
  stationary_degrees : Int32
  moving_mirrored : Bool
  stationary_mirrored : Bool
  contour : @moonclip.Path64
  precision : Precision
}

///|
/// A complete no-fit region. Positive contours are forbidden outer regions and
/// negative contours are holes where the moving part may fit without overlap.
/// `exact_contours` preserves the pre-display-quantization floating-point
/// boundary for membership tests and JSON output.
#derive(Eq, @debug.Debug)
pub(all) struct NoFitRegion {
  moving : Int32
  stationary : Int32
  moving_degrees : Int32
  stationary_degrees : Int32
  moving_mirrored : Bool
  stationary_mirrored : Bool
  contours : @moonclip.Paths64
  exact_contours : Array[Array[(Double, Double)]]
  precision : Precision
}