// Copyright 2026 PaiGack
// Licensed under the Apache License, Version 2.0.
// Ported from jlaffaye/ftp (ISC License), see LICENSE-THIRD-PARTY.

// Package: `PaiGack/ftp` -- the public client API. Layers below it live in
// `core/` (values), `connection/` (control + data channel) and `debug/` (traffic log).

// The FTP client handle and the connection state it carries.
//
// This file merges `client` and `state`: `FTPClient` owns a `Session`, the
// `Session` owns the `@connection.Control` connection, and `Options` is the resolved form
// of the caller facing `DialOptions`. The four types are a single object graph
// and the accessors on `FTPClient` were the only readers of `Session::*`, so
// keeping them in separate files only hid where the state lives.

///|
/// The FTP client, the equivalent of upstream `ftp.ServerConn`.
///
/// Upstream documents this type as *not* safe for concurrent use. We keep the
/// same constraint but enforce it with a `Mutex` so that a misuse shows up as
/// serialized commands instead of a corrupted session — a deliberate
/// improvement over the Go implementation, with unchanged semantics.
pub struct FTPClient {
  /// Connection parameters negotiated at dial/login time.
  options : DialOptions
  /// The same parameters projected onto what the data channel layer needs.
  state_options : Options
  /// The control connection.
  session : Session
  /// Whether the connection is currently open.
  mut closed : Bool
  /// Peer address as given by the caller (`host:port`).
  host : String
  /// Serializes every public operation.
  mutex : @async.Mutex
  /// Capability flags collected from `FEAT`.
  mut mlst_supported : Bool
  mut mfmt_supported : Bool
  mut mdtm_supported : Bool
  mut mdtm_can_write : Bool
  /// The timezone used to interpret `LIST` timestamps.
  mut location : @time.Zone
  /// Feature names advertised by `FEAT`, uppercased.
  mut features : Map[String, Bool]
}

///|
/// Acquire the internal lock, making every public operation serialized.
///
/// Upstream documents `ServerConn` as *not* concurrency safe; enforcing it at
/// runtime is a deliberate improvement that does not change the semantics.
///
/// This is also the guard that refuses to work on a client that already sent
/// `QUIT`. Every public operation takes this lock before touching the control
/// channel, so checking here covers all of them at once instead of leaving the
/// check to each one (where it was missing: `is_closed` existed but only
/// `quit` itself read it). Without it, a command after `quit` was written into
/// a session the server had already hung up on, and the failure surfaced as
/// whichever IO error the dead socket produced -- `ReaderClosed`, a read
/// timeout -- rather than as "this client is closed".
pub async fn FTPClient::lock(self : FTPClient) -> Unit {
  self.mutex.acquire()
  if self.closed {
    self.mutex.release()
    raise @core.FtpError::ParseError(
      msg="the FTP client was already closed with quit(); it cannot be used again",
    )
  }
}

///|
/// Release the internal lock.
pub fn FTPClient::unlock(self : FTPClient) -> Unit {
  self.mutex.release()
}

///|
/// Run `op` while holding the client lock, which every public operation takes
/// to serialize the session.
///
/// The lock is not re-entrant: calling it from inside a public operation that
/// already holds it -- `retr`, `stor`, `list`, `retr_from`, `stor_from`, ... --
/// deadlocks the single task that owns the session. Private helpers that run
/// under an operation's lock (`stream`, `check_data_shut`, this function) must
/// therefore not call back into the public API, and this one is the way a
/// helper outside `client.mbt` can take the lock without racing the operations
/// that already do. `transfer.mbt` uses it to wait for `DataResponse::close`.
///
/// Holds only "ownership of the session" tokens: the reply reads inside use the
/// control channel's own deadline, and the data channel's I/O has no deadline at
/// all (see `docs/porting.md` section on `SetDeadline`), so there is nothing
/// with a timer inside for `defer` to complain about.
pub async fn FTPClient::with_lock(
  self : FTPClient,
  op : async () -> Unit,
) -> Unit {
  self.lock()
  defer self.unlock()
  op()
}

///|
/// Whether the server advertised `name` in its `FEAT` list.
pub fn FTPClient::has_feature(self : FTPClient, name : String) -> Bool {
  self.features.contains(name.to_upper())
}

///|
/// Whether the server advertised `MLST` (and `MLSD` was not disabled
/// explicitly).
pub fn FTPClient::is_mlst_supported(self : FTPClient) -> Bool {
  self.mlst_supported
}

///|
/// Whether the server accepts `MFMT` to set modification times.
pub fn FTPClient::is_mfmt_supported(self : FTPClient) -> Bool {
  self.mfmt_supported
}

///|
/// Whether the server accepts `MDTM` to read modification times.
pub fn FTPClient::is_get_time_supported(self : FTPClient) -> Bool {
  self.mdtm_supported
}

///|
/// Whether the modification time can be written, either via `MFMT` or via the
/// VsFtpd style `MDTM