pub struct Fuwaroid[Cmd, Query, Reply] {
  priv mailbox : @aqueue.Queue[Envelope[Cmd, Query, Reply]]
  priv stop : LoopStop
}

pub enum Envelope[Cmd, Query, Reply] { Tell(Cmd); Ask(Query, @aqueue.Queue[Reply]) }
pub struct Ctx[Cmd, Query, Reply] { group : @async.TaskGroup; address : Fuwaroid[Cmd, Query, Reply] }

#derive(Eq, Debug)
pub(all) enum SendRefusal { MailboxClosed; MailboxFull }
pub extend SendRefusal with Eq::{equal, not_equal}
pub extend SendRefusal with @moonbitlang/core/debug.Debug::{to_repr}

#derive(Eq, Debug)
pub(all) enum AskFailure { NotDelivered(SendRefusal); TimedOut; Stopped }
pub extend AskFailure with Eq::{equal, not_equal}
pub extend AskFailure with @moonbitlang/core/debug.Debug::{to_repr}

#derive(Debug)
pub(all) enum StopReason { Graceful; Cancelled; Failed(Error) }
pub extend StopReason with @moonbitlang/core/debug.Debug::{to_repr}

pub(all) suberror StoppedError { StoppedError }

priv struct LoopStop {
  mut reason : StopReason?; mut cleanup_error : Error?; mut task : @async.Task[Unit]?; diag : Diag
}

#derive(Eq, Debug)
pub(all) enum Mailbox { Unbounded; Bounded(Int32) }
pub extend Mailbox with Eq::{equal, not_equal}
pub extend Mailbox with @moonbitlang/core/debug.Debug::{to_repr}

fn mailbox_capacity_error(n : Int32) -> String? {
  if n <= 0 { Some("Bounded mailbox capacity must be a positive integer, got \{n}") } else { None }
}

fn LoopStop::fresh() -> LoopStop { { reason: None, cleanup_error: None, task: None, diag: Diag::fresh() } }

#inline
fn[Cmd, Query, Reply] Fuwaroid::admit(
  self : Fuwaroid[Cmd, Query, Reply], envelope : Envelope[Cmd, Query, Reply]
) -> Result[Unit, SendRefusal] {
  try {
    if self.mailbox.try_put(envelope) { self.stop.diag.accepted += 1L; Ok(()) }
    else { self.stop.diag.rejected_full += 1L; Err(MailboxFull) }
  } catch { _ => { self.stop.diag.rejected_closed += 1L; Err(MailboxClosed) } }
}

pub fn[State, Cmd, Query, Reply] Fuwaroid::spawn(
  group~ : @async.TaskGroup, init~ : State,
  on_cmd~ : (Ctx[Cmd, Query, Reply], State, Cmd) -> State,
  on_query~ : (Ctx[Cmd, Query, Reply], State, Query) -> (State, Reply),
  mailbox~ : Mailbox = Mailbox::Unbounded
) -> Fuwaroid[Cmd, Query, Reply] {
  let kind : @aqueue.Kind = match mailbox {
    Unbounded => @aqueue.Unbounded
    Bounded(n) => match mailbox_capacity_error(n) { Some(m) => abort(m); None => @aqueue.Blocking(n) }
  }
  let queue : @aqueue.Queue[Envelope[Cmd, Query, Reply]] = @aqueue.Queue(kind~)
  let stop = LoopStop::fresh()
  let fuwaroid : Fuwaroid[Cmd, Query, Reply] = { mailbox: queue, stop }
  let ctx : Ctx[Cmd, Query, Reply] = { group, address: fuwaroid }
  stop.task = Some(group.spawn(no_wait=true, () => fuwaroid_loop(ctx, init, on_cmd, on_query, queue, stop~)))
  fuwaroid
}

pub fn[State, Cmd] Fuwaroid::spawn_fold(
  group~ : @async.TaskGroup, init~ : State,
  on_cmd~ : (Ctx[Cmd, Unit, Unit], State, Cmd) -> State,
  mailbox~ : Mailbox = Mailbox::Unbounded
) -> Fuwaroid[Cmd, Unit, Unit] {
  Fuwaroid::spawn(group~, init~, on_cmd~, on_query=(_, s, _) => (s, ()), mailbox~)
}

let fuwaroid_yield_batch : Int32 = 64
let fuwaroid_cleanup_yield_batch : Int32 = 32

async fn[State, Cmd, Query, Reply] fuwaroid_loop(
  ctx : Ctx[Cmd, Query, Reply], init : State,
  on_cmd : (Ctx[Cmd, Query, Reply], State, Cmd) -> State,
  on_query : (Ctx[Cmd, Query, Reply], State, Query) -> (State, Reply),
  queue : @aqueue.Queue[Envelope[Cmd, Query, Reply]], stop~ : LoopStop
) -> Unit {
  let outcome = @async.handle_cancellation(() => {
    try { fuwaroid_serve(ctx, init, on_cmd, on_query, queue, stop.diag) }
    catch { @aqueue.QueueAlreadyClosed => Graceful; original => Failed(original) }
  })
  match outcome {
    None => { fuwaroid_cleanup(queue, Cancelled, stop); @async.pause() }
    Some(r) => fuwaroid_cleanup(queue, r, stop)
  }
}

async fn[State, Cmd, Query, Reply] fuwaroid_serve(
  ctx : Ctx[Cmd, Query, Reply], init : State,
  on_cmd : (Ctx[Cmd, Query, Reply], State, Cmd) -> State,
  on_query : (Ctx[Cmd, Query, Reply], State, Query) -> (State, Reply),
  queue : @aqueue.Queue[Envelope[Cmd, Query, Reply]], diag : Diag
) -> StopReason {
  for state = init {
    let first = match queue.try_get() {
      Some(e) => e
      None => queue.get()
    }
    let p0 = diag.processed
    let s0 = match first {
      Tell(cmd) => on_cmd(ctx, state, cmd)
      Ask(q, r) => {
        let (ns, ans) = on_query(ctx, state, q)
        let _ = r.try_put(ans) catch { _ => false }
        ns
      }
    }
    diag.processed = p0 + 1L
    let s = for s = s0, served = 1 {
      if served >= fuwaroid_yield_batch { break s }
      match queue.try_get() {
        Some(Tell(cmd)) => {
          let ns = on_cmd(ctx, s, cmd)
          diag.processed += 1L
          continue ns, served + 1
        }
        Some(Ask(q, r)) => {
          let (ns, ans) = on_query(ctx, s, q)
          diag.processed += 1L
          let _ = r.try_put(ans) catch { _ => false }
          continue ns, served + 1
        }
        None => break s
      }
    }
    if diag.processed - p0 >= fuwaroid_yield_batch.to_int64() { @async.pause() }
    continue s
  }
  Graceful
}

async fn[Cmd, Query, Reply] fuwaroid_cleanup(
  queue : @aqueue.Queue[Envelope[Cmd, Query, Reply]], reason : StopReason, stop : LoopStop
) -> Unit {
  queue.close()
  stop.diag.transition(Closing)
  let secondary : Error? = try {
    @async.protect_from_cancel(() => fail_leftover_asks(queue, diag=stop.diag)); None
  } catch { e => Some(e) }
  stop.reason = Some(reason)
  stop.cleanup_error = secondary
  stop.diag.transition(Lifecycle::Stopped(reason))
  match reason {
    Cancelled => ()
    Graceful => if secondary is Some(e) { raise e }
    Failed(original) => raise original
  }
}

async fn[Cmd, Query, Reply] fail_leftover_asks(
  queue : @aqueue.Queue[Envelope[Cmd, Query, Reply]], diag? : Diag
) -> Unit {
  for abandoned = 0 {
    let next = queue.try_get() catch {
      @aqueue.QueueAlreadyClosed => { if diag is Some(d) { d.add_abandoned(abandoned) }; break () }
      e => { if diag is Some(d) { d.add_abandoned(abandoned) }; raise e }
    }
    match next {
      Some(env) => {
        if env is Ask(_, r) { r.close(error=StoppedError) }
        let abandoned = abandoned + 1
        if abandoned >= fuwaroid_cleanup_yield_batch {
          if diag is Some(d) { d.add_abandoned(abandoned) }
          @async.pause()
          continue 0
        }
        continue abandoned
      }
      None => { if diag is Some(d) { d.add_abandoned(abandoned) }; break () }
    }
  }
}

pub fn[Cmd, Query, Reply] Fuwaroid::tell(self : Fuwaroid[Cmd, Query, Reply], cmd : Cmd) -> Result[Unit, SendRefusal] {
  self.admit(Envelope::Tell(cmd))
}

#inline
fn classify_ask_error(error : Error) -> AskFailure? {
  match error { StoppedError => Some(Stopped); @async.TimeoutError => Some(TimedOut); _ => None }
}

pub async fn[Cmd, Query, Reply] Fuwaroid::ask(
  self : Fuwaroid[Cmd, Query, Reply], query : Query, timeout_ms~ : Int32
) -> Result[Reply, AskFailure] {
  let reply : @aqueue.Queue[Reply] = @aqueue.Queue(kind=@aqueue.Unbounded)
  match self.admit(Envelope::Ask(query, reply)) {
    Ok(_) => ()
    Err(refusal) => return Err(NotDelivered(refusal))
  }
  try {
    let deadline = @async.now() + timeout_ms.to_int64()
    for _ in 0..<64 {
      @async.pause()
      if reply.try_get() is Some(ans) { return Ok(ans) }
      if @async.now() >= deadline { reply.close(); return Err(TimedOut) }
    }
    let rem = (deadline - @async.now()).to_int()
    if rem <= 0 { reply.close(); return Err(TimedOut) }
    match @async.with_timeout_opt(rem, () => reply.get()) { Some(ans) => Ok(ans); None => { reply.close(); Err(TimedOut) } }
  } catch { e => match classify_ask_error(e) { Some(f) => Err(f); None => raise e } }
}

pub fn[Cmd, Query, Reply] Fuwaroid::close(self : Fuwaroid[Cmd, Query, Reply]) -> Unit {
  self.stop.diag.transition(Closing)
  self.mailbox.close()
}

pub async fn[Cmd, Query, Reply] Fuwaroid::join(self : Fuwaroid[Cmd, Query, Reply]) -> StopReason {
  if @async.is_being_cancelled() { @async.pause() }
  let cell = self.stop
  let outcome : Result[Unit, Error] = Ok(cell.task.unwrap().wait()) catch { e => Err(e) }
  match outcome {
    Ok(_) => cell.reason.unwrap()
    Err(@async.WaitedTaskAlreadyCancelled) => Cancelled
    Err(other) => match cell.reason { Some(Failed(_) as r) => r; _ => Failed(cell.cleanup_error.unwrap_or(other)) }
  }
}