///|
#derive(Eq, Debug)
pub(all) enum RowRuleOp {
  Less
  LessEqual
  Equal
}

///|
/// A comparison of two numeric fields on the same logical row.
#derive(Eq, Debug)
pub(all) struct RowRule {
  left : String
  op : RowRuleOp
  right : String
}

///|
fn RowRuleOp::symbol(self : RowRuleOp) -> String {
  match self {
    Less => "<"
    LessEqual => "<="
    Equal => "="
  }
}

///|
fn RowRule::json(self : RowRule) -> Json {
  { "left": self.left, "op": self.op.symbol(), "right": self.right }
}

///|
priv struct BoundRowRule {
  rule : RowRule
  left : Int32
  right : Int32
}

///|
fn parse_row_rules(
  schema : Json,
  resource : String,
  errors : Array[Diagnostic],
) -> Array[RowRule] {
  let key = "x-moonfriction-rowRules"
  guard schema is Object(properties) && properties.get(key) is Some(value) else {
    return []
  }
  guard value is Array(entries) else {
    errors.push(
      issue("row-rule-schema", resource, 0, "", key + " must be an array"),
    )
    return []
  }
  let rules = []
  for index, entry in entries {
    let label = key + "[" + index.to_string() + "]"
    guard entry is Object(parts) &&
      parts.length() == 3 &&
      parts.get("left") is Some(String(left)) &&
      parts.get("right") is Some(String(right)) &&
      parts.get("op") is Some(String(op)) else {
      errors.push(
        issue(
          "row-rule-schema",
          resource,
          0,
          "",
          label + " requires exactly the string properties left, op and right",
        ),
      )
      continue
    }
    let op : RowRuleOp = match op {
      "<" => Less
      "<=" => LessEqual
      "=" => Equal
      _ => {
        errors.push(
          issue(
            "row-rule-schema",
            resource,
            0,
            left,
            label + " requires op <, <= or =",
          ),
        )
        continue
      }
    }
    rules.push({ left, op, right, })
  }
  rules
}

///|
fn bind_row_rules(
  resource : String,
  fields : Array[Field],
  rules : Array[RowRule],
  errors : Array[Diagnostic],
) -> Array[BoundRowRule] {
  let bound = []
  if rules.is_empty() {
    return bound
  }
  let columns : Map[String, Int32] = Map([])
  for index, field in fields {
    columns[field.name] = index
  }
  for rule in rules {
    let left = columns.get(rule.left)
    let right = columns.get(rule.right)
    for (name, index) in [(rule.left, left), (rule.right, right)] {
      match index {
        None =>
          errors.push(
            issue(
              "row-rule-schema",
              resource,
              0,
              name,
              "Unknown row rule field: " + name,
            ),
          )
        Some(i) if !numeric_kind(fields[i].kind) =>
          errors.push(
            issue(
              "row-rule-schema",
              resource,
              0,
              name,
              "Row rule requires an integer or number field: " + name,
            ),
          )
        _ => ()
      }
    }
    if left is Some(l) && right is Some(r) {
      bound.push({ rule, left: l, right: r, })
    }
  }
  bound
}

///|
fn finite_row_decimal(value : Cell) -> ExactDecimal? {
  match value {
    IntegerValue(n) => Some(decimal_value(n.to_string()))
    BigIntegerValue(n) => Some(decimal_value(n.to_string()))
    _ => logical_decimal(value)
  }
}

///|
/// NaN is unordered, including against itself. Infinities sort beyond all
/// finite values, and an infinity equals another infinity with the same sign.
fn row_numeric_order(left : Cell, right : Cell) -> Int32? {
  match (left, right) {
    (SpecialNumber("NaN"), _) | (_, SpecialNumber("NaN")) => None
    (SpecialNumber(a), SpecialNumber(b)) if a == b => Some(0)
    (SpecialNumber("-INF"), _) | (_, SpecialNumber("INF")) => Some(-1)
    (SpecialNumber("INF"), _) | (_, SpecialNumber("-INF")) => Some(1)
    (IntegerValue(a), IntegerValue(b)) => Some(a.compare(b))
    (NumberValue(a), NumberValue(b)) => Some(a.compare(b))
    (BigIntegerValue(a), BigIntegerValue(b)) => Some(a.compare(b))
    (IntegerValue(a), BigIntegerValue(b)) =>
      Some(@bigint.BigInt::from_int64(a).compare(b))
    (BigIntegerValue(a), IntegerValue(b)) =>
      Some(a.compare(@bigint.BigInt::from_int64(b)))
    _ =>
      match (finite_row_decimal(left), finite_row_decimal(right)) {
        (Some(a), Some(b)) => Some(compare_decimal(a, b))
        _ => None
      }
  }
}

///|
fn check_row_rules(
  resource : String,
  row : Int32,
  cells : Array[Cell],
  rules : Array[BoundRowRule],
  errors : Array[Diagnostic],
) -> Unit {
  for bound in rules {
    let rule = bound.rule
    let left = cells[bound.left]
    let right = cells[bound.right]
    if left == Missing || right == Missing {
      continue
    }
    let passes = match (rule.op, row_numeric_order(left, right)) {
      (Less, Some(order)) => order < 0
      (LessEqual, Some(order)) => order <= 0
      (Equal, Some(order)) => order == 0
      (_, None) => false
    }
    if !passes {
      errors.push(
        issue(
          "row-rule",
          resource,
          row,
          rule.left,
          "Expected " +
          rule.left +
          " " +
          rule.op.symbol() +
          " " +
          rule.right +
          " (" +
          rule.left +
          "=" +
          logical_cell_json(left).stringify() +
          ", " +
          rule.right +
          "=" +
          logical_cell_json(right).stringify() +
          ")",
        ),
      )
    }
  }
}