///|
/// Shared `moonbitlang/parser` AST helpers for `schema_gen`, `orm_gen`, and `wire_gen`.
/// Replaces fragile line-splitting with full MoonBit syntax tree inspection.

///|
fn parse_mbt_ast(
  source : String,
  file : String,
) -> Array[@syntax.Impl] raise GenError {
  let (impls, reports) = @parser.parse_string(source, name=file)
  let out : Array[@syntax.Impl] = []
  let mut cur = impls
  for ;; {
    match cur {
      @list.List::Empty => break
      @list.List::More(item, tail~) => {
        out.push(item)
        cur = tail
      }
    }
  }
  if !reports.is_empty() {
    let first = reports[0]
    raise GenError::InvalidSource(
      file~,
      line=first.loc.start.lnum,
      message="MoonBit syntax error: \{first.msg}",
    )
  }
  out
}

///|
fn render_long_ident(id : @syntax.LongIdent) -> String {
  match id {
    @syntax.LongIdent::Ident(name~) => name
    @syntax.LongIdent::Dot(pkg~, id~) => "@\{pkg}.\{id}"
  }
}

///|
/// Faithfully renders a `@syntax.Type` AST node back into canonical MoonBit type syntax
/// (handling arbitrarily nested generics like `Map[String, Array[Int32]]`, `T?`, tuples, trait objects, and arrows).
fn render_syntax_type(ty : @syntax.Type) -> String {
  match ty {
    @syntax.Type::Any(..) => "_"
    @syntax.Type::Option(ty=inner, ..) => "\{render_syntax_type(inner)}?"
    @syntax.Type::Object(constr_id) => "&\{render_long_ident(constr_id.id)}"
    @syntax.Type::Tuple(tys~, ..) => {
      let parts : Array[String] = []
      let mut cur = tys
      for ;; {
        match cur {
          @list.List::Empty => break
          @list.List::More(t, tail~) => {
            parts.push(render_syntax_type(t))
            cur = tail
          }
        }
      }
      let joined = parts.join(", ")
      "(\{joined})"
    }
    @syntax.Type::Name(constr_id~, tys~, ..) => {
      let base = render_long_ident(constr_id.id)
      let args : Array[String] = []
      let mut cur = tys
      for ;; {
        match cur {
          @list.List::Empty => break
          @list.List::More(t, tail~) => {
            args.push(render_syntax_type(t))
            cur = tail
          }
        }
      }
      if args.is_empty() {
        base
      } else {
        let joined = args.join(", ")
        "\{base}[\{joined}]"
      }
    }
    @syntax.Type::Arrow(args~, res~, is_async~, ..) => {
      let parts : Array[String] = []
      let mut cur = args
      for ;; {
        match cur {
          @list.List::Empty => break
          @list.List::More(t, tail~) => {
            parts.push(render_syntax_type(t))
            cur = tail
          }
        }
      }
      let prefix = if is_async is Some(_) { "async " } else { "" }
      let joined = parts.join(", ")
      "\{prefix}(\{joined}) -> \{render_syntax_type(res)}"
    }
  }
}

///|
/// Recursively validates canonical MoonBit v1 type spellings across the full `@syntax.Type` tree
/// (rejecting legacy `Int`, `UInt`, `Option[T]` even inside nested generics such as `Map[String, Array[Int]]`).
fn check_syntax_type_canonical(
  ty : @syntax.Type,
  file : String,
  fallback_line : Int32,
  as_unsupported~ : Bool = false,
) -> Unit raise GenError {
  match ty {
    @syntax.Type::Any(..) | @syntax.Type::Object(_) => ()
    @syntax.Type::Option(ty=inner, ..) =>
      check_syntax_type_canonical(inner, file, fallback_line, as_unsupported~)
    @syntax.Type::Tuple(tys~, ..) => {
      let mut cur = tys
      for ;; {
        match cur {
          @list.List::Empty => break
          @list.List::More(t, tail~) => {
            check_syntax_type_canonical(t, file, fallback_line, as_unsupported~)
            cur = tail
          }
        }
      }
    }
    @syntax.Type::Arrow(args~, res~, ..) => {
      let mut cur = args
      for ;; {
        match cur {
          @list.List::Empty => break
          @list.List::More(t, tail~) => {
            check_syntax_type_canonical(t, file, fallback_line, as_unsupported~)
            cur = tail
          }
        }
      }
      check_syntax_type_canonical(res, file, fallback_line, as_unsupported~)
    }
    @syntax.Type::Name(constr_id~, tys~, loc~) => {
      let line = if loc.start.lnum > 0 { loc.start.lnum } else { fallback_line }
      match constr_id.id {
        @syntax.LongIdent::Ident(name~) =>
          if name == "Int" {
            let message = "legacy type spelling 'Int' is not supported; run `moon fmt` / `moon fix` and use canonical 'Int32'"
            if as_unsupported {
              raise GenError::UnsupportedConstruct(file~, line~, message~)
            } else {
              raise GenError::InvalidSource(file~, line~, message~)
            }
          } else if name == "UInt" {
            let message = "legacy type spelling 'UInt' is not supported; run `moon fmt` / `moon fix` and use canonical 'UInt32'"
            if as_unsupported {
              raise GenError::UnsupportedConstruct(file~, line~, message~)
            } else {
              raise GenError::InvalidSource(file~, line~, message~)
            }
          } else if name == "Option" {
            let message = "legacy type spelling 'Option[T]' is not supported; run `moon fmt` / `moon fix` and use canonical suffix 'T?'"
            if as_unsupported {
              raise GenError::UnsupportedConstruct(file~, line~, message~)
            } else {
              raise GenError::InvalidSource(file~, line~, message~)
            }
          }
        @syntax.LongIdent::Dot(..) => ()
      }
      let mut cur = tys
      for ;; {
        match cur {
          @list.List::Empty => break
          @list.List::More(t, tail~) => {
            check_syntax_type_canonical(t, file, line, as_unsupported~)
            cur = tail
          }
        }
      }
    }
  }
}

///|
/// Normalizes multi-line raw attribute text into a single trimmed line while preserving string literals.
fn normalize_attr_raw(raw : String) -> String {
  let sb = StringBuilder()
  let mut in_str = false
  let mut escaped = false
  for ch in raw {
    if in_str {
      sb.write_char(ch)
      if escaped {
        escaped = false
      } else if ch == '\\' {
        escaped = true
      } else if ch == '"' {
        in_str = false
      }
    } else if ch == '"' {
      in_str = true
      sb.write_char(ch)
    } else if ch == '\n' || ch == '\r' || ch == '\t' {
      sb.write_char(' ')
    } else {
      sb.write_char(ch)
    }
  }
  sb.to_string().trim().to_owned()
}

///|
/// Collects both real AST `#...` attributes (including multi-line ones) and `/// #...` doc directives.
fn collect_attr_strings(
  attrs : @list.List[@p_attr.Attribute],
  doc : @syntax.DocString,
) -> Array[String] {
  let out : Array[String] = []
  let mut cur = attrs
  for ;; {
    match cur {
      @list.List::Empty => break
      @list.List::More(a, tail~) => {
        let norm = normalize_attr_raw(a.raw)
        if !norm.is_empty() {
          out.push(norm)
        }
        cur = tail
      }
    }
  }
  let mut dcur = doc.content
  for ;; {
    match dcur {
      @list.List::Empty => break
      @list.List::More(line, tail~) => {
        let t = line.trim().to_owned()
        if t.has_prefix("#") {
          out.push(t)
        }
        dcur = tail
      }
    }
  }
  out
}

///|
/// Extracts plain human-readable documentation from `///` doc comments (ignoring `#ciallo.*`/`#orm.*` directives).
fn extract_doc_description(doc : @syntax.DocString) -> String? {
  let lines : Array[String] = []
  let mut cur = doc.content
  for ;; {
    match cur {
      @list.List::Empty => break
      @list.List::More(line, tail~) => {
        let t = line.trim().to_owned()
        if !t.is_empty() && !t.has_prefix("#") && t != "|" {
          lines.push(t)
        }
        cur = tail
      }
    }
  }
  if lines.is_empty() {
    None
  } else {
    Some(lines.join(" "))
  }
}

///|
/// Counts `(` and `)` outside double-quoted string literals so multi-line attribute
/// scanning is not misled by regex patterns like `pattern="^(\\d+)$"`.
fn count_parens_outside_strings(s : String) -> (Int32, Int32) {
  let mut open_p = 0
  let mut close_p = 0
  let mut in_str = false
  let mut escaped = false
  for ch in s {
    if in_str {
      if escaped {
        escaped = false
      } else if ch == '\\' {
        escaped = true
      } else if ch == '"' {
        in_str = false
      }
    } else if ch == '"' {
      in_str = true
    } else if ch == '(' {
      open_p += 1
    } else if ch == ')' {
      close_p += 1
    }
  }
  (open_p, close_p)
}

///|
/// Unwraps `@schema.Nullable[T]` or `Nullable[T]` to `Some(inner_syntax_type)`.
fn unwrap_nullable_syntax_type(ty : @syntax.Type) -> @syntax.Type? {
  match ty {
    @syntax.Type::Name(constr_id~, tys~, ..) => {
      let is_nullable = match constr_id.id {
        @syntax.LongIdent::Ident(name="Nullable") => true
        @syntax.LongIdent::Dot(id="Nullable", ..) => true
        _ => false
      }
      if is_nullable {
        match tys {
          @list.List::More(inner, tail=@list.List::Empty) => Some(inner)
          _ => None
        }
      } else {
        None
      }
    }
    _ => None
  }
}

///|
/// Unwraps `Array[T]` to `Some(elem_type_str)`.
fn unwrap_array_type(ty : @syntax.Type) -> String? {
  match ty {
    @syntax.Type::Name(constr_id~, tys~, ..) =>
      match constr_id.id {
        @syntax.LongIdent::Ident(name="Array") =>
          match tys {
            @list.List::More(inner, tail=@list.List::Empty) =>
              Some(render_syntax_type(inner))
            _ => None
          }
        _ => None
      }
    _ => None
  }
}