///|
priv enum Side {
  Top
  Bottom
} derive(Eq)

///|
/// A point in millimetres, shared by the audit pipeline and the registration
/// engine.
pub struct Point {
  x : Double
  y : Double
}

///|
priv struct Placement {
  refdes : String
  xy : Point
  angle_deg : Double
  side : Side
  value : String
  footprint : String
}

///|
pub struct PlacementTable {
  priv rows : Map[String, Placement]
}

///|
priv enum Column {
  Ref
  X
  Y
  Angle
  Layer
  Value
  Package
} derive(Eq, Hash)

///|
fn column(name : String) -> Column? {
  match name.trim().to_owned().to_lower() {
    "ref" | "designator" => Some(Ref)
    "posx" | "mid x" => Some(X)
    "posy" | "mid y" => Some(Y)
    "rot" | "rotation" => Some(Angle)
    "side" | "layer" => Some(Layer)
    "val" | "value" | "comment" => Some(Value)
    "package" | "footprint" | "pattern" => Some(Package)
    _ => None
  }
}

///|
fn placement_columns(
  row : CsvRow,
  source : String,
) -> Map[Column, Int32] raise InputError {
  let columns : Map[Column, Int32] = Map([])
  for index, name in row.fields {
    if column(name) is Some(kind) {
      if columns.contains(kind) {
        raise InvalidInput(
          source,
          "第 \{row.line} 行的关键列重复:\{name}",
        )
      }
      columns[kind] = index
    }
  }
  for required in [Ref, X, Y, Angle, Layer] {
    if !columns.contains(required) {
      raise InvalidInput(
        source, "表头必须包含位号、X、Y、角度和板面",
      )
    }
  }
  columns
}

///|
fn designator(text : String) -> String {
  text.trim().to_owned().to_upper()
}

///|
fn angle_wrap(angle : Double) -> Double {
  angle - 360.0 * @math.floor((angle + 180.0) / 360.0)
}

///|
fn read_number(
  raw : String,
  max_abs : Double,
  field : String,
  where_ : String,
) -> Double raise InputError {
  let value = @string.parse_double(raw.trim()) catch {
    _ => raise InvalidInput(where_, "\{field} 不是有效数字")
  }
  if value.is_nan() || value.is_inf() || value.abs() > max_abs {
    raise InvalidInput(where_, "\{field} 超出允许范围 ±\{max_abs}")
  }
  value
}

///|
fn read_side(raw : String, where_ : String) -> Side raise InputError {
  match raw.trim().to_owned().to_lower() {
    "top" | "front" | "f.cu" => Top
    "bottom" | "back" | "b.cu" => Bottom
    _ => raise InvalidInput(where_, "未知板面:\{raw}")
  }
}

///|
/// Read KiCad or JLC-style placement CSV. Coordinates and angles are as exported.
pub fn read_placements(
  input : String,
  source~ : String,
) -> PlacementTable raise InputError {
  let rows = parse_csv(input, source)
  if rows.length() < 2 {
    raise InvalidInput(source, "需要表头和至少一个器件")
  }
  let columns = placement_columns(rows[0], source)
  let placements : Map[String, Placement] = Map([])
  for i in 1.. row.fields[index].trim().to_owned()
      None => ""
    }
    let footprint = match columns.get(Package) {
      Some(index) => row.fields[index].trim().to_owned()
      None => ""
    }
    placements[refdes] = { refdes, xy, angle_deg, side, value, footprint, }
  }
  { rows: placements, }
}