///|
/// Trait for converting MoonBit types to HCLValue
///
/// ```mbt check
/// test {
///   assert_eq(to_hcl_str(42), "42")
///   assert_eq(to_hcl_str("hi"), "\"hi\"")
/// }
/// ```
pub trait ToHCL {
  fn to_hcl(Self) -> HCLValue
}

///|
/// Trait for converting HCLValue to MoonBit types
///
/// ```mbt check
/// test {
///   let r : HCLResult[Map[String, Int]] = from_hcl_str("a = 1")
///   assert_eq(r.unwrap()["a"], 1)
/// }
/// ```
pub trait FromHCL {
  fn from_hcl(HCLValue) -> HCLResult[Self]
}

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

///|
/// Convert any ToHCL type to HCL string
///
/// ```mbt check
/// test {
///   assert_eq(to_hcl_str(42), "42")
///   assert_eq(to_hcl_str(true), "true")
///   assert_true(to_hcl_str([1, 2]).contains("1"))
/// }
/// ```
pub fn[T : ToHCL] to_hcl_str(value : T) -> String {
  format_hcl_value(value.to_hcl(), 0)
}

///|
/// Parse HCL string to any FromHCL type
///
/// ```mbt check
/// test {
///   let r : HCLResult[Map[String, Int]] = from_hcl_str("a = 1")
///   assert_eq(r.unwrap()["a"], 1)
/// }
/// ```
pub fn[T : FromHCL] from_hcl_str(input : String) -> HCLResult[T] {
  match parse(input) {
    Ok(body) => T::from_hcl(body_to_value(body))
    Err(e) => Err(e)
  }
}

///|
/// ToHCL implementation for HCLValue (identity)
pub impl ToHCL for HCLValue with fn to_hcl(self) {
  self
}

///|
/// FromHCL implementation for HCLValue (identity)
pub impl FromHCL for HCLValue with fn from_hcl(value) {
  Ok(value)
}

///|
/// ToHCL implementation for Int
pub impl ToHCL for Int with fn to_hcl(self) {
  Number(Number::from_int(self), Decor::empty())
}

///|
/// FromHCL implementation for Int
pub impl FromHCL for Int with fn from_hcl(value) {
  match value {
    Number(n, _) =>
      match n.as_int() {
        Some(i) => Ok(i)
        None => Err(HCLError::type_mismatch("Int", type_name_of(value)))
      }
    _ => Err(HCLError::type_mismatch("Int", type_name_of(value)))
  }
}

///|
/// ToHCL implementation for Int64
pub impl ToHCL for Int64 with fn to_hcl(self) {
  Number(Number::from_int64(self), Decor::empty())
}

///|
/// FromHCL implementation for Int64
pub impl FromHCL for Int64 with fn from_hcl(value) {
  match value {
    Number(n, _) =>
      match n.as_int64() {
        Some(i) => Ok(i)
        None => Err(HCLError::type_mismatch("Int64", type_name_of(value)))
      }
    _ => Err(HCLError::type_mismatch("Int64", type_name_of(value)))
  }
}

///|
/// ToHCL implementation for Double
pub impl ToHCL for Double with fn to_hcl(self) {
  Number(Number::from_finite_f64(self), Decor::empty())
}

///|
/// FromHCL implementation for Double
pub impl FromHCL for Double with fn from_hcl(value) {
  match value {
    Number(n, _) => Ok(n.as_float())
    _ => Err(HCLError::type_mismatch("Double", type_name_of(value)))
  }
}

///|
/// ToHCL implementation for Bool
pub impl ToHCL for Bool with fn to_hcl(self) {
  Bool(self, Decor::empty())
}

///|
/// FromHCL implementation for Bool
pub impl FromHCL for Bool with fn from_hcl(value) {
  match value {
    Bool(b, _) => Ok(b)
    _ => Err(HCLError::type_mismatch("Bool", type_name_of(value)))
  }
}

///|
/// ToHCL implementation for String
pub impl ToHCL for String with fn to_hcl(self) {
  String(self, Decor::empty())
}

///|
/// FromHCL implementation for String
pub impl FromHCL for String with fn from_hcl(value) {
  match value {
    String(s, _) => Ok(s)
    _ => Err(HCLError::type_mismatch("String", type_name_of(value)))
  }
}

///|
/// ToHCL implementation for Option
pub impl[T : ToHCL] ToHCL for T? with fn to_hcl(self) {
  match self {
    Some(v) => v.to_hcl()
    None => Null(Decor::empty())
  }
}

///|
/// FromHCL implementation for Option
pub impl[T : FromHCL] FromHCL for T? with fn from_hcl(value) {
  match value {
    Null(_) => Ok(None)
    _ =>
      match T::from_hcl(value) {
        Ok(v) => Ok(Some(v))
        Err(e) => Err(e)
      }
  }
}

///|
/// ToHCL implementation for Array
pub impl[T : ToHCL] ToHCL for Array[T] with fn to_hcl(self) {
  let items = self.map(fn(v) { v.to_hcl() })
  Array(items, Decor::empty())
}

///|
/// FromHCL implementation for Array
pub impl[T : FromHCL] FromHCL for Array[T] with fn from_hcl(value) {
  match value {
    Array(arr, _) => {
      let result = []
      for v in arr {
        match T::from_hcl(v) {
          Ok(item) => result.push(item)
          Err(e) => return Err(e)
        }
      }
      Ok(result)
    }
    _ => Err(HCLError::type_mismatch("Array", type_name_of(value)))
  }
}

///|
/// ToHCL implementation for Map
pub impl[T : ToHCL] ToHCL for Map[String, T] with fn to_hcl(self) {
  let obj = Map([])
  for k, v in self {
    obj[k] = v.to_hcl()
  }
  Object(obj, Decor::empty())
}

///|
/// FromHCL implementation for Map
pub impl[T : FromHCL] FromHCL for Map[String, T] with fn from_hcl(value) {
  match value {
    Object(obj, _) => {
      let result = Map([])
      for k, v in obj {
        match T::from_hcl(v) {
          Ok(item) => result[k] = item
          Err(e) => return Err(e)
        }
      }
      Ok(result)
    }
    _ => Err(HCLError::type_mismatch("Object", type_name_of(value)))
  }
}