///|
/// A dark, flashed pad extracted from a Gerber layer.
pub struct CopperPad {
  refdes : String?
  shape : Shape
  center : Point
  area : Double
}

///|
/// Extract the flashed dark pads from a parsed layer.
pub fn gerber_pads(document : GerberDocument) -> Array[CopperPad] {
  let pads : Array[CopperPad] = []
  for feature in document.features {
    if feature.dark {
      match feature.kind {
        Flash(shape, center) =>
          pads.push({
            refdes: feature.refdes,
            shape,
            center,
            area: shape.area(),
          })
        _ => ()
      }
    }
  }
  pads
}

///|
/// Group pads by their X2 component reference.
pub fn pad_groups(pads : Array[CopperPad]) -> Map[String, Array[CopperPad]] {
  let groups : Map[String, Array[CopperPad]] = Map([])
  for pad in pads {
    match pad.refdes {
      Some(reference) => {
        let key = designator(reference)
        match groups.get(key) {
          Some(group) => group.push(pad)
          None => groups[key] = [pad]
        }
      }
      None => ()
    }
  }
  groups
}

///|
/// Area-weighted centre of a pad group. This is a geometric reference, which
/// may differ from the placement origin of an asymmetric footprint.
pub fn copper_centroid(pads : Array[CopperPad]) -> Point {
  let mut total = 0.0
  let mut x = 0.0
  let mut y = 0.0
  for pad in pads {
    total += pad.area
    x += pad.center.x * pad.area
    y += pad.center.y * pad.area
  }
  if total == 0.0 {
    return { x: 0.0, y: 0.0, }
  }
  { x: x / total, y: y / total, }
}

///|
fn gerber_object_bounds(kind : GerberKind) -> GerberBounds? {
  match kind {
    Flash(shape, center) => Some(bounds_at(center, shape.bounding_radius()))
    Draw(shape, start, end) => {
      let radius = shape.bounding_radius()
      Some(bounds_at(start, radius).union(bounds_at(end, radius)))
    }
    Arc(arc) => Some(arc.bounds())
    Region(region) => Some(region.bounds)
  }
}

///|
fn in_flash_hole(kind : GerberKind, point : Point, margin : Double) -> Bool {
  guard kind is Flash(shape, center) else { return false }
  shape.hole_contains(difference(point, center), margin)
}

///|
fn clear_may_cover(kind : GerberKind, point : Point, margin : Double) -> Bool {
  match kind {
    Arc(arc) => arc.may_cover(point, margin)
    Draw(shape, from, to) =>
      shape.bounding_radius() > 0.0 &&
      segment_distance(point, from, to) <= shape.bounding_radius() + margin
    Region(region) => region.may_cover(point, margin)
    _ => !in_flash_hole(kind, point, margin)
  }
}

///|
priv struct ClearanceWitness {
  pad_index : Int32
  pad_statement : Int32
  pin : String?
  pad_center : Point
  clear_index : Int32
  clear_statement : Int32
  clear_kind : String
  clear_bounds : GerberBounds
}

///|
fn gerber_kind_name(kind : GerberKind) -> String {
  match kind {
    Flash(_, _) => "flash"
    Draw(_, _, _) => "line"
    Arc(_) => "arc"
    Region(_) => "region"
  }
}

///|
/// Only a clear object painted after a flash can invalidate that flash.
/// Bounds can rule out an overlap without claiming to compute clipped area.
fn refs_with_possible_clearance(
  document : GerberDocument,
) -> Map[String, ClearanceWitness] {
  let affected : Map[String, ClearanceWitness] = Map([])
  let items : Array[ClearObject] = []
  for index, feature in document.features {
    if !feature.dark && gerber_object_bounds(feature.kind) is Some(bounds) {
      items.push({ index, feature, bounds, })
    }
  }
  if items.is_empty() {
    return affected
  }
  let tree = clearance_index(items)
  let count = document.features.length()
  for i in 0.. Bool {
  let mut covered = false
  let search = bounds_at(point, tolerance)
  for feature in document.features {
    if !feature.dark {
      if gerber_object_bounds(feature.kind) is Some(bounds) &&
        bounds.overlaps(search) &&
        clear_may_cover(feature.kind, point, tolerance) {
        covered = false
      }
      continue
    }
    let contains = match feature.kind {
      Flash(shape, center) => shape.expanded(tolerance).contains(center, point)
      Region(region) => region.covers(point)
      Arc(arc) => arc.covers(point, tolerance)
      Draw(shape, from, to) =>
        shape.bounding_radius() > 0.0 &&
        segment_distance(point, from, to) <= shape.bounding_radius() + tolerance
    }
    if contains {
      covered = true
    }
  }
  covered
}

///|
priv enum PadEvidence {
  ByReference(Int32, Point, Double)
  CopperOnly
  Unverified
  PossibleClearance(ClearanceWitness)
  RepeatedReference
}

///|
fn pad_evidence(
  document : GerberDocument,
  refdes : Array[String],
  positions : Array[Point],
  tolerance_mm : Double,
) -> Array[PadEvidence] {
  let count = positions.length().min(refdes.length())
  let groups = pad_groups(gerber_pads(document))
  let affected = refs_with_possible_clearance(document)
  let evidence = []
  for i in 0.. pad.area > 0.0) => {
          let delta = difference(point, copper_centroid(group))
          ByReference(group.length(), delta, magnitude(delta))
        }
        _ =>
          if copper_at(document, point, tolerance_mm) {
            CopperOnly
          } else {
            Unverified
          }
      },
    )
  }
  evidence
}

///|
fn pad_finding(
  refdes : String,
  evidence : PadEvidence,
  tolerance : Double,
) -> Json? {
  match evidence {
    ByReference(_, delta, distance) if distance > tolerance =>
      Some({
        "ref": Json(refdes),
        "kind": Json("pad_offset"),
        "delta_x_mm": Json(delta.x),
        "delta_y_mm": Json(delta.y),
        "distance_mm": Json(distance),
      })
    _ => None
  }
}

///|
/// Return attributable pad-centre offsets beyond tolerance. The audit report
/// also exposes the evidence for coordinates whose ownership is unknown.
pub fn check_pads(
  document : GerberDocument,
  refdes : Array[String],
  positions : Array[Point],
  tolerance_mm : Double,
) -> Array[Json] {
  let items = pad_evidence(document, refdes, positions, tolerance_mm)
  let findings = []
  for i in 0..