///|
/// HCL Schema - type definitions for validation

///|
/// Schema for validating HCL values
///
/// ```mbt check
/// test {
///   assert_true(is_valid(hcl_int(42), TypeSchema::int()))
///   assert_true(is_valid(hcl_str("x"), TypeSchema::string()))
/// }
/// ```
pub(all) enum TypeSchema {
  /// Any value is accepted
  Any
  /// Null value
  NullSchema
  /// Boolean value
  BoolSchema
  /// Integer value
  IntSchema
  /// 64-bit integer
  Int64Schema
  /// Float value
  FloatSchema
  /// Number (int or float)
  NumberSchema
  /// String value
  StringSchema
  /// Array with element schema
  ArraySchema(TypeSchema)
  /// Object with field schemas
  ObjectSchema(Map[String, FieldSchema])
} derive(Debug, Eq)

///|
/// Schema for an object field
///
/// ```mbt check
/// test {
///   let f = FieldSchema::required(TypeSchema::int())
///   let s = TypeSchema::object({ "age": f })
///   assert_true(is_valid(hcl_object({ "age": hcl_int(1) }), s))
/// }
/// ```
pub struct FieldSchema {
  /// Field type schema
  schema : TypeSchema
  /// Whether field is required
  required : Bool
  /// Optional description
  description : String
} derive(Debug, Eq)

///|
/// Create a required field schema
///
/// ```mbt check
/// test {
///   let f = FieldSchema::required(TypeSchema::int())
///   assert_eq(is_valid(hcl_object({}), TypeSchema::object({ "age": f })), false)
/// }
/// ```
pub fn FieldSchema::required(schema : TypeSchema) -> FieldSchema {
  { schema, required: true, description: "" }
}

///|
/// Create an optional field schema
///
/// ```mbt check
/// test {
///   let f = FieldSchema::optional(TypeSchema::int())
///   assert_eq(is_valid(hcl_object({}), TypeSchema::object({ "age": f })), true)
/// }
/// ```
pub fn FieldSchema::optional(schema : TypeSchema) -> FieldSchema {
  { schema, required: false, description: "" }
}

///|
/// Create a field schema with description
///
/// ```mbt check
/// test {
///   let f = FieldSchema::optional(TypeSchema::int()).with_description(
///     "age in years",
///   )
///   let s = TypeSchema::object({ "age": f })
///   assert_true(is_valid(hcl_object({ "age": hcl_int(1) }), s))
/// }
/// ```
pub fn FieldSchema::with_description(
  self : FieldSchema,
  desc : String,
) -> FieldSchema {
  { ..self, description: desc }
}

///|
/// Schema for any value
///
/// ```mbt check
/// test {
///   assert_true(is_valid(hcl_int(1), TypeSchema::any()))
///   assert_true(is_valid(hcl_str("x"), TypeSchema::any()))
/// }
/// ```
pub fn TypeSchema::any() -> TypeSchema {
  Any
}

///|
/// Schema for null
///
/// ```mbt check
/// test {
///   assert_true(is_valid(hcl_null(), TypeSchema::null()))
///   assert_eq(is_valid(hcl_int(1), TypeSchema::null()), false)
/// }
/// ```
pub fn TypeSchema::null() -> TypeSchema {
  NullSchema
}

///|
/// Schema for boolean
///
/// ```mbt check
/// test {
///   assert_true(is_valid(hcl_bool(true), TypeSchema::bool()))
///   assert_eq(is_valid(hcl_int(1), TypeSchema::bool()), false)
/// }
/// ```
pub fn TypeSchema::bool() -> TypeSchema {
  BoolSchema
}

///|
/// Schema for integer
///
/// ```mbt check
/// test {
///   assert_true(is_valid(hcl_int(42), TypeSchema::int()))
///   assert_eq(is_valid(hcl_str("x"), TypeSchema::int()), false)
/// }
/// ```
pub fn TypeSchema::int() -> TypeSchema {
  IntSchema
}

///|
/// Schema for 64-bit integer
///
/// ```mbt check
/// test {
///   assert_true(is_valid(hcl_int64(42L), TypeSchema::int64()))
/// }
/// ```
pub fn TypeSchema::int64() -> TypeSchema {
  Int64Schema
}

///|
/// Schema for float
///
/// ```mbt check
/// test {
///   assert_true(is_valid(hcl_float(1.5), TypeSchema::float()))
///   assert_eq(is_valid(hcl_int(1), TypeSchema::float()), false)
/// }
/// ```
pub fn TypeSchema::float() -> TypeSchema {
  FloatSchema
}

///|
/// Schema for number (int or float)
///
/// ```mbt check
/// test {
///   assert_true(is_valid(hcl_int(1), TypeSchema::number()))
///   assert_true(is_valid(hcl_float(1.5), TypeSchema::number()))
///   assert_eq(is_valid(hcl_str("x"), TypeSchema::number()), false)
/// }
/// ```
pub fn TypeSchema::number() -> TypeSchema {
  NumberSchema
}

///|
/// Schema for string
///
/// ```mbt check
/// test {
///   assert_true(is_valid(hcl_str("x"), TypeSchema::string()))
///   assert_eq(is_valid(hcl_int(1), TypeSchema::string()), false)
/// }
/// ```
pub fn TypeSchema::string() -> TypeSchema {
  StringSchema
}

///|
/// Schema for array
///
/// ```mbt check
/// test {
///   let s = TypeSchema::array(TypeSchema::int())
///   assert_true(is_valid(hcl_array([hcl_int(1), hcl_int(2)]), s))
///   assert_eq(is_valid(hcl_array([hcl_str("x")]), s), false)
/// }
/// ```
pub fn TypeSchema::array(element : TypeSchema) -> TypeSchema {
  ArraySchema(element)
}

///|
/// Schema for object
///
/// ```mbt check
/// test {
///   let s = TypeSchema::object({
///     "name": FieldSchema::required(TypeSchema::string()),
///   })
///   assert_true(is_valid(hcl_object({ "name": hcl_str("x") }), s))
/// }
/// ```
pub fn TypeSchema::object(fields : Map[String, FieldSchema]) -> TypeSchema {
  ObjectSchema(fields)
}

///|
/// Validate a value against a schema
///
/// ```mbt check
/// test {
///   assert_eq(validate(hcl_int(1), TypeSchema::int()).length(), 0)
///   assert_eq(validate(hcl_str("x"), TypeSchema::int()).length(), 1)
/// }
/// ```
pub fn validate(value : HCLValue, schema : TypeSchema) -> Array[HCLError] {
  validate_at(value, schema, "$")
}

///|
/// Validate with path tracking
fn validate_at(
  value : HCLValue,
  schema : TypeSchema,
  path : String,
) -> Array[HCLError] {
  if value.is_unknown() {
    return []
  }
  match schema {
    Any => []
    NullSchema =>
      if value.is_null() {
        []
      } else {
        [HCLError::validation_error(path, "expected null")]
      }
    BoolSchema =>
      if value.is_bool() {
        []
      } else {
        [HCLError::validation_error(path, "expected bool")]
      }
    IntSchema =>
      match value {
        Number(n, _) =>
          if n.is_int() {
            []
          } else {
            [HCLError::validation_error(path, "expected int")]
          }
        _ => [HCLError::validation_error(path, "expected int")]
      }
    Int64Schema =>
      match value {
        Number(n, _) =>
          if n.is_int() {
            []
          } else {
            [HCLError::validation_error(path, "expected int64")]
          }
        _ => [HCLError::validation_error(path, "expected int64")]
      }
    FloatSchema =>
      match value {
        Number(n, _) =>
          if n.is_float() {
            []
          } else {
            [HCLError::validation_error(path, "expected float")]
          }
        _ => [HCLError::validation_error(path, "expected float")]
      }
    NumberSchema =>
      if value.is_number() {
        []
      } else {
        [HCLError::validation_error(path, "expected number")]
      }
    StringSchema =>
      if value.is_string() {
        []
      } else {
        [HCLError::validation_error(path, "expected string")]
      }
    ArraySchema(elem_schema) => validate_array(value, elem_schema, path)
    ObjectSchema(field_schemas) => validate_object(value, field_schemas, path)
  }
}

///|
/// Validate array value
fn validate_array(
  value : HCLValue,
  elem_schema : TypeSchema,
  path : String,
) -> Array[HCLError] {
  match value {
    Array(arr, _) => {
      let errors = []
      for i in 0.. [HCLError::validation_error(path, "expected array")]
  }
}

///|
/// Validate object value
fn validate_object(
  value : HCLValue,
  field_schemas : Map[String, FieldSchema],
  path : String,
) -> Array[HCLError] {
  match value {
    Object(obj, _) => {
      let errors = []
      for name, field_schema in field_schemas {
        let field_path = path + "." + name
        match obj.get(name) {
          Some(field_value) => {
            let field_errors = validate_at(
              field_value,
              field_schema.schema,
              field_path,
            )
            for e in field_errors {
              errors.push(e)
            }
          }
          None =>
            if field_schema.required {
              errors.push(
                HCLError::validation_error(field_path, "required field missing"),
              )
            }
        }
      }
      errors
    }
    _ => [HCLError::validation_error(path, "expected object")]
  }
}

///|
/// Validate and return first error, or Ok
///
/// ```mbt check
/// test {
///   assert_true(validate_one(hcl_int(1), TypeSchema::int()) is Ok(_))
///   assert_true(validate_one(hcl_str("x"), TypeSchema::int()) is Err(_))
/// }
/// ```
pub fn validate_one(value : HCLValue, schema : TypeSchema) -> HCLResult[Unit] {
  let errors = validate(value, schema)
  if errors.is_empty() {
    Ok(())
  } else {
    Err(errors[0])
  }
}

///|
/// Check if value is valid
///
/// ```mbt check
/// test {
///   assert_eq(is_valid(hcl_int(1), TypeSchema::int()), true)
///   assert_eq(is_valid(hcl_str("x"), TypeSchema::int()), false)
/// }
/// ```
pub fn is_valid(value : HCLValue, schema : TypeSchema) -> Bool {
  validate(value, schema).is_empty()
}

///|
/// Schema for extracting structured data from HCL Body
///
/// ```mbt check
/// test {
///   let s = BodySchema::new()
///   assert_eq(extract_body(Body::new(), s).unwrap().get_attr("x"), None)
/// }
/// ```
pub struct BodySchema {
  attrs : Map[String, AttrSchema]
  blocks : Map[String, BlockSchema]
  extra_attrs : Bool
  extra_blocks : Bool
} derive(Debug, Eq)

///|
/// Schema for a body attribute
///
/// ```mbt check
/// test {
///   let a = AttrSchema::required(TypeSchema::int())
///   let s = BodySchema::new().with_attrs({ "x": a })
///   assert_true(extract_body(parse("x = 1").unwrap(), s) is Ok(_))
/// }
/// ```
pub struct AttrSchema {
  required : Bool
  type_schema : TypeSchema
} derive(Debug, Eq)

///|
/// Schema for a body block
///
/// ```mbt check
/// test {
///   let bs = BlockSchema::new(BodySchema::new())
///   let s = BodySchema::new().with_blocks({ "server": bs })
///   assert_true(extract_body(parse("server {}\n").unwrap(), s) is Ok(_))
/// }
/// ```
pub struct BlockSchema {
  required : Bool
  max_items : Int?
  labels : Array[LabelSchema]
  body : BodySchema
} derive(Debug, Eq)

///|
/// Schema for a block label
///
/// ```mbt check
/// test {
///   let ls = LabelSchema::required()
///   let bs = BlockSchema::new(BodySchema::new()).with_labels([ls])
///   let s = BodySchema::new().with_blocks({ "server": bs })
///   assert_true(extract_body(parse("server \"web\" {}\n").unwrap(), s) is Ok(_))
/// }
/// ```
pub struct LabelSchema {
  required : Bool
} derive(Debug, Eq)

///|
/// Create an empty BodySchema
///
/// ```mbt check
/// test {
///   let s = BodySchema::new()
///   assert_true(extract_body(Body::new(), s) is Ok(_))
/// }
/// ```
pub fn BodySchema::new() -> BodySchema {
  { attrs: {}, blocks: {}, extra_attrs: false, extra_blocks: false }
}

///|
/// Set attribute schemas on a BodySchema
///
/// ```mbt check
/// test {
///   let s = BodySchema::new().with_attrs({
///     "name": AttrSchema::required(TypeSchema::string()),
///   })
///   let r = extract_body(parse("name = \"x\"").unwrap(), s)
///   assert_eq(r.unwrap().get_attr("name").unwrap().as_string().unwrap(), "x")
/// }
/// ```
pub fn BodySchema::with_attrs(
  self : BodySchema,
  attrs : Map[String, AttrSchema],
) -> BodySchema {
  { ..self, attrs, }
}

///|
/// Set block schemas on a BodySchema
///
/// ```mbt check
/// test {
///   let s = BodySchema::new().with_blocks({
///     "server": BlockSchema::new(BodySchema::new()),
///   })
///   let r = extract_body(parse("server {}\n").unwrap(), s)
///   assert_eq(r.unwrap().get_blocks("server").length(), 1)
/// }
/// ```
pub fn BodySchema::with_blocks(
  self : BodySchema,
  blocks : Map[String, BlockSchema],
) -> BodySchema {
  { ..self, blocks, }
}

///|
/// Create a required AttrSchema
///
/// ```mbt check
/// test {
///   let s = BodySchema::new().with_attrs({
///     "x": AttrSchema::required(TypeSchema::int()),
///   })
///   assert_true(extract_body(Body::new(), s) is Err(_))
/// }
/// ```
pub fn AttrSchema::required(type_schema : TypeSchema) -> AttrSchema {
  { required: true, type_schema }
}

///|
/// Create an optional AttrSchema
///
/// ```mbt check
/// test {
///   let s = BodySchema::new().with_attrs({
///     "x": AttrSchema::optional(TypeSchema::int()),
///   })
///   assert_true(extract_body(Body::new(), s) is Ok(_))
/// }
/// ```
pub fn AttrSchema::optional(type_schema : TypeSchema) -> AttrSchema {
  { required: false, type_schema }
}

///|
/// Create a new BlockSchema
///
/// ```mbt check
/// test {
///   let bs = BlockSchema::new(
///     BodySchema::new().with_attrs({
///       "port": AttrSchema::required(TypeSchema::int()),
///     }),
///   )
///   let s = BodySchema::new().with_blocks({ "server": bs })
///   assert_true(
///     extract_body(parse("server {\n  port = 80\n}\n").unwrap(), s) is Ok(_),
///   )
/// }
/// ```
pub fn BlockSchema::new(body : BodySchema) -> BlockSchema {
  { required: false, max_items: None, labels: [], body }
}

///|
/// Mark an existing block schema as required
///
/// ```mbt check
/// test {
///   let bs = BlockSchema::new(BodySchema::new()).mark_required()
///   let s = BodySchema::new().with_blocks({ "server": bs })
///   assert_true(extract_body(Body::new(), s) is Err(_))
/// }
/// ```
pub fn BlockSchema::mark_required(self : BlockSchema) -> BlockSchema {
  { ..self, required: true }
}

///|
/// Set max items for block
///
/// ```mbt check
/// test {
///   let bs = BlockSchema::new(BodySchema::new()).with_max_items(1)
///   let s = BodySchema::new().with_blocks({ "server": bs })
///   assert_true(
///     extract_body(parse("server {}\nserver {}\n").unwrap(), s) is Err(_),
///   )
/// }
/// ```
pub fn BlockSchema::with_max_items(
  self : BlockSchema,
  max : Int,
) -> BlockSchema {
  { ..self, max_items: Some(max) }
}

///|
/// Set labels for block
///
/// ```mbt check
/// test {
///   let bs = BlockSchema::new(BodySchema::new()).with_labels([
///     LabelSchema::required(),
///   ])
///   let s = BodySchema::new().with_blocks({ "server": bs })
///   assert_true(extract_body(parse("server \"web\" {}\n").unwrap(), s) is Ok(_))
/// }
/// ```
pub fn BlockSchema::with_labels(
  self : BlockSchema,
  labels : Array[LabelSchema],
) -> BlockSchema {
  { ..self, labels, }
}

///|
/// Create a required LabelSchema
///
/// ```mbt check
/// test {
///   let bs = BlockSchema::new(BodySchema::new()).with_labels([
///     LabelSchema::required(),
///   ])
///   let s = BodySchema::new().with_blocks({ "server": bs })
///   assert_true(extract_body(parse("server {}\n").unwrap(), s) is Err(_))
/// }
/// ```
pub fn LabelSchema::required() -> LabelSchema {
  { required: true }
}

///|
/// Create an optional LabelSchema
///
/// ```mbt check
/// test {
///   let bs = BlockSchema::new(BodySchema::new()).with_labels([
///     LabelSchema::optional(),
///   ])
///   let s = BodySchema::new().with_blocks({ "server": bs })
///   assert_true(extract_body(parse("server {}\n").unwrap(), s) is Ok(_))
/// }
/// ```
pub fn LabelSchema::optional() -> LabelSchema {
  { required: false }
}

///|
/// Custom validator function type
///
/// ```mbt check
/// test {
///   let v : Validator = fn(value, _path) {
///     match value.as_string() {
///       Some("") => [HCLError::validation_error("", "must not be empty")]
///       _ => []
///     }
///   }
///   assert_eq(v(hcl_str(""), "name").length(), 1)
/// }
/// ```
pub type Validator = (HCLValue, String) -> Array[HCLError]

///|
/// Extended field schema with custom validators
///
/// ```mbt check
/// test {
///   let fx = FieldSchemaEx::new(FieldSchema::required(TypeSchema::string()))
///   assert_eq(
///     validate_ex(hcl_object({ "name": hcl_str("x") }), { "name": fx }).length(),
///     0,
///   )
/// }
/// ```
pub struct FieldSchemaEx {
  /// Base field schema
  base : FieldSchema
  /// Custom validators
  validators : Array[Validator]
}

///|
/// Create extended field schema
///
/// ```mbt check
/// test {
///   let fx = FieldSchemaEx::new(FieldSchema::required(TypeSchema::int()))
///   assert_eq(
///     validate_ex(hcl_object({ "age": hcl_int(1) }), { "age": fx }).length(),
///     0,
///   )
/// }
/// ```
pub fn FieldSchemaEx::new(base : FieldSchema) -> FieldSchemaEx {
  { base, validators: [] }
}

///|
/// Add validator to field schema
///
/// ```mbt check
/// test {
///   let fx = FieldSchemaEx::new(FieldSchema::required(TypeSchema::string())).add_validator(
///     string_not_empty(),
///   )
///   assert_eq(
///     validate_ex(hcl_object({ "name": hcl_str("") }), { "name": fx }).length(),
///     1,
///   )
/// }
/// ```
pub fn FieldSchemaEx::add_validator(
  self : FieldSchemaEx,
  v : Validator,
) -> FieldSchemaEx {
  let vs = self.validators.copy()
  vs.push(v)
  { ..self, validators: vs }
}

///|
/// Validate with custom validators
///
/// ```mbt check
/// test {
///   let fx = FieldSchemaEx::new(FieldSchema::required(TypeSchema::int())).add_validator(
///     int_in_range(0, 10),
///   )
///   assert_eq(
///     validate_ex(hcl_object({ "age": hcl_int(5) }), { "age": fx }).length(),
///     0,
///   )
///   assert_eq(
///     validate_ex(hcl_object({ "age": hcl_int(99) }), { "age": fx }).length(),
///     1,
///   )
/// }
/// ```
pub fn validate_ex(
  value : HCLValue,
  schema : Map[String, FieldSchemaEx],
) -> Array[HCLError] {
  validate_object_ex(value, schema, "$")
}

///|
/// Validate object with extended field schemas
fn validate_object_ex(
  value : HCLValue,
  field_schemas : Map[String, FieldSchemaEx],
  path : String,
) -> Array[HCLError] {
  match value {
    Object(obj, _) => {
      let errors = []
      for name, field_schema in field_schemas {
        let field_path = path + "." + name
        match obj.get(name) {
          Some(field_value) => {
            // Base validation
            let base_errors = validate_at(
              field_value,
              field_schema.base.schema,
              field_path,
            )
            for e in base_errors {
              errors.push(e)
            }
            // Custom validators
            for v in field_schema.validators {
              let custom_errors = v(field_value, field_path)
              for e in custom_errors {
                errors.push(e)
              }
            }
          }
          None =>
            if field_schema.base.required {
              errors.push(
                HCLError::validation_error(field_path, "required field missing"),
              )
            }
        }
      }
      errors
    }
    _ => [HCLError::validation_error(path, "expected object")]
  }
}

///|
/// Validator: string not empty
///
/// ```mbt check
/// test {
///   let v = string_not_empty()
///   assert_eq(v(hcl_str("x"), "name").length(), 0)
///   assert_eq(v(hcl_str(""), "name").length(), 1)
/// }
/// ```
pub fn string_not_empty() -> Validator {
  fn(value, path) {
    match value {
      String(s, _) if s.is_empty() =>
        [HCLError::validation_error(path, "string must not be empty")]
      _ => []
    }
  }
}

///|
/// Validator: int in range
///
/// ```mbt check
/// test {
///   let v = int_in_range(0, 150)
///   assert_eq(v(hcl_int(25), "age").length(), 0)
///   assert_eq(v(hcl_int(200), "age").length(), 1)
/// }
/// ```
pub fn int_in_range(min : Int, max : Int) -> Validator {
  fn(value, path) {
    match value {
      Number(n, _) =>
        match n.as_int() {
          Some(i) if i < min || i > max =>
            [
              HCLError::validation_error(
                path,
                "value " +
                i.to_string() +
                " not in range [" +
                min.to_string() +
                ", " +
                max.to_string() +
                "]",
              ),
            ]
          _ => []
        }
      _ => []
    }
  }
}

///|
/// Validator: string matches pattern (simple prefix/suffix check)
///
/// ```mbt check
/// test {
///   let v = string_starts_with("usr_")
///   assert_eq(v(hcl_str("usr_1"), "id").length(), 0)
///   assert_eq(v(hcl_str("abc"), "id").length(), 1)
/// }
/// ```
pub fn string_starts_with(prefix : String) -> Validator {
  fn(value, path) {
    match value {
      String(s, _) if !s.has_prefix(prefix) =>
        [HCLError::validation_error(path, "string must start with " + prefix)]
      _ => []
    }
  }
}

///|
/// Result of extracting structured data from an HCL Body using a BodySchema
///
/// ```mbt check
/// test {
///   let r = extract_body(
///     parse("name = \"x\"\n").unwrap(),
///     BodySchema::new().with_attrs({
///       "name": AttrSchema::required(TypeSchema::string()),
///     }),
///   ).unwrap()
///   assert_eq(r.get_attr("name").unwrap().as_string().unwrap(), "x")
/// }
/// ```
pub struct ExtractedBody {
  attrs : Map[String, HCLValue]
  blocks : Map[String, Array[ExtractedBlock]]
  extra_blocks : Array[ExtractedBlock]
} derive(Debug, Eq)

///|
/// A single extracted block with its labels and nested body
///
/// ```mbt check
/// test {
///   let e = extract_body(
///     parse("server \"web\" {}\n").unwrap(),
///     BodySchema::new().with_blocks({
///       "server": BlockSchema::new(BodySchema::new()).with_labels([
///         LabelSchema::required(),
///       ]),
///     }),
///   ).unwrap()
///   assert_eq(e.get_blocks("server")[0].get_label(0), Some("web"))
/// }
/// ```
pub struct ExtractedBlock {
  labels : Array[String]
  body : ExtractedBody
} derive(Debug, Eq)

///|
/// Create an empty ExtractedBody
///
/// ```mbt check
/// test {
///   let e = ExtractedBody::new()
///   assert_eq(e.get_attr("x"), None)
///   assert_eq(e.get_blocks("x").length(), 0)
/// }
/// ```
pub fn ExtractedBody::new() -> ExtractedBody {
  { attrs: {}, blocks: {}, extra_blocks: [] }
}

///|
/// Get all extra blocks (unknown blocks when extra_blocks=true)
///
/// ```mbt check
/// test {
///   let e = extract_body(
///     parse("server {}\n").unwrap(),
///     BodySchema::new().with_blocks({
///       "server": BlockSchema::new(BodySchema::new()),
///     }),
///   ).unwrap()
///   assert_eq(e.get_extra_blocks().length(), 0)
/// }
/// ```
pub fn ExtractedBody::get_extra_blocks(
  self : ExtractedBody,
) -> Array[ExtractedBlock] {
  self.extra_blocks
}

///|
/// Get an attribute value by key
///
/// ```mbt check
/// test {
///   let e = extract_body(
///     parse("a = 1\n").unwrap(),
///     BodySchema::new().with_attrs({
///       "a": AttrSchema::required(TypeSchema::int()),
///     }),
///   ).unwrap()
///   assert_eq(e.get_attr("a").unwrap().as_int().unwrap(), 1)
/// }
/// ```
pub fn ExtractedBody::get_attr(self : ExtractedBody, key : String) -> HCLValue? {
  self.attrs.get(key)
}

///|
/// Get all blocks of a given type name
///
/// ```mbt check
/// test {
///   let e = extract_body(
///     parse("server {}\nserver {}\n").unwrap(),
///     BodySchema::new().with_blocks({
///       "server": BlockSchema::new(BodySchema::new()),
///     }),
///   ).unwrap()
///   assert_eq(e.get_blocks("server").length(), 2)
/// }
/// ```
pub fn ExtractedBody::get_blocks(
  self : ExtractedBody,
  type_name : String,
) -> Array[ExtractedBlock] {
  match self.blocks.get(type_name) {
    Some(blocks) => blocks
    None => []
  }
}

///|
/// Get the first block of a given type name
///
/// ```mbt check
/// test {
///   let e = extract_body(
///     parse("server {}\n").unwrap(),
///     BodySchema::new().with_blocks({
///       "server": BlockSchema::new(BodySchema::new()),
///     }),
///   ).unwrap()
///   assert_true(e.get_block("server") is Some(_))
///   assert_eq(e.get_block("other"), None)
/// }
/// ```
pub fn ExtractedBody::get_block(
  self : ExtractedBody,
  type_name : String,
) -> ExtractedBlock? {
  match self.blocks.get(type_name) {
    Some(blocks) if blocks.length() > 0 => Some(blocks[0])
    _ => None
  }
}

///|
/// Get a label by index from a block
///
/// ```mbt check
/// test {
///   let e = extract_body(
///     parse("server \"web\" \"prod\" {}\n").unwrap(),
///     BodySchema::new().with_blocks({
///       "server": BlockSchema::new(BodySchema::new()).with_labels([
///         LabelSchema::required(),
///         LabelSchema::required(),
///       ]),
///     }),
///   ).unwrap()
///   assert_eq(e.get_blocks("server")[0].get_label(0), Some("web"))
///   assert_eq(e.get_blocks("server")[0].get_label(1), Some("prod"))
/// }
/// ```
pub fn ExtractedBlock::get_label(self : ExtractedBlock, index : Int) -> String? {
  if index >= 0 && index < self.labels.length() {
    Some(self.labels[index])
  } else {
    None
  }
}

///|
/// Validate block labels against label schemas
fn validate_labels(
  labels : Array[String],
  label_schemas : Array[LabelSchema],
  path : String,
) -> Array[HCLError] {
  let errors = []
  for i in 0..= labels.length() {
      errors.push(
        HCLError::validation_error(
          path + "[" + i.to_string() + "]",
          "required label missing",
        ),
      )
    }
  }
  if labels.length() > label_schemas.length() {
    errors.push(
      HCLError::validation_error(
        path,
        "unexpected labels (got " +
        labels.length().to_string() +
        ", expected at most " +
        label_schemas.length().to_string() +
        ")",
      ),
    )
  }
  errors
}

///|
/// Extract structured data from an HCL Body using a BodySchema
///
/// ```mbt check
/// test {
///   let body = parse("name = \"test\"\ncount = 42\n").unwrap()
///   let schema = BodySchema::new().with_attrs({
///     "name": AttrSchema::required(TypeSchema::string()),
///     "count": AttrSchema::required(TypeSchema::int()),
///   })
///   let extracted = extract_body(body, schema).unwrap()
///   assert_eq(extracted.get_attr("name").unwrap().as_string().unwrap(), "test")
///   assert_eq(extracted.get_attr("count").unwrap().as_int().unwrap(), 42)
/// }
/// ```
pub fn extract_body(
  body : Body,
  schema : BodySchema,
) -> Result[ExtractedBody, Array[HCLError]] {
  extract_body_with_prefix(body, schema, "$")
}

///|
/// Extract structured data with a custom path prefix for error reporting
fn extract_body_with_prefix(
  body : Body,
  schema : BodySchema,
  path_prefix : String,
) -> Result[ExtractedBody, Array[HCLError]] {
  let errors = []
  let attrs : Map[String, HCLValue] = Map([])
  let blocks : Map[String, Array[ExtractedBlock]] = Map([])
  let extra_blocks : Array[ExtractedBlock] = []

  for item in body.get_items() {
    match item {
      Attribute(attr) => {
        let key = attr.get_key()
        match schema.attrs.get(key) {
          Some(attr_schema) => {
            let value = expr_to_hcl_value(attr.get_value())
            let validation_errors = validate_at(
              value,
              attr_schema.type_schema,
              path_prefix + "." + key,
            )
            for e in validation_errors {
              errors.push(e)
            }
            attrs[key] = value
          }
          None => {
            if !schema.extra_attrs {
              errors.push(
                HCLError::validation_error(
                  path_prefix + "." + key,
                  "unexpected attribute",
                ),
              )
            }
            attrs[key] = expr_to_hcl_value(attr.get_value())
          }
        }
      }
      Block(block) => {
        let type_name = block.get_type_name()
        match schema.blocks.get(type_name) {
          Some(block_schema) => {
            let block_path = path_prefix + "." + type_name
            let labels = block.get_labels()
            let label_errors = validate_labels(
              labels,
              block_schema.labels,
              block_path,
            )
            for e in label_errors {
              errors.push(e)
            }
            match
              extract_body_with_prefix(
                block.get_body(),
                block_schema.body,
                block_path,
              ) {
              Ok(nested_body) => {
                let extracted = { labels, body: nested_body }
                match blocks.get(type_name) {
                  Some(arr) => {
                    let new_arr = arr.copy()
                    new_arr.push(extracted)
                    blocks[type_name] = new_arr
                  }
                  None => blocks[type_name] = [extracted]
                }
              }
              Err(nested_errors) =>
                for e in nested_errors {
                  errors.push(e)
                }
            }
          }
          None =>
            if !schema.extra_blocks {
              errors.push(
                HCLError::validation_error(
                  path_prefix + "." + type_name,
                  "unexpected block",
                ),
              )
            } else {
              let block_path = path_prefix + "." + type_name
              match
                extract_body_with_prefix(
                  block.get_body(),
                  BodySchema::new(),
                  block_path,
                ) {
                Ok(nested_body) =>
                  extra_blocks.push({
                    labels: block.get_labels(),
                    body: nested_body,
                  })
                Err(nested_errors) =>
                  for e in nested_errors {
                    errors.push(e)
                  }
              }
            }
        }
      }
    }
  }

  for key, attr_schema in schema.attrs {
    if attr_schema.required {
      match attrs.get(key) {
        None =>
          errors.push(
            HCLError::validation_error(
              path_prefix + "." + key,
              "required attribute missing",
            ),
          )
        Some(_) => ()
      }
    }
  }

  for type_name, block_schema in schema.blocks {
    if block_schema.required {
      match blocks.get(type_name) {
        None =>
          errors.push(
            HCLError::validation_error(
              path_prefix + "." + type_name,
              "required block missing",
            ),
          )
        Some(_) => ()
      }
    }
    match block_schema.max_items {
      Some(max) =>
        match blocks.get(type_name) {
          Some(arr) =>
            if arr.length() > max {
              errors.push(
                HCLError::validation_error(
                  path_prefix + "." + type_name,
                  "expected at most " +
                  max.to_string() +
                  " blocks, got " +
                  arr.length().to_string(),
                ),
              )
            }
          None => ()
        }
      None => ()
    }
  }

  if errors.is_empty() {
    Ok({ attrs, blocks, extra_blocks })
  } else {
    Err(errors)
  }
}