// OpenAPI Overlays Specification 1.0.0 engine (plan 7.6).
// Evaluates JSONPath `target` expressions (`$`, `.prop`, `['prop']`, `[idx]`,
// `[*]`, `.*`, `..prop`, `[?(@.key == 'val')]`, `[?(@.key != 'val')]`) and
// applies `update` (deep merge / array append) and `remove` actions.

///|
priv enum FilterValue {
  Str(String)
  Num(String)
  Bool(Bool)
  Null
}

///|
priv enum PathStep {
  Key(String)
  Index(Int32)
  Wildcard
  RecursiveKey(String)
  FilterEq(key~ : String, value~ : FilterValue, negate~ : Bool)
}

///|
fn parse_jsonpath_string_lit(
  s : String,
  start : Int32,
  quote : UInt16,
) -> (String, Int32)? {
  let buf = StringBuilder()
  let mut i = start
  let mut seg_start = start
  while i < s.length() {
    let ch = s[i]
    if ch == '\\' && i + 1 < s.length() {
      if i > seg_start {
        buf.write_string(s[seg_start:i].to_owned())
      }
      let next = s[i + 1]
      match next {
        'n' => buf.write_char('\n')
        'r' => buf.write_char('\r')
        't' => buf.write_char('\t')
        '\\' => buf.write_char('\\')
        '\'' => buf.write_char('\'')
        '"' => buf.write_char('"')
        _ => buf.write_string(s[i + 1:i + 2].to_owned())
      }
      i += 2
      seg_start = i
      continue
    }
    if ch == quote {
      if i > seg_start {
        buf.write_string(s[seg_start:i].to_owned())
      }
      return Some((buf.to_string(), i + 1))
    }
    i += 1
  }
  None
}

///|
fn parse_jsonpath(expr : String) -> Array[PathStep]? {
  let trimmed = expr.trim().to_owned()
  if !trimmed.has_prefix("$") {
    return None
  }
  let steps : Array[PathStep] = []
  let mut i : Int32 = 1
  let n = trimmed.length()
  while i < n {
    let ch = trimmed[i]
    if ch == '.' {
      if i + 1 < n && trimmed[i + 1] == '.' {
        // Recursive descent `..key`
        i += 2
        if i < n && trimmed[i] == '[' {
          // `..['key']`
          i += 1
          if i < n && (trimmed[i] == '\'' || trimmed[i] == '"') {
            match parse_jsonpath_string_lit(trimmed, i + 1, trimmed[i]) {
              Some((k, next_i)) if next_i < n && trimmed[next_i] == ']' => {
                steps.push(RecursiveKey(k))
                i = next_i + 1
                continue
              }
              _ => return None
            }
          }
          return None
        }
        let start = i
        while i < n && trimmed[i] != '.' && trimmed[i] != '[' {
          i += 1
        }
        if i == start {
          return None
        }
        steps.push(RecursiveKey(trimmed[start:i].to_owned()))
      } else {
        i += 1
        if i < n && trimmed[i] == '*' {
          steps.push(Wildcard)
          i += 1
        } else {
          let start = i
          while i < n && trimmed[i] != '.' && trimmed[i] != '[' {
            i += 1
          }
          if i == start {
            return None
          }
          steps.push(Key(trimmed[start:i].to_owned()))
        }
      }
    } else if ch == '[' {
      i += 1
      while i < n && trimmed[i] == ' ' {
        i += 1
      }
      if i >= n {
        return None
      }
      if trimmed[i] == '*' {
        i += 1
        while i < n && trimmed[i] == ' ' {
          i += 1
        }
        if i >= n || trimmed[i] != ']' {
          return None
        }
        steps.push(Wildcard)
        i += 1
      } else if trimmed[i] == '\'' || trimmed[i] == '"' {
        match parse_jsonpath_string_lit(trimmed, i + 1, trimmed[i]) {
          Some((k, next_i)) => {
            let mut j = next_i
            while j < n && trimmed[j] == ' ' {
              j += 1
            }
            if j >= n || trimmed[j] != ']' {
              return None
            }
            steps.push(Key(k))
            i = j + 1
          }
          None => return None
        }
      } else if trimmed[i] == '?' {
        // Filter expression: `[?(@.key == 'val')]` or `[?@.key == 'val']`
        i += 1
        let start = i
        let mut depth : Int32 = 1
        let mut in_quote : UInt16 = 0
        while i < n && depth > 0 {
          let c = trimmed[i]
          if in_quote != 0 {
            if c == '\\' && i + 1 < n {
              i += 2
              continue
            }
            if c == in_quote {
              in_quote = 0
            }
          } else if c == '\'' || c == '"' {
            in_quote = c
          } else if c == '[' {
            depth += 1
          } else if c == ']' {
            depth -= 1
            if depth == 0 {
              break
            }
          }
          i += 1
        }
        if depth != 0 {
          return None
        }
        let body = trimmed[start:i].to_owned().trim().to_owned()
        i += 1 // skip ']'
        // Only strip one matching outer `( ... )` pair if it actually balances
        // across the whole filter (rejecting `(@.a == 1) && (@.b == 2)`).
        let inner = if body.has_prefix("(") && body.has_suffix(")") {
          let mut pdepth : Int32 = 0
          let mut pquote : UInt16 = 0
          let mut wraps_all = true
          let mut pi : Int32 = 0
          while pi < body.length() {
            let pc = body[pi]
            if pquote != 0 {
              if pc == '\\' && pi + 1 < body.length() {
                pi += 2
                continue
              }
              if pc == pquote {
                pquote = 0
              }
            } else if pc == '\'' || pc == '"' {
              pquote = pc
            } else if pc == '(' {
              pdepth += 1
            } else if pc == ')' {
              pdepth -= 1
              if pdepth == 0 && pi < body.length() - 1 {
                wraps_all = false
                break
              }
            }
            pi += 1
          }
          if wraps_all && pdepth == 0 {
            body[1:body.length() - 1].to_owned().trim().to_owned()
          } else {
            return None
          }
        } else {
          body
        }
        // Scan for `==` or `!=` OUTSIDE quoted string literals.
        let mut op_idx : Int32 = -1
        let mut negate = false
        let mut oquote : UInt16 = 0
        let mut oi : Int32 = 0
        while oi + 1 < inner.length() {
          let oc = inner[oi]
          if oquote != 0 {
            if oc == '\\' && oi + 1 < inner.length() {
              oi += 2
              continue
            }
            if oc == oquote {
              oquote = 0
            }
            oi += 1
            continue
          }
          if oc == '\'' || oc == '"' {
            oquote = oc
            oi += 1
            continue
          }
          if oc == '=' && inner[oi + 1] == '=' {
            op_idx = oi
            negate = false
            break
          }
          if oc == '!' && inner[oi + 1] == '=' {
            op_idx = oi
            negate = true
            break
          }
          oi += 1
        }
        if op_idx < 0 {
          return None
        }
        let lhs = inner[:op_idx].to_owned().trim().to_owned()
        let rhs = inner[op_idx + 2:].to_owned().trim().to_owned()
        if !lhs.has_prefix("@.") || rhs.is_empty() {
          return None
        }
        let field_key = lhs[2:].to_owned().trim().to_owned()
        if field_key.is_empty() || !is_valid_filter_key(field_key) {
          return None
        }
        let val : FilterValue = if rhs[0] == '\'' || rhs[0] == '"' {
          match parse_jsonpath_string_lit(rhs, 1, rhs[0]) {
            Some((parsed_val, end_idx)) if end_idx == rhs.length() =>
              Str(parsed_val)
            _ => return None
          }
        } else if rhs == "true" {
          Bool(true)
        } else if rhs == "false" {
          Bool(false)
        } else if rhs == "null" {
          Null
        } else if is_valid_json_number_lit(rhs) {
          Num(rhs)
        } else {
          return None
        }
        steps.push(FilterEq(key=field_key, value=val, negate~))
      } else {
        // Numeric index
        let start = i
        while i < n && trimmed[i] != ']' {
          i += 1
        }
        if i >= n {
          return None
        }
        let num_str = trimmed[start:i].to_owned().trim().to_owned()
        i += 1
        match parse_int64_text(num_str) {
          Some(v) if v >= 0L && v <= 2147483647L =>
            steps.push(Index(v.to_int()))
          _ => return None
        }
      }
    } else {
      return None
    }
  }
  Some(steps)
}

///|
/// Deep-merge `patch` into `target` per OpenAPI Overlays 1.0.0 ยง4.4.4:
/// - Object + Object -> recursively merge keys (`patch` overwrites matching keys)
/// - Array + Array -> append `patch` items to `target`
/// - Anything else -> replace `target` with `patch`.
fn overlay_merge(target : Node, patch : Node) -> Node {
  match (target, patch) {
    (Object(t_obj), Object(p_obj)) => {
      let out = t_obj.entries.copy()
      for p_entry in p_obj.entries {
        let (pk, pv) = p_entry
        let mut found = false
        for i in 0.. {
      let out = t_arr.copy()
      for item in p_arr {
        out.push(item)
      }
      Array(out)
    }
    (_, p) => p
  }
}

///|
fn is_valid_filter_key(s : String) -> Bool {
  for ch in s {
    if ch == ' ' ||
      ch == '\t' ||
      ch == '\n' ||
      ch == '\r' ||
      ch == '&' ||
      ch == '|' ||
      ch == '=' ||
      ch == '!' ||
      ch == '(' ||
      ch == ')' ||
      ch == '\'' ||
      ch == '"' {
      return false
    }
  }
  true
}

///|
fn is_valid_json_number_lit(s : String) -> Bool {
  let n = s.length()
  if n == 0 {
    return false
  }
  let mut i = 0
  if s[i] == '-' {
    i += 1
    if i >= n {
      return false
    }
  }
  if s[i] == '0' {
    i += 1
  } else if s[i] >= '1' && s[i] <= '9' {
    while i < n && s[i] >= '0' && s[i] <= '9' {
      i += 1
    }
  } else {
    return false
  }
  if i < n && s[i] == '.' {
    i += 1
    if i >= n || s[i] < '0' || s[i] > '9' {
      return false
    }
    while i < n && s[i] >= '0' && s[i] <= '9' {
      i += 1
    }
  }
  if i < n && (s[i] == 'e' || s[i] == 'E') {
    i += 1
    if i < n && (s[i] == '+' || s[i] == '-') {
      i += 1
    }
    if i >= n || s[i] < '0' || s[i] > '9' {
      return false
    }
    while i < n && s[i] >= '0' && s[i] <= '9' {
      i += 1
    }
  }
  i == n
}

///|
fn matches_filter(
  node : Node,
  key : String,
  value : FilterValue,
  negate : Bool,
) -> Bool {
  match node {
    Object(obj) => {
      let eq = match (obj.get(key), value) {
        (Some(Str(s)), Str(target)) => s == target
        (Some(Bool(b)), Bool(target)) => b == target
        (Some(Null), Null) => true
        (Some(Number(n) as nn), Num(target)) =>
          if n == target {
            true
          } else {
            let tn = Node::Number(target)
            match (nn.as_int64(), tn.as_int64()) {
              (Some(ix), Some(iy)) => ix == iy
              _ =>
                match (nn.as_double(), tn.as_double()) {
                  (Some(dx), Some(dy)) => dx == dy
                  _ => false
                }
            }
          }
        _ => false
      }
      if negate {
        !eq
      } else {
        eq
      }
    }
    _ => false
  }
}

///|
fn apply_update_steps(
  node : Node,
  steps : Array[PathStep],
  idx : Int32,
  patch : Node,
) -> Node {
  if idx >= steps.length() {
    return overlay_merge(node, patch)
  }
  match steps[idx] {
    Key(k) =>
      match node {
        Object(obj) => {
          let out : Array[(String, Node)] = []
          for entry in obj.entries {
            if entry.0 == k {
              out.push((k, apply_update_steps(entry.1, steps, idx + 1, patch)))
            } else {
              out.push(entry)
            }
          }
          Object({ entries: out, })
        }
        _ => node
      }
    Index(target_i) =>
      match node {
        Array(items) => {
          let out : Array[Node] = []
          for i, item in items {
            if i == target_i {
              out.push(apply_update_steps(item, steps, idx + 1, patch))
            } else {
              out.push(item)
            }
          }
          Array(out)
        }
        _ => node
      }
    Wildcard =>
      match node {
        Object(obj) => {
          let out : Array[(String, Node)] = []
          for entry in obj.entries {
            out.push(
              (entry.0, apply_update_steps(entry.1, steps, idx + 1, patch)),
            )
          }
          Object({ entries: out, })
        }
        Array(items) =>
          Array(items.map(it => apply_update_steps(it, steps, idx + 1, patch)))
        _ => node
      }
    RecursiveKey(k) =>
      match node {
        Object(obj) => {
          let out : Array[(String, Node)] = []
          for entry in obj.entries {
            let child = apply_update_steps(entry.1, steps, idx, patch)
            let updated = if entry.0 == k {
              apply_update_steps(child, steps, idx + 1, patch)
            } else {
              child
            }
            out.push((entry.0, updated))
          }
          Object({ entries: out, })
        }
        Array(items) =>
          Array(items.map(it => apply_update_steps(it, steps, idx, patch)))
        _ => node
      }
    FilterEq(key~, value~, negate~) =>
      match node {
        Array(items) => {
          let out : Array[Node] = []
          for item in items {
            if matches_filter(item, key, value, negate) {
              out.push(apply_update_steps(item, steps, idx + 1, patch))
            } else {
              out.push(item)
            }
          }
          Array(out)
        }
        Object(obj) => {
          let out : Array[(String, Node)] = []
          for entry in obj.entries {
            if matches_filter(entry.1, key, value, negate) {
              out.push(
                (entry.0, apply_update_steps(entry.1, steps, idx + 1, patch)),
              )
            } else {
              out.push(entry)
            }
          }
          Object({ entries: out, })
        }
        _ => node
      }
  }
}

///|
fn apply_remove_steps(
  node : Node,
  steps : Array[PathStep],
  idx : Int32,
) -> Node {
  if idx >= steps.length() {
    return node
  }
  let is_last = idx == steps.length() - 1
  match steps[idx] {
    Key(k) =>
      match node {
        Object(obj) => {
          let out : Array[(String, Node)] = []
          for entry in obj.entries {
            if entry.0 == k {
              if !is_last {
                out.push((k, apply_remove_steps(entry.1, steps, idx + 1)))
              }
            } else {
              out.push(entry)
            }
          }
          Object({ entries: out, })
        }
        _ => node
      }
    Index(target_i) =>
      match node {
        Array(items) => {
          let out : Array[Node] = []
          for i, item in items {
            if i == target_i {
              if !is_last {
                out.push(apply_remove_steps(item, steps, idx + 1))
              }
            } else {
              out.push(item)
            }
          }
          Array(out)
        }
        _ => node
      }
    Wildcard =>
      match node {
        Object(obj) =>
          if is_last {
            Object(ObjectNode::new())
          } else {
            let out : Array[(String, Node)] = []
            for entry in obj.entries {
              out.push((entry.0, apply_remove_steps(entry.1, steps, idx + 1)))
            }
            Object({ entries: out, })
          }
        Array(items) =>
          if is_last {
            Array([])
          } else {
            Array(items.map(it => apply_remove_steps(it, steps, idx + 1)))
          }
        _ => node
      }
    RecursiveKey(k) =>
      match node {
        Object(obj) => {
          let out : Array[(String, Node)] = []
          for entry in obj.entries {
            if entry.0 == k && is_last {
              continue
            }
            let child = apply_remove_steps(entry.1, steps, idx)
            let updated = if entry.0 == k {
              apply_remove_steps(child, steps, idx + 1)
            } else {
              child
            }
            out.push((entry.0, updated))
          }
          Object({ entries: out, })
        }
        Array(items) =>
          Array(items.map(it => apply_remove_steps(it, steps, idx)))
        _ => node
      }
    FilterEq(key~, value~, negate~) =>
      match node {
        Array(items) => {
          let out : Array[Node] = []
          for item in items {
            if matches_filter(item, key, value, negate) {
              if !is_last {
                out.push(apply_remove_steps(item, steps, idx + 1))
              }
            } else {
              out.push(item)
            }
          }
          Array(out)
        }
        Object(obj) => {
          let out : Array[(String, Node)] = []
          for entry in obj.entries {
            if matches_filter(entry.1, key, value, negate) {
              if !is_last {
                out.push((entry.0, apply_remove_steps(entry.1, steps, idx + 1)))
              }
            } else {
              out.push(entry)
            }
          }
          Object({ entries: out, })
        }
        _ => node
      }
  }
}

///|
/// Apply an OpenAPI Overlay 1.0 document (`overlay`) to an OpenAPI `Node` tree
/// (`doc`), executing `actions` in document order.
pub fn apply_overlay(doc : Node, overlay : Node, diags : Diagnostics) -> Node {
  let ov_obj = match overlay {
    Object(o) => o
    _ => {
      diags.error("E-overlay", "", "overlay document must be an object")
      return doc
    }
  }
  match ov_obj.get("overlay") {
    Some(Str(ver)) if ver.has_prefix("1.0") => ()
    Some(Str(ver)) =>
      diags.warning(
        "W-overlay-version",
        "/overlay",
        "unsupported OpenAPI Overlay version \"\{ver}\" (expected 1.0.x)",
      )
    _ =>
      diags.error(
        "E-overlay", "/overlay", "overlay document requires \"overlay\" version",
      )
  }
  let actions = match ov_obj.get("actions") {
    Some(Array(a)) => a
    _ => {
      diags.error(
        "E-overlay", "/actions", "overlay document requires \"actions\" array",
      )
      return doc
    }
  }
  let mut current = doc
  for i, action_node in actions {
    let ptr = "/actions/" + i.to_string()
    let act = match action_node {
      Object(o) => o
      _ => {
        diags.error("E-overlay", ptr, "overlay action must be an object")
        continue
      }
    }
    let target = match act.get("target") {
      Some(Str(t)) => t
      _ => {
        diags.error(
          "E-overlay",
          pointer_join(ptr, "target"),
          "overlay action requires string \"target\" JSONPath",
        )
        continue
      }
    }
    let steps = match parse_jsonpath(target) {
      Some(s) => s
      None => {
        diags.error(
          "E-overlay",
          pointer_join(ptr, "target"),
          "invalid JSONPath expression: \"\{target}\"",
        )
        continue
      }
    }
    let do_remove = match act.get("remove") {
      Some(Bool(b)) => b
      Some(_) => {
        diags.error(
          "E-type",
          pointer_join(ptr, "remove"),
          "overlay action \"remove\" must be a boolean",
        )
        continue
      }
      None => false
    }
    if do_remove {
      if steps.is_empty() {
        diags.error(
          "E-overlay",
          pointer_join(ptr, "target"),
          "cannot remove root document target \"$\"",
        )
      } else {
        current = apply_remove_steps(current, steps, 0)
      }
    } else {
      match act.get("update") {
        Some(patch) => current = apply_update_steps(current, steps, 0, patch)
        None =>
          diags.warning(
            "W-overlay-noop", ptr, "overlay action has neither \"update\" nor \"remove: true\"",
          )
      }
    }
  }
  current
}