///|
#derive(@debug.Debug)
pub(all) struct Limits {
  lower : Double?
  upper : Double?
}

///|
pub fn Limits::contains(self : Limits, n : Double) -> Bool {
  self.lower.map(bound => n >= bound).unwrap_or(true) &&
  self.upper.map(bound => n <= bound).unwrap_or(true)
}

///|
#derive(@debug.Debug)
pub(all) enum Encoding {
  U8
  I8
  U16LE
  I16LE
  U16BE
  I16BE
}

///|
pub(all) enum Step {
  Scalar(
    name~ : String,
    query~ : String,
    samples~ : Int32,
    unit~ : String,
    limits~ : Limits,
  )
  Waveform(
    name~ : String,
    preamble~ : String,
    query~ : String,
    encoding~ : Encoding,
    terminator~ : Terminator,
    unit~ : String,
    limits~ : Limits,
  )
}

///|
pub struct Plan {
  priv name : String
  priv expected_idn_prefix : String?
  priv profile : Profile?
  priv steps : Array[Step]
}

///|
#derive(Eq, @debug.Debug)
pub(all) struct Request {
  query : String
  mode : Mode
}

///|
fn object(value : Json, path : String) -> Map[String, Json] raise ScpiError {
  guard value is Object(data) else {
    raise PlanError(path + " must be an object")
  }
  data
}

///|
fn known(
  fields : Map[String, Json],
  allowed : Array[String],
  path : String,
) -> Unit raise ScpiError {
  for key, _ in fields {
    guard allowed.contains(key) else {
      raise PlanError(path + " has unknown field " + key)
    }
  }
}

///|
fn required_text(
  fields : Map[String, Json],
  key : String,
  path : String,
) -> String raise ScpiError {
  guard fields.get(key) is Some(String(text)) &&
    !text.trim().is_empty() &&
    text.length() <= 240 &&
    !text.iter().any(ch => ch.to_int() < 32 || ch.to_int() == 127) else {
    raise PlanError(
      path +
      "." +
      key +
      " must be a non-empty single-line string of at most 240 characters",
    )
  }
  text
}

///|
fn optional_text(
  fields : Map[String, Json],
  key : String,
  path : String,
  fallback : String,
) -> String raise ScpiError {
  if fields.contains(key) {
    required_text(fields, key, path)
  } else {
    fallback
  }
}

///|
fn ascii_letter(char : Char) -> Bool {
  (char >= 'A' && char <= 'Z') || (char >= 'a' && char <= 'z')
}

///|
fn mnemonic(text : StringView) -> Bool {
  guard text.iter().next() is Some(first) && ascii_letter(first) else {
    return false
  }
  text
  .iter()
  .all(char => ascii_letter(char) || (char >= '0' && char <= '9') || char == '_')
}

///|
fn query_text(
  fields : Map[String, Json],
  key : String,
  path : String,
) -> String raise ScpiError {
  let query = required_text(fields, key, path)
  let error = PlanError(
    path + "." + key + " must be one argument-free SCPI query",
  )
  guard query.has_suffix("?") else { raise error }
  let header = query[:query.length() - 1]
  let valid = if header.has_prefix("*") {
    mnemonic(header[1:])
  } else {
    let hierarchy = if header.has_prefix(":") { header[1:] } else { header }
    hierarchy.split(":").all(mnemonic)
  }
  guard valid else { raise error }
  query
}

///|
fn optional_bound(
  fields : Map[String, Json],
  key : String,
  path : String,
) -> Double? raise ScpiError {
  match fields.get(key) {
    None => None
    Some(Number(value, repr=_)) if !value.is_inf() && !value.is_nan() =>
      Some(value)
    _ => raise PlanError(path + "." + key + " must be a finite number")
  }
}

///|
fn read_step(
  value : Json,
  path : String,
  profile : Profile?,
) -> Step raise ScpiError {
  let fields = object(value, path)
  let kind = required_text(fields, "kind", path)
  let name = required_text(fields, "name", path)
  let query = query_text(fields, "query", path)
  let unit = optional_text(fields, "unit", path, "")
  let lower = optional_bound(fields, "min", path)
  let upper = optional_bound(fields, "max", path)
  if lower is Some(low) && upper is Some(high) && low > high {
    raise PlanError(path + ".min exceeds .max")
  }
  let limits = { lower, upper, }
  let common = ["kind", "name", "query", "unit", "min", "max"]
  match kind {
    "scalar" => {
      common.push("samples")
      let (query, unit) = if profile is Some(instrument) {
        common.push("channel")
        let (wire_query, native_unit) = instrument.scalar_query(
          query,
          fields.get("channel"),
          path,
        )
        guard unit.is_empty() || unit == native_unit else {
          raise PlanError(
            path + ".unit must be " + native_unit + " for " + query,
          )
        }
        (wire_query, native_unit)
      } else {
        (query, unit)
      }
      known(fields, common, path)
      let samples = match fields.get("samples") {
        None => 1
        Some(Number(v, repr=_)) if v >= 1.0 &&
          v <= 100.0 &&
          v.to_int().to_double() == v => v.to_int()
        _ => raise PlanError(path + ".samples must be an integer from 1 to 100")
      }
      Scalar(name~, query~, unit~, limits~, samples~)
    }
    "waveform" => {
      guard profile is None else {
        raise PlanError(
          path + ": the keysight-e36300 profile accepts scalar steps",
        )
      }
      for field in ["preamble", "encoding", "terminator"] {
        common.push(field)
      }
      known(fields, common, path)
      let preamble = query_text(fields, "preamble", path)
      let encoding = match required_text(fields, "encoding", path) {
        "u8" => U8
        "i8" => I8
        "u16le" => U16LE
        "i16le" => I16LE
        "u16be" => U16BE
        "i16be" => I16BE
        _ =>
          raise PlanError(
            path + ".encoding must be u8, i8, u16le, i16le, u16be or i16be",
          )
      }
      let terminator = match optional_text(fields, "terminator", path, "lf") {
        "lf" => LF
        "crlf" => CRLF
        "none" => NoTerminator
        _ => raise PlanError(path + ".terminator must be lf, crlf or none")
      }
      Waveform(name~, preamble~, query~, encoding~, terminator~, unit~, limits~)
    }
    _ => raise PlanError(path + ".kind must be scalar or waveform")
  }
}

///|
/// Parse and validate the whole plan before attempting instrument I/O.
pub fn Plan::parse(text : StringView) -> Plan raise ScpiError {
  let root = @json.parse(text, reject_duplicate_keys=true) catch {
    error => raise PlanError(error.to_string())
  }
  let fields = object(root, "plan")
  known(fields, ["name", "expected_idn_prefix", "profile", "steps"], "plan")
  let name = required_text(fields, "name", "plan")
  let profile = profile_from_json(fields.get("profile"))
  let expected_idn_prefix = if fields.contains("expected_idn_prefix") {
    Some(required_text(fields, "expected_idn_prefix", "plan"))
  } else {
    None
  }
  guard fields.get("steps") is Some(Array(items)) &&
    !items.is_empty() &&
    items.length() <= 64 else {
    raise PlanError("plan.steps must contain 1..64 steps")
  }
  let names : Map[String, Bool] = Map([])
  let steps = []
  for index, item in items {
    let step = read_step(item, "plan.steps[" + index.to_string() + "]", profile)
    let label = match step {
      Scalar(name~, ..) | Waveform(name~, ..) => name
    }
    guard !names.contains(label) else {
      raise PlanError("duplicate step name: " + label)
    }
    names[label] = true
    steps.push(step)
  }
  let plan = { name, expected_idn_prefix, profile, steps, }
  guard plan.requests().length() <= 256 else {
    raise PlanError("plan exceeds 256 queries")
  }
  plan
}

///|
pub fn Plan::requests(self : Plan) -> Array[Request] {
  let result = [{ query: "*IDN?", mode: Text, }]
  for step in self.steps {
    match step {
      Scalar(query~, samples~, ..) =>
        for _ in 0.. {
        result.push({ query: preamble, mode: Text, })
        result.push({ query, mode: Block(terminator), })
      }
    }
  }
  result
}

///|
pub fn Plan::verify_identification(
  self : Plan,
  response : Response,
) -> String raise ScpiError {
  guard response is Line(raw) && !raw.trim().is_empty() else {
    raise MeasurementError("*IDN? must return non-empty text")
  }
  let identity = raw.trim().to_owned()
  if self.profile is Some(instrument) {
    instrument.verify_identity(identity)
  }
  if self.expected_idn_prefix is Some(prefix) && !identity.has_prefix(prefix) {
    raise MeasurementError(
      "instrument identification does not match plan prefix " + prefix,
    )
  }
  identity
}