// Source adapters: YAML (bobzhang/yaml) and JSON (core/json) → Node.
// Parse failures raise SpecError with the located message; duplicate keys in
// YAML are caught prior to alias resolution via `parse_yaml_stream_raw` and
// reported as `SourceIssue`s (last value wins, visible in diagnostics).

///|
fn loc_label(pointer : String) -> String {
  if pointer == "" {
    "document root"
  } else {
    pointer
  }
}

///|
/// Unwrap anchor/tag wrappers around a YAML mapping key.
fn unwrap_yaml_key(key : @yaml.Yaml) -> @yaml.Yaml {
  match key {
    @yaml.Anchor(value~, ..) => unwrap_yaml_key(value)
    @yaml.Tagged(value~, ..) => unwrap_yaml_key(value)
    other => other
  }
}

///|
/// Walk a raw YAML tree (before `resolve_aliases` deduplicates map keys) to
/// record duplicate keys at their JSON-pointer locations.
fn scan_yaml_duplicate_keys(
  value : @yaml.Yaml,
  pointer : String,
  issues : Array[SourceIssue],
) -> Unit {
  match value {
    @yaml.Anchor(value~, ..) => scan_yaml_duplicate_keys(value, pointer, issues)
    @yaml.Tagged(value~, ..) => scan_yaml_duplicate_keys(value, pointer, issues)
    @yaml.Seq(items) =>
      for i, item in items {
        scan_yaml_duplicate_keys(item, pointer + "/" + i.to_string(), issues)
      }
    @yaml.Map(entries) => {
      let seen : Map[String, Unit] = Map([])
      for entry in entries {
        let (raw_key, val_node) = entry
        let key_opt : String? = match unwrap_yaml_key(raw_key) {
          @yaml.String(s) => if s == "<<" { None } else { Some(s) }
          @yaml.Int(i) => Some(i.to_string())
          _ => None
        }
        match key_opt {
          Some(key) => {
            if seen.contains(key) {
              issues.push({
                code: "E-duplicate-key",
                pointer: pointer_join(pointer, key),
                message: "duplicate key \"\{key}\" at \{loc_label(pointer)} (last value wins)",
              })
            } else {
              seen[key] = ()
            }
            scan_yaml_duplicate_keys(
              val_node,
              pointer_join(pointer, key),
              issues,
            )
          }
          None => scan_yaml_duplicate_keys(val_node, pointer, issues)
        }
      }
    }
    _ => ()
  }
}

///|
/// Convert a resolved `bobzhang/yaml` tree into `Node`.
fn yaml_to_node(
  value : @yaml.Yaml,
  pointer : String,
  issues : Array[SourceIssue],
) -> Node raise SpecError {
  match value {
    @yaml.Null => Null
    @yaml.Bool(b) => Bool(b)
    @yaml.Int(i) => Number(i.to_string())
    @yaml.Float(f) => Number(f.to_string())
    @yaml.String(s) => Str(s)
    @yaml.Binary(bytes) => Str(@yaml.encode_base64(bytes))
    @yaml.Seq(items) => {
      let out : Array[Node] = []
      for i, item in items {
        out.push(yaml_to_node(item, pointer + "/" + i.to_string(), issues))
      }
      Array(out)
    }
    @yaml.Map(entries) => {
      let converted : Array[(String, Node)] = []
      for entry in entries {
        let (key_node, value_node) = entry
        let key = match unwrap_yaml_key(key_node) {
          @yaml.String(s) => s
          @yaml.Int(i) => {
            let s = i.to_string()
            issues.push({
              code: "W-numeric-key",
              pointer: pointer_join(pointer, s),
              message: "unquoted numeric key \{i} at \{loc_label(pointer)} coerced to string",
            })
            s
          }
          other =>
            raise SpecError(
              "object key at \{loc_label(pointer)} is not a string: \{other}",
            )
        }
        let child_pointer = pointer_join(pointer, key)
        converted.push((key, yaml_to_node(value_node, child_pointer, issues)))
      }
      Object({ entries: converted, })
    }
    @yaml.Anchor(value~, ..) => yaml_to_node(value, pointer, issues)
    @yaml.Tagged(value~, ..) => yaml_to_node(value, pointer, issues)
    @yaml.Alias(name) =>
      raise SpecError("unresolved alias \"\{name}\" at \{loc_label(pointer)}")
  }
}

///|
/// Return true if `rest` (the text after `- ` or `: `) is a YAML block mapping
/// entry (`key:` or `key: value`), carefully ignoring quoted scalars that merely
/// contain `:` inside quotes, flow collections, block scalars, anchors/tags,
/// and nested `-` sequence indicators.
fn is_inline_block_map_entry(rest : String) -> Bool {
  if rest.is_empty() {
    return false
  }
  let first = rest.code_unit_at(0).to_int()
  if first == '-'.to_int() ||
    first == '?'.to_int() ||
    first == ':'.to_int() ||
    first == '{'.to_int() ||
    first == '['.to_int() ||
    first == '|'.to_int() ||
    first == '>'.to_int() ||
    first == '&'.to_int() ||
    first == '!'.to_int() ||
    first == '*'.to_int() ||
    first == '#'.to_int() {
    return false
  }
  let n = rest.length()
  let mut i : Int32 = 0
  if first == '"'.to_int() {
    i = 1
    while i < n {
      let c = rest.code_unit_at(i).to_int()
      if c == '\\'.to_int() {
        i += 2
        continue
      }
      if c == '"'.to_int() {
        i += 1
        break
      }
      i += 1
    }
    while i < n &&
          (
            rest.code_unit_at(i).to_int() == ' '.to_int() ||
            rest.code_unit_at(i).to_int() == '\t'.to_int()
          ) {
      i += 1
    }
    return i < n &&
      rest.code_unit_at(i).to_int() == ':'.to_int() &&
      (
        i + 1 == n ||
        rest.code_unit_at(i + 1).to_int() == ' '.to_int() ||
        rest.code_unit_at(i + 1).to_int() == '\t'.to_int()
      )
  }
  if first == '\''.to_int() {
    i = 1
    while i < n {
      let c = rest.code_unit_at(i).to_int()
      if c == '\''.to_int() {
        if i + 1 < n && rest.code_unit_at(i + 1).to_int() == '\''.to_int() {
          i += 2
          continue
        }
        i += 1
        break
      }
      i += 1
    }
    while i < n &&
          (
            rest.code_unit_at(i).to_int() == ' '.to_int() ||
            rest.code_unit_at(i).to_int() == '\t'.to_int()
          ) {
      i += 1
    }
    return i < n &&
      rest.code_unit_at(i).to_int() == ':'.to_int() &&
      (
        i + 1 == n ||
        rest.code_unit_at(i + 1).to_int() == ' '.to_int() ||
        rest.code_unit_at(i + 1).to_int() == '\t'.to_int()
      )
  }
  // Unquoted key: scan for `:` followed by EOL or space/tab before any `#` comment.
  while i < n {
    let c = rest.code_unit_at(i).to_int()
    if c == '#'.to_int() &&
      i > 0 &&
      (
        rest.code_unit_at(i - 1).to_int() == ' '.to_int() ||
        rest.code_unit_at(i - 1).to_int() == '\t'.to_int()
      ) {
      return false
    }
    if c == ':'.to_int() &&
      (
        i + 1 == n ||
        rest.code_unit_at(i + 1).to_int() == ' '.to_int() ||
        rest.code_unit_at(i + 1).to_int() == '\t'.to_int()
      ) {
      return i > 0
    }
    i += 1
  }
  false
}

///|
/// Return true if a non-quoted YAML value suffix (after `:` or `-`) opens a
/// block scalar (`|`, `|-`, `|+`, `>`, `>-`, `>+`, optionally with 1-9 indent
/// indicator and trailing comment).
fn starts_block_scalar(val_part : String) -> Bool {
  let t = val_part.trim().to_owned()
  if t.is_empty() {
    return false
  }
  let c0 = t.code_unit_at(0).to_int()
  if c0 != '|'.to_int() && c0 != '>'.to_int() {
    return false
  }
  let n = t.length()
  let mut i : Int32 = 1
  while i < n {
    let c = t.code_unit_at(i).to_int()
    if c == '+'.to_int() ||
      c == '-'.to_int() ||
      (c >= '1'.to_int() && c <= '9'.to_int()) {
      i += 1
    } else if c == ' '.to_int() || c == '\t'.to_int() {
      // Only trailing spaces or a `#` comment may follow a block scalar header
      while i < n &&
            (
              t.code_unit_at(i).to_int() == ' '.to_int() ||
              t.code_unit_at(i).to_int() == '\t'.to_int()
            ) {
        i += 1
      }
      return i == n || t.code_unit_at(i).to_int() == '#'.to_int()
    } else {
      return false
    }
  }
  true
}

///|
/// Check if the value part of a mapping line (`key: |...`) or sequence item
/// (`- |...`) starts a YAML block scalar.
fn line_starts_block_scalar(trimmed : String) -> Bool {
  if trimmed.has_prefix("- ") || trimmed.has_prefix("-\t") {
    let after_dash = trimmed[1:].to_owned()
    if starts_block_scalar(after_dash) {
      return true
    }
  }
  // Find first unquoted `: ` or trailing `:`
  let n = trimmed.length()
  let mut in_sq = false
  let mut in_dq = false
  let mut i : Int32 = 0
  while i < n {
    let c = trimmed.code_unit_at(i).to_int()
    if in_dq {
      if c == '\\'.to_int() {
        i += 2
        continue
      }
      if c == '"'.to_int() {
        in_dq = false
      }
    } else if in_sq {
      if c == '\''.to_int() {
        if i + 1 < n && trimmed.code_unit_at(i + 1).to_int() == '\''.to_int() {
          i += 2
          continue
        }
        in_sq = false
      }
    } else if c == '"'.to_int() {
      in_dq = true
    } else if c == '\''.to_int() {
      in_sq = true
    } else if c == '#'.to_int() &&
      (
        i == 0 ||
        trimmed.code_unit_at(i - 1).to_int() == ' '.to_int() ||
        trimmed.code_unit_at(i - 1).to_int() == '\t'.to_int()
      ) {
      return false
    } else if c == ':'.to_int() &&
      i + 1 < n &&
      (
        trimmed.code_unit_at(i + 1).to_int() == ' '.to_int() ||
        trimmed.code_unit_at(i + 1).to_int() == '\t'.to_int()
      ) {
      return starts_block_scalar(trimmed[i + 1:].to_owned())
    }
    i += 1
  }
  false
}

///|
/// Work around a `bobzhang/yaml@0.1.3` bug (`inline_virtual_indent_map`) and
/// O(N²) line-copy cliff on compact block mappings inside sequence items
/// (`- key: ...`) or explicit map values (`: key: ...`).
///
/// Semantically identical in YAML 1.2: splits `- : ...` into
/// `-\n: ...` (preserving exact column
/// alignment), while leaving block scalars (`|`/`>`) and multiline quoted
/// values (where the quote actually opens at the start of a YAML value)
/// completely untouched.
fn normalize_yaml_compact_blocks(text : String) -> String {
  let out = StringBuilder(capacity=text.length() + 1024)
  let mut block_scalar_indent : Int32? = None
  let mut open_quote : Int32 = 0 // 0 = none, 34 = '"', 39 = '\''
  let mut first_line = true
  for raw_sv in text.split("\n") {
    if !first_line {
      out.write_char('\n')
    }
    first_line = false
    let raw = raw_sv.to_owned()
    let line = if raw.has_suffix("\r") {
      raw[:raw.length() - 1].to_owned()
    } else {
      raw
    }
    // Count leading spaces
    let n = line.length()
    let mut indent : Int32 = 0
    while indent < n && line.code_unit_at(indent).to_int() == ' '.to_int() {
      indent += 1
    }
    let trimmed = line[indent:].to_owned()
    let is_blank = trimmed.is_empty()
    let is_comment = trimmed.has_prefix("#")

    // Active multiline quoted string continuation
    if open_quote != 0 {
      out.write_string(raw)
      let tn = trimmed.length()
      let mut j : Int32 = 0
      while j < tn {
        let c = trimmed.code_unit_at(j).to_int()
        if open_quote == '"'.to_int() {
          if c == '\\'.to_int() {
            j += 2
            continue
          }
          if c == '"'.to_int() {
            open_quote = 0
            break
          }
        } else if c == '\''.to_int() {
          if j + 1 < tn && trimmed.code_unit_at(j + 1).to_int() == '\''.to_int() {
            j += 2
            continue
          }
          open_quote = 0
          break
        }
        j += 1
      }
      continue
    }

    // Active block scalar (`|` / `>`)
    match block_scalar_indent {
      Some(parent_ind) =>
        if is_blank || indent > parent_ind {
          out.write_string(raw)
          continue
        } else {
          block_scalar_indent = None
        }
      None => ()
    }

    if is_blank || is_comment {
      out.write_string(raw)
      continue
    }

    // Check for compact block mapping after `- ` or `: `
    let mut active_trimmed = trimmed
    let mut active_indent = indent
    let c0 = trimmed.code_unit_at(0).to_int()
    if (c0 == '-'.to_int() || c0 == ':'.to_int()) && trimmed.length() >= 2 {
      let mut sp : Int32 = 1
      while sp < trimmed.length() &&
            trimmed.code_unit_at(sp).to_int() == ' '.to_int() {
        sp += 1
      }
      if sp >= 2 {
        let rest = trimmed[sp:].to_owned()
        if is_inline_block_map_entry(rest) {
          let ind_str = line[:indent].to_owned()
          out.write_string(ind_str)
          out.write_char(if c0 == '-'.to_int() { '-' } else { ':' })
          out.write_char('\n')
          active_indent = indent + sp
          for _ in 0.. {
          let after = active_trimmed[idx + 2:]
            .to_owned()
            .trim_start()
            .to_owned()
          if after.has_prefix("\"") || after.has_prefix("'") {
            Some(after)
          } else {
            None
          }
        }
        None => None
      }
    }
    match val_start_str {
      Some(vs) => {
        let q = vs.code_unit_at(0).to_int()
        let vn = vs.length()
        let mut closed = false
        let mut j : Int32 = 1
        while j < vn {
          let c = vs.code_unit_at(j).to_int()
          if q == '"'.to_int() {
            if c == '\\'.to_int() {
              j += 2
              continue
            }
            if c == '"'.to_int() {
              closed = true
              break
            }
          } else if c == '\''.to_int() {
            if j + 1 < vn && vs.code_unit_at(j + 1).to_int() == '\''.to_int() {
              j += 2
              continue
            }
            closed = true
            break
          }
          j += 1
        }
        if !closed {
          open_quote = q
        }
      }
      None => ()
    }
  }
  out.to_string()
}

///|
/// Parse a single-document YAML source. Detects duplicate keys prior to alias
/// resolution and returns them in `issues`. Raises `SpecError` on syntax
/// errors, multiple documents, non-string keys, or unresolved aliases.
pub fn parse_yaml_source(
  text : String,
) -> (Node, Array[SourceIssue]) raise SpecError {
  let normalized = normalize_yaml_compact_blocks(text)
  let raw_docs = @yaml.parse_yaml_stream_raw(normalized) catch {
    e => raise SpecError("YAML parse error: \{e}")
  }
  if raw_docs.length() != 1 {
    raise SpecError(
      "YAML parse error: expected single document, found \{raw_docs.length()}",
    )
  }
  let raw_doc = raw_docs[0]
  let issues : Array[SourceIssue] = []
  scan_yaml_duplicate_keys(raw_doc, "", issues)
  let resolved = @yaml.resolve_aliases(raw_doc) catch {
    e => raise SpecError("YAML parse error: \{e}")
  }
  let node = yaml_to_node(resolved, "", issues)
  (node, issues)
}

///|
/// Parse a JSON document. `@json.parse` is called with duplicate-key rejection
/// and `preserve_number_repr=true`, so duplicate keys are hard errors and
/// number literals preserve their exact text.
pub fn parse_json_source(
  text : String,
) -> (Node, Array[SourceIssue]) raise SpecError {
  let value = @json.parse(
    text,
    reject_duplicate_keys=true,
    preserve_number_repr=true,
  ) catch {
    e => raise SpecError("JSON parse error: \{e}")
  }
  (json_to_node(value), [])
}

///|
fn json_to_node(value : @json.Json) -> Node {
  match value {
    @json.Null => Null
    @json.True => Bool(true)
    @json.False => Bool(false)
    @json.Number(value_repr, repr=rep) =>
      Number(
        match rep {
          Some(text) => text
          None => "\{value_repr}"
        },
      )
    @json.String(s) => Str(s)
    @json.Array(items) => Array(items.map(json_to_node))
    @json.Object(fields) => {
      let converted : Array[(String, Node)] = []
      for key, item in fields {
        converted.push((key, json_to_node(item)))
      }
      Object({ entries: converted, })
    }
  }
}