///|
/// HCL Expression types - represents the expression sub-language
/// Based on hcl-rs design: https://github.com/nickelchenwealth/hcl-rs

///|
/// Object key type - can be identifier or expression
///
/// ```mbt check
/// test {
///   assert_eq(ObjectKey::Identifier("x").to_string(), "x")
///   assert_eq(ObjectKey::Expression(expr_int(1)).to_string(), "1")
/// }
/// ```
pub(all) enum ObjectKey {
  /// Unquoted identifier used as object key
  Identifier(String)
  /// Any valid HCL expression can be an object key
  Expression(Expression)
} derive(Debug, Eq)

///|
/// Object type for expressions (preserves insertion order via array of pairs)
///
/// ```mbt check
/// test {
///   let pairs : ExprObject = [(ObjectKey::Identifier("a"), expr_int(1))]
///   assert_eq(expr_to_string(Expression::ExprObject(pairs)), "{ a = 1 }")
/// }
/// ```
pub type ExprObject = Array[(ObjectKey, Expression)]

///|
/// Represents an HCL expression
///
/// ```mbt check
/// test {
///   assert_eq(expr_to_string(expr_int(1)), "1")
///   assert_eq(expr_to_string(expr_array([expr_int(1), expr_int(2)])), "[1, 2]")
/// }
/// ```
pub(all) enum Expression {
  /// Null value
  ExprNull
  /// Boolean value
  ExprBool(Bool)
  /// Number (int)
  ExprInt(Int)
  /// 64-bit integer
  ExprInt64(Int64)
  /// Floating point number
  ExprFloat(Double)
  /// String without template interpolations
  ExprString(String)
  /// Array of expressions
  ExprArray(Array[Expression])
  /// Object (key-value pairs)
  ExprObject(ExprObject)
  /// Template expression (string with interpolations or heredoc)
  ExprTemplate(TemplateExpr)
  /// Variable reference
  ExprVariable(Variable)
  /// Property/element traversal
  ExprTraversal(Traversal)
  /// Function call
  ExprFuncCall(FuncCall)
  /// Parenthesized expression
  ExprParenthesis(Expression)
  /// Conditional expression (cond ? true_expr : false_expr)
  ExprConditional(Conditional)
  /// Binary or unary operation
  ExprOperation(Operation)
  /// For expression (list/object comprehension)
  ExprFor(ForExpr)
  /// Unknown value (Terraform plan-stage)
  ExprUnknown
} derive(Debug, Eq)

///|
/// Template expression (heredoc or interpolated string)
///
/// ```mbt check
/// test {
///   let h : Heredoc = {
///     delimiter: "EOT",
///     content: "hi\n",
///     strip_mode: HeredocStripMode::NoStrip,
///   }
///   match TemplateExpr::Heredoc(h) {
///     TemplateExpr::Heredoc(inner) => assert_eq(inner.content, "hi\n")
///     _ => panic()
///   }
/// }
/// ```
pub(all) enum TemplateExpr {
  /// Heredoc template
  Heredoc(Heredoc)
  /// Interpolated string template
  InterpolatedString(String)
} derive(Debug, Eq)

///|
/// Heredoc template
///
/// ```mbt check
/// test {
///   let h : Heredoc = {
///     delimiter: "EOT",
///     content: "hi\n",
///     strip_mode: HeredocStripMode::NoStrip,
///   }
///   assert_eq(h.delimiter, "EOT")
///   assert_eq(h.content, "hi\n")
/// }
/// ```
pub(all) struct Heredoc {
  /// Delimiter (e.g., "EOF")
  delimiter : String
  /// Template content
  content : String
  /// Strip indentation mode
  strip_mode : HeredocStripMode
} derive(Debug, Eq)

///|
/// Heredoc strip mode
///
/// ```mbt check
/// test {
///   let h : Heredoc = {
///     delimiter: "EOT",
///     content: "  hi\n",
///     strip_mode: HeredocStripMode::StripMode,
///   }
///   assert_eq(h.strip_mode, HeredocStripMode::StripMode)
///   let h2 : Heredoc = {
///     delimiter: "EOT",
///     content: "hi\n",
///     strip_mode: HeredocStripMode::NoStrip,
///   }
///   assert_eq(h2.strip_mode, HeredocStripMode::NoStrip)
/// }
/// ```
pub(all) enum HeredocStripMode {
  /// No stripping
  NoStrip
  /// Strip leading whitespace (<<-EOF)
  StripMode
} derive(Debug, Eq)

///|
/// Variable reference
///
/// ```mbt check
/// test {
///   let e = parse("v = x").unwrap().find_attr("v").unwrap().get_value()
///   match e {
///     Expression::ExprVariable(_) => ()
///     _ => panic()
///   }
/// }
/// ```
pub(all) struct Variable {
  /// Variable name
  name : String
} derive(Debug, Eq)

///|
/// Traversal (property/element access)
///
/// ```mbt check
/// test {
///   let t = TraversalBuilder::new(expr_str("obj")).attr("key").build()
///   assert_eq(expr_to_string(Expression::ExprTraversal(t)), "\"obj\".key")
/// }
/// ```
pub(all) struct Traversal {
  /// Base expression
  base : Expression
  /// Traversal operators
  operators : Array[TraversalOperator]
} derive(Debug, Eq)

///|
/// Traversal operator
///
/// ```mbt check
/// test {
///   assert_eq(
///     expr_to_string(
///       Expression::ExprTraversal(
///         TraversalBuilder::new(expr_str("o")).attr("a").build(),
///       ),
///     ),
///     "\"o\".a",
///   )
/// }
/// ```
pub(all) enum TraversalOperator {
  /// Attribute access (obj.attr)
  Attr(String)
  /// Index access (obj[index])
  Index(Expression)
  /// Splat access (obj.* or obj[*])
  Splat
} derive(Debug, Eq)

///|
/// Builder for constructing Traversal expressions incrementally
///
/// ```mbt check
/// test {
///   let t = TraversalBuilder::new(expr_str("o")).attr("a").build()
///   assert_eq(expr_to_string(Expression::ExprTraversal(t)), "\"o\".a")
/// }
/// ```
pub struct TraversalBuilder {
  base : Expression
  operators : Array[TraversalOperator]
}

///|
/// Create a new TraversalBuilder from a base expression
///
/// ```mbt check
/// test {
///   let b = TraversalBuilder::new(expr_str("o"))
///   assert_eq(expr_to_string(Expression::ExprTraversal(b.build())), "\"o\"")
/// }
/// ```
pub fn TraversalBuilder::new(base : Expression) -> TraversalBuilder {
  { base, operators: [] }
}

///|
/// Add an attribute access operator (.attr)
///
/// ```mbt check
/// test {
///   let t = TraversalBuilder::new(expr_str("o")).attr("a").attr("b").build()
///   assert_eq(expr_to_string(Expression::ExprTraversal(t)), "\"o\".a.b")
/// }
/// ```
pub fn TraversalBuilder::attr(
  self : TraversalBuilder,
  name : String,
) -> TraversalBuilder {
  self.operators.push(Attr(name))
  self
}

///|
/// Add an index access operator ([expr])
///
/// ```mbt check
/// test {
///   let t = TraversalBuilder::new(expr_str("o")).index(expr_int(0)).build()
///   assert_eq(expr_to_string(Expression::ExprTraversal(t)), "\"o\"[0]")
/// }
/// ```
pub fn TraversalBuilder::index(
  self : TraversalBuilder,
  expr : Expression,
) -> TraversalBuilder {
  self.operators.push(Index(expr))
  self
}

///|
/// Add a splat access operator (.*)
///
/// ```mbt check
/// test {
///   let t = TraversalBuilder::new(expr_str("o")).splat().attr("a").build()
///   assert_eq(expr_to_string(Expression::ExprTraversal(t)), "\"o\".*.a")
/// }
/// ```
pub fn TraversalBuilder::splat(self : TraversalBuilder) -> TraversalBuilder {
  self.operators.push(Splat)
  self
}

///|
/// Build the Traversal expression
///
/// ```mbt check
/// test {
///   let t = TraversalBuilder::new(expr_str("o")).build()
///   assert_true(Expression::ExprTraversal(t) is Expression::ExprTraversal(_))
/// }
/// ```
pub fn TraversalBuilder::build(self : TraversalBuilder) -> Traversal {
  { base: self.base, operators: self.operators }
}

///|
/// Create a TraversalBuilder starting from this Traversal
///
/// ```mbt check
/// test {
///   let b = Traversal::builder(expr_str("o"))
///   assert_eq(
///     expr_to_string(Expression::ExprTraversal(b.attr("k").build())),
///     "\"o\".k",
///   )
/// }
/// ```
pub fn Traversal::builder(base : Expression) -> TraversalBuilder {
  TraversalBuilder::new(base)
}

///|
/// Function call
///
/// ```mbt check
/// test {
///   let fc = FuncCallBuilder::new("upper").arg(expr_str("x")).build()
///   assert_eq(expr_to_string(Expression::ExprFuncCall(fc)), "upper(\"x\")")
/// }
/// ```
pub(all) struct FuncCall {
  /// Function name
  name : String
  /// Arguments
  args : Array[Expression]
} derive(Debug, Eq)

///|
/// Builder for constructing FuncCall expressions incrementally
///
/// ```mbt check
/// test {
///   let fc = FuncCallBuilder::new("max").arg(expr_int(1)).build()
///   assert_eq(expr_to_string(Expression::ExprFuncCall(fc)), "max(1)")
/// }
/// ```
pub struct FuncCallBuilder {
  name : String
  args : Array[Expression]
}

///|
/// Create a new FuncCallBuilder with a function name
///
/// ```mbt check
/// test {
///   let b = FuncCallBuilder::new("max")
///   assert_eq(expr_to_string(Expression::ExprFuncCall(b.build())), "max()")
/// }
/// ```
pub fn FuncCallBuilder::new(name : String) -> FuncCallBuilder {
  { name, args: [] }
}

///|
/// Add an argument expression
///
/// ```mbt check
/// test {
///   let fc = FuncCallBuilder::new("max").arg(expr_int(1)).arg(expr_int(2)).build()
///   assert_eq(expr_to_string(Expression::ExprFuncCall(fc)), "max(1, 2)")
/// }
/// ```
pub fn FuncCallBuilder::arg(
  self : FuncCallBuilder,
  expr : Expression,
) -> FuncCallBuilder {
  self.args.push(expr)
  self
}

///|
/// Build the FuncCall expression
///
/// ```mbt check
/// test {
///   let fc = FuncCallBuilder::new("min").arg(expr_int(1)).build()
///   assert_eq(fc.name, "min")
/// }
/// ```
pub fn FuncCallBuilder::build(self : FuncCallBuilder) -> FuncCall {
  { name: self.name, args: self.args }
}

///|
/// Create a FuncCallBuilder for this function name
///
/// ```mbt check
/// test {
///   let fc = FuncCall::builder("len").arg(expr_str("x")).build()
///   assert_eq(expr_to_string(Expression::ExprFuncCall(fc)), "len(\"x\")")
/// }
/// ```
pub fn FuncCall::builder(name : String) -> FuncCallBuilder {
  FuncCallBuilder::new(name)
}

///|
/// Conditional expression (cond ? true_expr : false_expr)
///
/// ```mbt check
/// test {
///   let e = parse("v = c ? 1 : 2").unwrap().find_attr("v").unwrap().get_value()
///   match e {
///     Expression::ExprConditional(_) => ()
///     _ => panic()
///   }
/// }
/// ```
pub(all) struct Conditional {
  /// Condition expression
  condition : Expression
  /// True branch expression
  true_expr : Expression
  /// False branch expression
  false_expr : Expression
} derive(Debug, Eq)

///|
/// Operation (binary or unary)
///
/// ```mbt check
/// test {
///   let e = parse("v = 1 + 2").unwrap().find_attr("v").unwrap().get_value()
///   match e {
///     Expression::ExprOperation(Operation::Binary(_)) => ()
///     _ => panic()
///   }
/// }
/// ```
pub(all) enum Operation {
  /// Binary operation (left op right)
  Binary(BinaryOp)
  /// Unary operation (op operand)
  Unary(UnaryOp)
} derive(Debug, Eq)

///|
/// Binary operation
///
/// ```mbt check
/// test {
///   let e = parse("v = 1 + 2").unwrap().find_attr("v").unwrap().get_value()
///   match e {
///     Expression::ExprOperation(Operation::Binary(b)) =>
///       assert_eq(b.op, BinaryOperator::Plus)
///     _ => panic()
///   }
/// }
/// ```
pub(all) struct BinaryOp {
  /// Left operand
  left : Expression
  /// Operator
  op : BinaryOperator
  /// Right operand
  right : Expression
} derive(Debug, Eq)

///|
/// Binary operator
///
/// ```mbt check
/// test {
///   let e = parse("v = 1 * 2").unwrap().find_attr("v").unwrap().get_value()
///   match e {
///     Expression::ExprOperation(Operation::Binary(b)) =>
///       assert_eq(b.op, BinaryOperator::Mul)
///     _ => panic()
///   }
/// }
/// ```
pub(all) enum BinaryOperator {
  /// Addition (+)
  Plus
  /// Subtraction (-)
  Minus
  /// Multiplication (*)
  Mul
  /// Division (/)
  Div
  /// Modulo (%)
  Mod
  /// Equality (==)
  Eq
  /// Inequality (!=)
  Neq
  /// Less than (<)
  Lt
  /// Greater than (>)
  Gt
  /// Less than or equal (<=)
  Lte
  /// Greater than or equal (>=)
  Gte
  /// Logical AND (&&)
  And
  /// Logical OR (||)
  Or
} derive(Debug, Eq)

///|
/// Unary operation
///
/// ```mbt check
/// test {
///   let e = parse("v = -x").unwrap().find_attr("v").unwrap().get_value()
///   match e {
///     Expression::ExprOperation(Operation::Unary(u)) =>
///       assert_eq(u.op, UnaryOperator::Negate)
///     _ => panic()
///   }
/// }
/// ```
pub(all) struct UnaryOp {
  /// Operator
  op : UnaryOperator
  /// Operand
  operand : Expression
} derive(Debug, Eq)

///|
/// Unary operator
///
/// ```mbt check
/// test {
///   let e = parse("v = !x").unwrap().find_attr("v").unwrap().get_value()
///   match e {
///     Expression::ExprOperation(Operation::Unary(u)) =>
///       assert_eq(u.op, UnaryOperator::Not)
///     _ => panic()
///   }
/// }
/// ```
pub(all) enum UnaryOperator {
  /// Negation (-)
  Negate
  /// Logical NOT (!)
  Not
} derive(Debug, Eq)

///|
/// For expression (list/object comprehension)
///
/// ```mbt check
/// test {
///   let e = parse("v = [for x in xs : x]")
///     .unwrap()
///     .find_attr("v")
///     .unwrap()
///     .get_value()
///   match e {
///     Expression::ExprFor(ForExpr::List(_)) => ()
///     _ => panic()
///   }
/// }
/// ```
pub(all) enum ForExpr {
  /// List comprehension: [for x in list: expr]
  List(ForListExpr)
  /// Object comprehension: {for k, v in obj: k => v}
  Object(ForObjectExpr)
} derive(Debug, Eq)

///|
/// List comprehension
///
/// ```mbt check
/// test {
///   let e = parse("v = [for x in xs : x]")
///     .unwrap()
///     .find_attr("v")
///     .unwrap()
///     .get_value()
///   match e {
///     Expression::ExprFor(ForExpr::List(l)) => assert_eq(l.var_name, "x")
///     _ => panic()
///   }
/// }
/// ```
pub(all) struct ForListExpr {
  /// Loop variable name
  var_name : String
  /// Collection expression
  collection : Expression
  /// Value expression
  value_expr : Expression
  /// Optional filter expression
  filter : Expression?
} derive(Debug, Eq)

///|
/// Object comprehension
///
/// ```mbt check
/// test {
///   let e = parse("v = {for k, v in m : k => v}")
///     .unwrap()
///     .find_attr("v")
///     .unwrap()
///     .get_value()
///   match e {
///     Expression::ExprFor(ForExpr::Object(o)) => assert_eq(o.key_var, "k")
///     _ => panic()
///   }
/// }
/// ```
pub(all) struct ForObjectExpr {
  /// Key variable name
  key_var : String
  /// Value variable name
  value_var : String
  /// Collection expression
  collection : Expression
  /// Key expression
  key_expr : Expression
  /// Value expression
  value_expr : Expression
  /// Optional filter expression
  filter : Expression?
} derive(Debug, Eq)

///|
/// Convert ObjectKey to string representation
///
/// ```mbt check
/// test {
///   assert_eq(ObjectKey::Identifier("x").to_string(), "x")
///   assert_eq(ObjectKey::Expression(expr_int(2)).to_string(), "2")
/// }
/// ```
pub fn ObjectKey::to_string(self : ObjectKey) -> String {
  match self {
    Identifier(name) => name
    Expression(expr) => expr_to_string(expr)
  }
}

///|
/// Convert Expression to string representation
///
/// ```mbt check
/// test {
///   assert_eq(expr_to_string(expr_int(42)), "42")
///   assert_eq(expr_to_string(expr_str("hi")), "\"hi\"")
/// }
/// ```
pub fn expr_to_string(expr : Expression) -> String {
  match expr {
    ExprNull => "null"
    ExprBool(b) => if b { "true" } else { "false" }
    ExprInt(i) => i.to_string()
    ExprInt64(i) => i.to_string()
    ExprFloat(f) => f.to_string()
    ExprString(s) => "\"" + s + "\""
    ExprArray(arr) => {
      let items = arr.map(expr_to_string)
      "[" + items.join(", ") + "]"
    }
    ExprObject(obj) =>
      if obj.is_empty() {
        "{}"
      } else {
        let items = obj.map(fn(pair) {
          let (k, v) = pair
          ObjectKey::to_string(k) + " = " + expr_to_string(v)
        })
        "{ " + items.join(", ") + " }"
      }
    ExprTemplate(_) => "