///|
/// HCL Deserialization - convert HCL to MoonBit types

///|
/// Deserialize from HCL string to Int
///
/// ```mbt check
/// test {
///   assert_eq(from_hcl_int("x = 42").unwrap(), 42)
/// }
/// ```
pub fn from_hcl_int(input : String) -> Result[Int, HCLError] {
  match parse(input) {
    Ok(body) => {
      let value = body_to_single_value(body)
      match value {
        Number(n, _) =>
          match n.as_int() {
            Some(i) => Ok(i)
            None =>
              Err(HCLError::type_mismatch("Int", value_to_type_name(value)))
          }
        _ => Err(HCLError::type_mismatch("Int", value_to_type_name(value)))
      }
    }
    Err(e) => Err(e)
  }
}

///|
/// Deserialize from HCL string to String
///
/// ```mbt check
/// test {
///   assert_eq(from_hcl_string("x = \"hi\"").unwrap(), "hi")
/// }
/// ```
pub fn from_hcl_string(input : String) -> Result[String, HCLError] {
  match parse(input) {
    Ok(body) => {
      let value = body_to_single_value(body)
      match value {
        String(s, _) => Ok(s)
        _ => Err(HCLError::type_mismatch("String", value_to_type_name(value)))
      }
    }
    Err(e) => Err(e)
  }
}

///|
/// Deserialize from HCL string to Bool
///
/// ```mbt check
/// test {
///   assert_eq(from_hcl_bool("x = true").unwrap(), true)
/// }
/// ```
pub fn from_hcl_bool(input : String) -> Result[Bool, HCLError] {
  match parse(input) {
    Ok(body) => {
      let value = body_to_single_value(body)
      match value {
        Bool(b, _) => Ok(b)
        _ => Err(HCLError::type_mismatch("Bool", value_to_type_name(value)))
      }
    }
    Err(e) => Err(e)
  }
}

///|
/// Deserialize from HCL string to HCLValue
///
/// ```mbt check
/// test {
///   let v = from_hcl_value("x = 1").unwrap()
///   assert_eq(v.as_object().unwrap()["x"].as_int().unwrap(), 1)
/// }
/// ```
pub fn from_hcl_value(input : String) -> Result[HCLValue, HCLError] {
  match parse(input) {
    Ok(body) => Ok(body_to_value(body))
    Err(e) => Err(e)
  }
}

///|
/// Deserialize from HCL string to Body
///
/// ```mbt check
/// test {
///   let body = from_hcl_body("x = 1").unwrap()
///   assert_eq(body.len(), 1)
/// }
/// ```
pub fn from_hcl_body(input : String) -> Result[Body, HCLError] {
  parse(input)
}

///|
/// Convert Body to HCLValue
fn body_to_value(body : Body) -> HCLValue {
  let obj = Map([])
  for item in body.get_items() {
    match item {
      Attribute(attr) =>
        obj[attr.get_key()] = expr_to_hcl_value(attr.get_value())
      Block(block) => {
        let block_obj = body_to_value(block.get_body())
        obj[block.get_type_name()] = block_obj
      }
    }
  }
  Object(obj, Decor::empty())
}

///|
/// Convert Body to HCLValue; a single-attribute body yields that attribute's
/// value, otherwise the whole body is converted to an object
fn body_to_single_value(body : Body) -> HCLValue {
  let items = body.get_items()
  if items.length() == 1 {
    match items[0] {
      Attribute(attr) => expr_to_hcl_value(attr.get_value())
      Block(_) => body_to_value(body)
    }
  } else {
    body_to_value(body)
  }
}

///|
/// Deserialize HCL with schema validation
///
/// ```mbt check
/// test {
///   let schema = TypeSchema::object({
///     "x": FieldSchema::required(TypeSchema::int()),
///   })
///   assert_true(from_hcl_with_schema("x = 1", schema) is Ok(_))
///   let bad = TypeSchema::object({
///     "x": FieldSchema::required(TypeSchema::string()),
///   })
///   assert_true(from_hcl_with_schema("x = 1", bad) is Err(_))
/// }
/// ```
pub fn from_hcl_with_schema(
  input : String,
  schema : TypeSchema,
) -> HCLResult[HCLValue] {
  match parse(input) {
    Ok(body) => {
      let value = body_to_value(body)
      let errors = validate(value, schema)
      if errors.is_empty() {
        Ok(value)
      } else {
        Err(errors[0])
      }
    }
    Err(e) => Err(e)
  }
}

///|
/// Deserialize HCL with schema, return all errors
///
/// ```mbt check
/// test {
///   let schema = TypeSchema::object({
///     "x": FieldSchema::required(TypeSchema::int()),
///   })
///   match from_hcl_with_schema_full("x = \"no\"", schema) {
///     Err(errs) => assert_eq(errs.length(), 1)
///     Ok(_) => panic()
///   }
/// }
/// ```
pub fn from_hcl_with_schema_full(
  input : String,
  schema : TypeSchema,
) -> Result[HCLValue, Array[HCLError]] {
  match parse(input) {
    Ok(body) => {
      let value = body_to_value(body)
      let errors = validate(value, schema)
      if errors.is_empty() {
        Ok(value)
      } else {
        Err(errors)
      }
    }
    Err(e) => Err([e])
  }
}

///|
/// Deserialize from HCL string using a BodySchema, returning ExtractedBody
///
/// ```mbt check
/// test {
///   let schema = BodySchema::new().with_attrs({
///     "x": AttrSchema::required(TypeSchema::int()),
///   })
///   let r = from_hcl_with_body_schema("x = 42", schema)
///   assert_true(r is Ok(_))
///   assert_eq(r.unwrap().get_attr("x").unwrap().as_int().unwrap(), 42)
/// }
/// ```
pub fn from_hcl_with_body_schema(
  input : String,
  schema : BodySchema,
) -> Result[ExtractedBody, Array[HCLError]] {
  match parse(input) {
    Ok(body) => extract_body(body, schema)
    Err(e) => Err([e])
  }
}

///|
/// Get type name for error messages
fn value_to_type_name(value : HCLValue) -> String {
  match value {
    Null(_) => "null"
    Bool(_, _) => "bool"
    Number(_, _) => "number"
    String(_, _) => "string"
    Array(_, _) => "array"
    Object(_, _) => "object"
    Unknown(_) => "unknown"
  }
}

///|
/// Decode a required attribute from a Body into a typed value
///
/// ```mbt check
/// test {
///   let body = parse("port = 8080").unwrap()
///   let port : Int = decode_attr(body, "port").unwrap()
///   assert_eq(port, 8080)
/// }
/// ```
pub fn[T : FromHCL] decode_attr(body : Body, key : String) -> HCLResult[T] {
  match body.find_attr(key) {
    Some(attr) => T::from_hcl(expr_to_hcl_value(attr.get_value()))
    None => Err(HCLError::missing_field(key))
  }
}

///|
/// Decode an optional attribute from a Body (None when absent)
///
/// ```mbt check
/// test {
///   let body = parse("port = 8080").unwrap()
///   let port : Int? = decode_opt_attr(body, "port").unwrap()
///   let missing : Int? = decode_opt_attr(body, "host").unwrap()
///   assert_eq(port, Some(8080))
///   assert_eq(missing, None)
/// }
/// ```
pub fn[T : FromHCL] decode_opt_attr(body : Body, key : String) -> HCLResult[T?] {
  match body.find_attr(key) {
    Some(attr) =>
      match expr_to_hcl_value(attr.get_value()) {
        // a null value is treated as absent (kdl decode_opt_prop semantics)
        Null(_) => Ok(None)
        value =>
          match T::from_hcl(value) {
            Ok(v) => Ok(Some(v))
            Err(e) => Err(e)
          }
      }
    None => Ok(None)
  }
}

///|
/// Decode the body of a required block into a typed value
///
/// ```mbt check
/// test {
///   let body = parse("server {\n  port = 8080\n}").unwrap()
///   let cfg : Map[String, Int] = decode_block(body, "server").unwrap()
///   assert_eq(cfg["port"], 8080)
/// }
/// ```
pub fn[T : FromHCL] decode_block(
  body : Body,
  type_name : String,
) -> HCLResult[T] {
  match body.find_block(type_name) {
    Some(block) => T::from_hcl(body_to_value(block.get_body()))
    None => Err(HCLError::missing_field(type_name))
  }
}

///|
/// Decode the body of an optional block (None when absent)
///
/// ```mbt check
/// test {
///   let body = parse("server {\n  port = 8080\n}").unwrap()
///   let cfg : Map[String, Int]? = decode_opt_block(body, "server").unwrap()
///   let missing : Map[String, Int]? = decode_opt_block(body, "db").unwrap()
///   assert_true(cfg is Some(_))
///   assert_eq(missing, None)
/// }
/// ```
pub fn[T : FromHCL] decode_opt_block(
  body : Body,
  type_name : String,
) -> HCLResult[T?] {
  match body.find_block(type_name) {
    Some(block) =>
      match T::from_hcl(body_to_value(block.get_body())) {
        Ok(v) => Ok(Some(v))
        Err(e) => Err(e)
      }
    None => Ok(None)
  }
}

///|
/// Decode every block of a type into an array of typed values
///
/// ```mbt check
/// test {
///   let body = parse("server {\n  port = 8080\n}\nserver {\n  port = 3000\n}").unwrap()
///   let cfgs : Array[Map[String, Int]] = decode_blocks(body, "server").unwrap()
///   assert_eq(cfgs.length(), 2)
///   assert_eq(cfgs[0]["port"], 8080)
///   assert_eq(cfgs[1]["port"], 3000)
/// }
/// ```
pub fn[T : FromHCL] decode_blocks(
  body : Body,
  type_name : String,
) -> HCLResult[Array[T]] {
  let result = []
  for block in body.find_blocks(type_name) {
    match T::from_hcl(body_to_value(block.get_body())) {
      Ok(v) => result.push(v)
      Err(e) => return Err(e)
    }
  }
  Ok(result)
}