///|
/// Create an async function value. When called, it:
/// 1. Creates a Promise
/// 2. Internally creates a generator from the body (await → yield)
/// 3. Auto-steps the generator, resolving/rejecting the Promise
/// 4. Returns the Promise
fn Interpreter::make_async_function(
  self : Interpreter,
  name : String?,
  params : Array[String],
  rest_param : String?,
  body : Array[@ast.Stmt],
  strict : Bool,
  closure : Environment,
) -> Value {
  let func_name = match name {
    Some(n) => n
    None => ""
  }
  let nf_desc : PropDescriptor = {
    writable: false,
    enumerable: false,
    configurable: true,
    getter: None,
    setter: None,
    is_accessor: false,
  }
  let async_proto = get_function_prototype(self)
  stamp_function_realm(
    Object({
      bag: {
        properties: {
          "name": String_(func_name),
          "length": Number(params.length().to_double()),
        },
        symbol_properties: {},
        descriptors: { "name": nf_desc, "length": nf_desc },
        symbol_descriptors: {},
      },
      prototype: async_proto,
      callable: Some(
        InterpreterCallable(func_name, fn(
          ip : Interpreter,
          this_val : Value,
          args : Array[Value],
        ) -> Value {
          run_async_body(
            ip,
            this_val,
            args,
            name,
            params,
            None,
            rest_param,
            body,
            strict,
            closure,
          )
        }),
      ),
      class_name: "AsyncFunction",
      extensible: true,
      arraybuffer_state: None,
    }),
    realm_state=Some(self.realm_state),
  )
}

///|
fn Interpreter::make_async_function_ext(
  self : Interpreter,
  name : String?,
  params : Array[@ast.Param],
  rest_param : String?,
  body : Array[@ast.Stmt],
  strict : Bool,
  closure : Environment,
) -> Value {
  let func_name = match name {
    Some(n) => n
    None => ""
  }
  let nf_desc : PropDescriptor = {
    writable: false,
    enumerable: false,
    configurable: true,
    getter: None,
    setter: None,
    is_accessor: false,
  }
  let async_proto = get_function_prototype(self)
  let func_length = expected_argument_count_ext(params)
  stamp_function_realm(
    Object({
      bag: {
        properties: {
          "name": String_(func_name),
          "length": Number(func_length.to_double()),
        },
        symbol_properties: {},
        descriptors: { "name": nf_desc, "length": nf_desc },
        symbol_descriptors: {},
      },
      prototype: async_proto,
      callable: Some(
        InterpreterCallable(func_name, fn(
          ip : Interpreter,
          this_val : Value,
          args : Array[Value],
        ) -> Value {
          run_async_body(
            ip,
            this_val,
            args,
            name,
            [],
            Some(params),
            rest_param,
            body,
            strict,
            closure,
          )
        }),
      ),
      class_name: "AsyncFunction",
      extensible: true,
      arraybuffer_state: None,
    }),
    realm_state=Some(self.realm_state),
  )
}

///|
/// Execute an async function body by creating a generator internally
/// and auto-stepping it with Promise resolution.
fn run_async_body(
  ip : Interpreter,
  this_val : Value,
  args : Array[Value],
  name : String?,
  params : Array[String],
  params_ext : Array[@ast.Param]?,
  rest_param : String?,
  body : Array[@ast.Stmt],
  strict : Bool,
  closure : Environment,
) -> Value {
  let promise_data = new_promise_data()
  let promise_val = Promise(promise_data)
  let (resolve_fn, reject_fn) = create_resolving_functions(ip, promise_data)
  // Create a generator object from the async function body
  let gen_proto = get_generator_prototype(ip)
  let func_proto = Object({
    bag: PropertyBag(),
    prototype: gen_proto,
    callable: None,
    class_name: "Object",
    extensible: true,
    arraybuffer_state: None,
  })
  let gen_val = create_generator_instance(
    ip, this_val, args, name, params, params_ext, rest_param, body, strict, closure,
    func_proto,
  ) catch {
    JsException(e) => {
      // Parameter binding error rejects the promise
      let _ = ip.call_value(reject_fn, Undefined, [e], @token.Loc::default()) catch {
        _ => Undefined
      }
      return promise_val
    }
    e => {
      let err_val = String_(e.to_string())
      let _ = ip.call_value(
        reject_fn,
        Undefined,
        [err_val],
        @token.Loc::default(),
      ) catch {
        _ => Undefined
      }
      return promise_val
    }
  }
  // Auto-step the generator
  async_step(ip, gen_val, Undefined, resolve_fn, reject_fn, false)
  promise_val
}

///|
/// Auto-step an async generator: call next/throw, handle result.
fn async_step(
  ip : Interpreter,
  gen_val : Value,
  value : Value,
  resolve_fn : Value,
  reject_fn : Value,
  is_throw : Bool,
) -> Unit {
  let loc = @token.Loc::default()
  // Call gen.next(value) or gen.throw(value)
  let result : Value = try {
    if is_throw {
      let throw_method = ip.get_property(gen_val, "throw", loc)
      ip.call_value(throw_method, gen_val, [value], loc)
    } else {
      let next_method = ip.get_property(gen_val, "next", loc)
      ip.call_value(next_method, gen_val, [value], loc)
    }
  } catch {
    JsException(e) => {
      // Generator threw — reject the promise
      let _ = ip.call_value(reject_fn, Undefined, [e], loc) catch {
        _ => Undefined
      }
      return
    }
    e => {
      let err_val = js_error_to_value_with_env(e, Some(ip.global))
      let _ = ip.call_value(reject_fn, Undefined, [err_val], loc) catch {
        _ => Undefined
      }
      return
    }
  }
  // Extract { value, done } from result
  let result_value = ip.get_property(result, "value", loc) catch {
    _ => Undefined
  }
  let result_done = ip.get_property(result, "done", loc) catch {
    _ => Bool(false)
  }
  let is_done = match result_done {
    Bool(b) => b
    _ => false
  }
  if is_done {
    // Generator completed — resolve the promise
    // Do NOT call run_microtasks() here; the outer event loop
    // (run_microtasks in js_engine.mbt) uses index-based draining
    // and will process any newly enqueued reaction microtasks.
    let _ = ip.call_value(resolve_fn, Undefined, [result_value], loc) catch {
      _ => Undefined
    }
  } else {
    // Generator yielded (await) — schedule continuation via microtask.
    // Do NOT call run_microtasks() here to avoid recursive re-entry;
    // the outer event loop drains the queue with its while loop.
    let awaited = result_value
    let gen = gen_val
    let res_fn = resolve_fn
    let rej_fn = reject_fn
    let on_fulfill = make_interp_method_func(
      name="",
      length=1,
      realm_state=Some(ip.realm_state),
      fn(i : Interpreter, _this : Value, args : Array[Value]) -> Value {
        let v = if args.length() > 0 { args[0] } else { Undefined }
        async_step(i, gen, v, res_fn, rej_fn, false)
        Undefined
      },
    )
    let on_reject = make_interp_method_func(
      name="",
      length=1,
      realm_state=Some(ip.realm_state),
      fn(i : Interpreter, _this : Value, args : Array[Value]) -> Value {
        let v = if args.length() > 0 { args[0] } else { Undefined }
        async_step(i, gen, v, res_fn, rej_fn, true)
        Undefined
      },
    )
    // Wrap the awaited value in Promise.resolve() then schedule .then()
    // This ensures all await continuations go through the microtask queue,
    // matching spec behavior and preventing stack overflow.
    let resolved_promise = try {
      let promise_ctor = ip.get_property(
        ip.global.get("Promise"),
        "resolve",
        loc,
      )
      ip.call_value(promise_ctor, ip.global.get("Promise"), [awaited], loc)
    } catch {
      _ => {
        // Fallback: Promise.resolve() unavailable; inspect awaited directly
        match awaited {
          Promise(pd) =>
            match pd.state {
              Fulfilled => ip.enqueue_microtask(on_fulfill, [pd.result])
              Rejected => ip.enqueue_microtask(on_reject, [pd.result])
              Pending => {
                let noop = make_interp_method_func(
                  name="",
                  length=0,
                  realm_state=Some(ip.realm_state),
                  fn(_i : Interpreter, _t : Value, _a : Array[Value]) -> Value {
                    Undefined
                  },
                )
                pd.fulfill_reactions.push({
                  handler: Some(on_fulfill),
                  resolve: noop,
                  reject: noop,
                  reaction_type: Fulfill,
                })
                pd.reject_reactions.push({
                  handler: Some(on_reject),
                  resolve: noop,
                  reject: noop,
                  reaction_type: Reject,
                })
              }
            }
          _ => ip.enqueue_microtask(on_fulfill, [awaited])
        }
        return
      }
    }
    // Fast path: if resolved_promise is a native Promise, bypass the JS-level
    // .then property and attach reactions directly via the internal record.
    // This avoids issues with overridden .then and matches spec PerformPromiseThen.
    match resolved_promise {
      Promise(pd) =>
        match pd.state {
          Fulfilled => ip.enqueue_microtask(on_fulfill, [pd.result])
          Rejected => ip.enqueue_microtask(on_reject, [pd.result])
          Pending => {
            let noop = make_interp_method_func(
              name="",
              length=0,
              realm_state=Some(ip.realm_state),
              fn(_i : Interpreter, _t : Value, _a : Array[Value]) -> Value {
                Undefined
              },
            )
            pd.fulfill_reactions.push({
              handler: Some(on_fulfill),
              resolve: noop,
              reject: noop,
              reaction_type: Fulfill,
            })
            pd.reject_reactions.push({
              handler: Some(on_reject),
              resolve: noop,
              reject: noop,
              reaction_type: Reject,
            })
          }
        }
      _ => {
        // Non-native promise: use JS-level .then() property
        let then_method = ip.get_property(resolved_promise, "then", loc) catch {
          e => {
            // get_property threw — propagate to on_reject
            let err_val = js_error_to_value_with_env(e, Some(ip.global))
            ip.enqueue_microtask(on_reject, [err_val])
            return
          }
        }
        // Check if then_method is callable before invoking
        let is_callable = match then_method {
          Object(od) => od.callable is Some(_)
          _ => false
        }
        if is_callable {
          try {
            let _ = ip.call_value(
              then_method,
              resolved_promise,
              [on_fulfill, on_reject],
              loc,
            )
          } catch {
            e => {
              // .then() threw — propagate to on_reject
              let err_val = js_error_to_value_with_env(e, Some(ip.global))
              ip.enqueue_microtask(on_reject, [err_val])
            }
          }
        } else {
          // Non-callable .then — treat as non-thenable, fulfill directly
          ip.enqueue_microtask(on_fulfill, [resolved_promise])
        }
      }
    }
  }
}

///|
/// Create an async generator function value (simple params).
fn Interpreter::make_async_generator_function(
  self : Interpreter,
  name : String?,
  params : Array[String],
  rest_param : String?,
  body : Array[@ast.Stmt],
  strict : Bool,
  closure : Environment,
) -> Value {
  make_async_gen_function_inner(
    self,
    name,
    params,
    None,
    rest_param,
    body,
    strict,
    closure,
  )
}

///|
/// Create an async generator function value (extended params).
fn Interpreter::make_async_generator_function_ext(
  self : Interpreter,
  name : String?,
  params : Array[@ast.Param],
  rest_param : String?,
  body : Array[@ast.Stmt],
  strict : Bool,
  closure : Environment,
) -> Value {
  make_async_gen_function_inner(
    self,
    name,
    [],
    Some(params),
    rest_param,
    body,
    strict,
    closure,
  )
}

///|
/// Shared factory for async generator functions.
/// Builds the function object with async generator prototype and class name.
fn make_async_gen_function_inner(
  interp : Interpreter,
  name : String?,
  params : Array[String],
  params_ext : Array[@ast.Param]?,
  rest_param : String?,
  body : Array[@ast.Stmt],
  strict : Bool,
  closure : Environment,
) -> Value {
  let object_prototype = interp.global.get("[[ObjectPrototype]]") catch {
    _ => Null
  }
  let async_gen_proto = init_async_generator_prototype(
    interp.realm_state.well_known_symbols,
    interp.realm_state,
    object_prototype,
  )
  let func_prototype = Object({
    bag: PropertyBag(),
    prototype: async_gen_proto,
    callable: None,
    class_name: "AsyncGenerator",
    extensible: true,
    arraybuffer_state: None,
  })
  let gen_func_proto : Value = match
    interp.global.bindings.get("[[GeneratorFunctionPrototype]]") {
    Some(binding) => binding.value
    None => Null
  }
  let func_name = match name {
    Some(n) => n
    None => ""
  }
  let func_length = match params_ext {
    Some(pext) => expected_argument_count_ext(pext)
    None => params.length()
  }
  let fn_props : Map[String, Value] = {}
  fn_props["prototype"] = func_prototype
  fn_props["name"] = String_(func_name)
  fn_props["length"] = Number(func_length.to_double())
  let nf_desc : PropDescriptor = {
    writable: false,
    enumerable: false,
    configurable: true,
    getter: None,
    setter: None,
    is_accessor: false,
  }
  stamp_function_realm(
    Object({
      bag: {
        properties: fn_props,
        symbol_properties: {},
        descriptors: {
          "name": nf_desc,
          "length": nf_desc,
          "prototype": {
            writable: true,
            enumerable: false,
            configurable: false,
            getter: None,
            setter: None,
            is_accessor: false,
          },
        },
        symbol_descriptors: {},
      },
      prototype: gen_func_proto,
      callable: Some(
        InterpreterCallable(func_name, fn(ip, this_val, args) raise {
          create_generator_instance(
            ip, this_val, args, name, params, params_ext, rest_param, body, strict,
            closure, func_prototype,
          )
        }),
      ),
      class_name: "AsyncGeneratorFunction",
      extensible: true,
      arraybuffer_state: None,
    }),
    realm_state=Some(interp.realm_state),
  )
}

///|
/// Create the async generator prototype with Promise-wrapping protocol methods.
/// Async generator .next()/.throw()/.return() return Promises per ECMAScript spec.
fn init_async_generator_prototype(
  well_known_symbols : WellKnownSymbols,
  realm_state : RealmState,
  object_prototype : Value,
) -> Value {
  let async_iter_sym = well_known_symbols.async_iterator
  let props : Map[String, Value] = {}
  let sym_props : Map[Int, Value] = {}
  let descs : Map[String, PropDescriptor] = {}
  let non_enum : PropDescriptor = {
    writable: true,
    enumerable: false,
    configurable: true,
    getter: None,
    setter: None,
    is_accessor: false,
  }

  // .next(value) — returns Promise<{value, done}>
  props["next"] = make_interp_method_func(
    name="next",
    length=1,
    realm_state=Some(realm_state),
    fn(ip, this_val, args) {
      let arg = if args.length() > 0 { args[0] } else { Undefined }
      async_generator_resume(ip, this_val, Next(arg))
    },
  )
  descs["next"] = non_enum

  // .throw(exception) — returns Promise<{value, done}>
  props["throw"] = make_interp_method_func(
    name="throw",
    length=1,
    realm_state=Some(realm_state),
    fn(ip, this_val, args) {
      let arg = if args.length() > 0 { args[0] } else { Undefined }
      async_generator_resume(ip, this_val, Throw(arg))
    },
  )
  descs["throw"] = non_enum

  // .return(value) — returns Promise<{value, done}>
  props["return"] = make_interp_method_func(
    name="return",
    length=1,
    realm_state=Some(realm_state),
    fn(ip, this_val, args) {
      let arg = if args.length() > 0 { args[0] } else { Undefined }
      async_generator_resume(ip, this_val, Return(arg))
    },
  )
  descs["return"] = non_enum

  // [Symbol.asyncIterator]() { return this; }
  sym_props[async_iter_sym.id] = make_method_func(
    name="[Symbol.asyncIterator]",
    length=0,
    realm_state=Some(realm_state),
    fn(this_val, _args) { this_val },
  )

  Object({
    bag: {
      properties: props,
      symbol_properties: sym_props,
      descriptors: descs,
      symbol_descriptors: {},
    },
    prototype: object_prototype,
    callable: None,
    class_name: "AsyncGenerator",
    extensible: true,
    arraybuffer_state: None,
  })
}

///|
/// Wrap generator_resume in a Promise for async generator protocol.
/// Returns a resolved Promise with {value, done} on success,
/// or a rejected Promise with the error on failure.
fn async_generator_resume(
  ip : Interpreter,
  this_val : Value,
  resume_kind : ResumeKind,
) -> Value {
  let result = generator_resume(ip, this_val, resume_kind) catch {
    JsException(e) => {
      let pd = new_promise_data()
      pd.state = Rejected
      pd.result = e
      return Promise(pd)
    }
    e => {
      let pd = new_promise_data()
      pd.state = Rejected
      pd.result = js_error_to_value_with_env(e, Some(ip.global))
      return Promise(pd)
    }
  }
  let pd = new_promise_data()
  pd.state = Fulfilled
  pd.result = result
  Promise(pd)
}

///|
/// Get the function prototype for async function objects.
fn get_function_prototype(interp : Interpreter) -> Value {
  match interp.global.bindings.get("[[AsyncFunctionPrototype]]") {
    Some(binding) => binding.value
    None =>
      match interp.global.bindings.get("[[FunctionPrototype]]") {
        Some(binding) => binding.value
        None => Null
      }
  }
}

///|
/// Set up the AsyncFunction constructor and prototype chain.
/// Mirrors setup_generator_function_constructor in generator.mbt.
///
/// Prototype chain (per ES spec):
///   AsyncFunction.__proto__ === Function
///   AsyncFunction.prototype.__proto__ === Function.prototype
///   AsyncFunction.prototype[@@toStringTag] === "AsyncFunction"
///   AsyncFunction.prototype.constructor === AsyncFunction
pub fn setup_async_function_constructor(
  env : Environment,
  well_known_symbols~ : WellKnownSymbols,
) -> Unit {
  // %AsyncFunction.prototype% inherits from Function.prototype
  let func_proto : Value = match env.bindings.get("[[FunctionPrototype]]") {
    Some(binding) => binding.value
    None => Null
  }
  let af_sym_props : Map[Int, Value] = {}
  let af_sym_descs : Map[Int, PropDescriptor] = {}
  let tostringtag_sym = well_known_symbols.to_string_tag
  af_sym_props[tostringtag_sym.id] = String_("AsyncFunction")
  af_sym_descs[tostringtag_sym.id] = {
    writable: false,
    enumerable: false,
    configurable: true,
    getter: None,
    setter: None,
    is_accessor: false,
  }
  let async_func_proto : Value = Object({
    bag: {
      properties: {},
      symbol_properties: af_sym_props,
      descriptors: {},
      symbol_descriptors: af_sym_descs,
    },
    prototype: func_proto,
    callable: None,
    class_name: "AsyncFunction",
    extensible: true,
    arraybuffer_state: None,
  })
  // AsyncFunction constructor: AsyncFunction(p1, p2, ..., body)
  let async_func_ctor : Value = make_interp_method_func(
    name="AsyncFunction",
    length=1,
    realm_state=env.realm_state,
    fn(interp, _this, args) raise {
      if args.length() == 0 {
        return interp.make_async_function(
          Some("anonymous"),
          [],
          None,
          [],
          false,
          interp.global,
        )
      }
      // Last arg is body, previous args are parameter names
      let body_str = match args[args.length() - 1] {
        String_(s) => s
        _ => args[args.length() - 1].to_string()
      }
      let param_parts : Array[String] = []
      for i = 0; i < args.length() - 1; i = i + 1 {
        match args[i] {
          String_(s) => param_parts.push(s)
          _ => param_parts.push(args[i].to_string())
        }
      }
      let params_str = param_parts.join(",")
      let source = "async function anonymous(" +
        params_str +
        ") {\n" +
        body_str +
        "\n}"
      let prog = @parser.parse(source)
      if prog.stmts.length() > 0 {
        match prog.stmts[0] {
          AsyncFuncDecl(_, params, body, _) => {
            // Validate static early errors against the function's strict context.
            let body_strict = has_use_strict(body)
            validate_function_constructor_params(true, params, None, body)
            interp.validate_block_early_errors(body, body_strict)
            return interp.make_async_function(
              Some("anonymous"),
              params,
              None,
              body,
              body_strict,
              interp.global,
            )
          }
          AsyncFuncDeclExt(_, params, rest_param, body, _) => {
            // Validate static early errors against the function's strict context.
            let body_strict = has_use_strict(body)
            validate_function_constructor_params_ext(params, rest_param, body)
            interp.validate_block_early_errors(body, body_strict)
            return interp.make_async_function_ext(
              Some("anonymous"),
              params,
              rest_param,
              body,
              body_strict,
              interp.global,
            )
          }
          _ => ()
        }
      }
      raise @errors.SyntaxError(
        message="Invalid AsyncFunction constructor source",
      )
    },
  )
  // AsyncFunction.prototype.constructor = AsyncFunction
  match async_func_proto {
    Object(data) => {
      data.bag.properties["constructor"] = async_func_ctor
      data.bag.descriptors["constructor"] = {
        writable: false,
        enumerable: false,
        configurable: true,
        getter: None,
        setter: None,
        is_accessor: false,
      }
    }
    _ => ()
  }
  // AsyncFunction.prototype property on the constructor
  match async_func_ctor {
    Object(data) => {
      data.bag.properties["prototype"] = async_func_proto
      data.bag.descriptors["prototype"] = {
        writable: false,
        enumerable: false,
        configurable: false,
        getter: None,
        setter: None,
        is_accessor: false,
      }
    }
    _ => ()
  }
  // Note: AsyncFunction is NOT a global property per spec (section 19).
  // It is only reachable via (async function(){}).constructor.
  // We store it as an internal binding so async functions get the right prototype.
  env.def_builtin("[[AsyncFunctionPrototype]]", async_func_proto)
}