///|
/// Cursor position reported by the terminal.
///
/// Rows and columns are 1-based terminal coordinates.
#derive(Eq, Debug)
pub struct CursorPosition {
  row : Int32
  col : Int32
}

///|
/// Terminal event reported by the coordinated root `Tty` handle.
#derive(Eq, Debug)
pub(all) enum Event {
  Input(@public_input.InputEvent)
  Resize(WindowSize)
}

///|
/// Raised out of a backend read when a window resize arrives instead of input.
priv suberror Resized

///|
/// Coordinated controlling-terminal handle.
///
/// `Tty` owns the controlling terminal (via `moonbitlang/core/async/tty` on
/// native and `internal/sidecar` on wasm) and coordinates VT command output,
/// input decoding, resize notifications, and request/response protocols. It
/// does not model a screen.
struct Tty {
  backend : Backend
  // Decodes terminal input as VT bytes on every platform.
  reader : @input.EventReader
  pending_input : Array[@public_input.InputEvent]
  // Serializes output writes so a single `write` call lands on the terminal
  // atomically with respect to other concurrent writers.
  write_lock : @lock.Lock
  // A resize noticed while a request/response query owned the reader; it is
  // reported by the next `read_event`.
  mut resize_pending : Bool
}

///|
/// Open the controlling terminal as one coordinated terminal handle.
///
/// On native this uses `moonbitlang/core/async/tty`; on wasm the terminal is
/// held by a sidecar process named by `TTY_SIDECAR` or embedded for the host
/// (see `sidecar/README.md`). Input, resize events and output all go through it.
pub async fn Tty::open() -> Tty {
  {
    backend: open_backend(),
    reader: @input.EventReader::new(),
    pending_input: [],
    write_lock: @lock.Lock::new(),
    resize_pending: false,
  }
}

///|
/// Close the terminal handle.
///
/// Restores raw mode if active and, on wasm, ends and reaps the sidecar.
pub async fn Tty::close(self : Self) -> Unit nocancel {
  backend_close(self.backend)
}

///|
/// Read the next root terminal event.
///
/// `esc_timeout_ms` controls the short wait used to distinguish a standalone
/// Escape key from the start of a longer escape sequence.
pub async fn Tty::read_event(
  self : Self,
  esc_timeout_ms~ : Int32 = 50,
) -> Event {
  if self.pending_input.length() > 0 {
    return Input(self.pending_input.remove(0))
  }
  for ;; {
    if self.resize_pending {
      self.resize_pending = false
      return Resize(self.window_size())
    }
    try self.read_decoded_input_event(esc_timeout_ms) catch {
      Resized => self.resize_pending = true
      error => raise error
    } noraise {
      event => return event
    }
  }
}

///|
async fn Tty::read_decoded_input_event(
  self : Self,
  esc_timeout_ms : Int32,
) -> Event {
  for ;; {
    match self.reader.read_event(self, esc_timeout_ms~) {
      Input(event) => return Input(event)
      CursorPosition(..) => ()
      KeyboardEnhancementFlags(_) => ()
      PrimaryDeviceAttributes(_) => ()
      DynamicColor(..) => ()
    }
  }
}

///|
/// Next low-level stream event for request/response queries. A resize seen
/// meanwhile is kept for the next `read_event`.
async fn Tty::read_internal_event(
  self : Self,
  esc_timeout_ms~ : Int32 = 50,
) -> @input.Event {
  for ;; {
    try self.reader.read_event(self, esc_timeout_ms~) catch {
      Resized => self.resize_pending = true
      error => raise error
    } noraise {
      event => return event
    }
  }
}

///|
/// Write bytes or UTF-8 text to the terminal output handle.
///
/// The write is serialized through an internal lock, so a single call lands on
/// the terminal atomically even when multiple tasks write concurrently. To make
/// a multi-call sequence atomic, assemble it into one buffer and issue a single
/// `write`.
pub async fn Tty::write(self : Self, data : &@async/io.Data) -> Unit {
  let bytes = data.binary()
  self.write_lock.with_lock(() => backend_write(self.backend, bytes[:]))
}

///|
/// Query the terminal cursor position.
///
/// The returned row and column are 1-based. User input received while waiting
/// for the terminal response is preserved for later `Tty::read_event` calls.
pub async fn Tty::query_cursor_position(
  self : Self,
  timeout_ms~ : Int32 = 50,
) -> CursorPosition? {
  @async.with_timeout_opt(timeout_ms, () => {
    self.write(@vt.request_cursor_position)
    for ;; {
      match self.read_internal_event() {
        CursorPosition(row~, col~) => return { row, col, }
        Input(event) => self.pending_input.push(event)
        KeyboardEnhancementFlags(_) => ()
        PrimaryDeviceAttributes(_) => ()
        DynamicColor(..) => ()
      }
    }
  })
}

///|
/// Query whether the terminal supports the kitty keyboard protocol.
///
/// User input received while waiting for terminal responses is preserved for
/// later `Tty::read_event` calls.
pub async fn Tty::query_kitty_keyboard_support(
  self : Self,
  timeout_ms~ : Int32 = 50,
) -> Bool {
  @async.with_timeout_opt(timeout_ms, () => {
    self.write(@vt.query_keyboard_enhancement_flags)
    self.write(@vt.request_primary_device_attributes)
    for ;; {
      match self.read_internal_event() {
        KeyboardEnhancementFlags(_) => return true
        PrimaryDeviceAttributes(_) => return false
        CursorPosition(..) => ()
        DynamicColor(..) => ()
        Input(event) => self.pending_input.push(event)
      }
    }
  }).unwrap_or(false)
}

///|
/// Query the terminal default foreground color.
///
/// The returned RGB components are 16-bit values in the range `0..65535`.
/// User input received while waiting for the terminal response is preserved for
/// later `Tty::read_event` calls.
pub async fn Tty::query_default_foreground_color(
  self : Self,
  timeout_ms~ : Int32 = 50,
) -> @color.Rgb16? {
  self.query_dynamic_color(10, @vt.query_default_foreground_color, timeout_ms~)
}

///|
/// Query the terminal default background color.
///
/// The returned RGB components are 16-bit values in the range `0..65535`.
/// User input received while waiting for the terminal response is preserved for
/// later `Tty::read_event` calls.
pub async fn Tty::query_default_background_color(
  self : Self,
  timeout_ms~ : Int32 = 50,
) -> @color.Rgb16? {
  self.query_dynamic_color(11, @vt.query_default_background_color, timeout_ms~)
}

///|
/// Query the terminal text cursor color.
///
/// The returned RGB components are 16-bit values in the range `0..65535`.
/// User input received while waiting for the terminal response is preserved for
/// later `Tty::read_event` calls.
pub async fn Tty::query_cursor_color(
  self : Self,
  timeout_ms~ : Int32 = 50,
) -> @color.Rgb16? {
  self.query_dynamic_color(12, @vt.query_cursor_color, timeout_ms~)
}

///|
async fn Tty::query_dynamic_color(
  self : Self,
  expected_code : Int32,
  request : Bytes,
  timeout_ms~ : Int32,
) -> @color.Rgb16? {
  @async.with_timeout_opt(timeout_ms, () => {
    self.write(request)
    for ;; {
      match self.read_internal_event() {
        DynamicColor(code~, red~, green~, blue~) if code == expected_code =>
          return { red, green, blue, }
        DynamicColor(..) => ()
        CursorPosition(..) => ()
        KeyboardEnhancementFlags(_) => ()
        PrimaryDeviceAttributes(_) => ()
        Input(event) => self.pending_input.push(event)
      }
    }
  })
}