///|
/// PostgreSQL v3 pooled connection, LRU prepared statement cache,
/// cancellation propagation (`CancelRequest` + `Lease::mark_tainted`), and `SqlDriver`/`SqlTx` implementation.

///|
priv struct CachedStmt {
  name : String
  fields : Array[@proto.FieldDesc]
}

///|
/// Per-connection LRU prepared statement cache.
priv struct StmtLruCache {
  max_entries : Int32
  entries : Map[String, CachedStmt]
  order : Array[String] // oldest at index 0, newest at end
  mut seq : Int32
}

///|
fn StmtLruCache::StmtLruCache(max_entries : Int32) -> StmtLruCache {
  { max_entries, entries: Map([]), order: [], seq: 0, }
}

///|
fn StmtLruCache::touch(self : StmtLruCache, sql : String) -> Unit {
  let mut idx = -1
  for i in 0..= 0 {
    ignore(self.order.remove(idx))
    self.order.push(sql)
  }
}

///|
fn StmtLruCache::get(self : StmtLruCache, sql : String) -> CachedStmt? {
  match self.entries.get(sql) {
    Some(entry) => {
      self.touch(sql)
      Some(entry)
    }
    None => None
  }
}

///|
fn StmtLruCache::next_name(self : StmtLruCache) -> String {
  self.seq += 1
  "ciallo_s_\{self.seq}"
}

///|
/// Inserts a prepared statement into the cache, returning any evicted statement name to close on the server.
fn StmtLruCache::put(
  self : StmtLruCache,
  sql : String,
  stmt : CachedStmt,
) -> String? {
  if self.max_entries <= 0 {
    return None
  }
  if self.entries.contains(sql) {
    self.entries[sql] = stmt
    self.touch(sql)
    return None
  }
  let mut evicted : String? = None
  if self.order.length() >= self.max_entries {
    let oldest_sql = self.order.remove(0)
    match self.entries.get(oldest_sql) {
      Some(old) => evicted = Some(old.name)
      None => ()
    }
    self.entries.remove(oldest_sql)
  }
  self.entries[sql] = stmt
  self.order.push(sql)
  evicted
}

///|
fn concat_frames(frames : Array[Bytes]) -> Bytes {
  let buf = Buffer()
  for f in frames {
    buf.write_bytesview(f[:])
  }
  buf.to_bytes()
}

///|
/// Active PostgreSQL wire-protocol v3 connection with LRU statement cache.
pub struct PgConnection {
  priv transport : &PgTransport
  priv decoder : @proto.PgDecoder
  priv stmt_cache : StmtLruCache
  priv mut process_id : Int32
  priv mut secret_key : Int32
  priv mut tx_status : Byte
  priv mut wire_synced : Bool
  priv mut closed : Bool
}

///|
async fn PgConnection::recv_message(
  self : PgConnection,
) -> @proto.BackendMessage raise @codec.DataError {
  for ;; {
    match self.decoder.next_message() {
      Some(msg) => return msg
      None =>
        match self.transport.read_chunk() {
          Some(chunk) => self.decoder.feed(chunk[:])
          None =>
            raise @codec.DataError::ConnectionFailed(
              "PostgreSQL server closed connection unexpectedly",
            )
        }
    }
  }
}

///|
/// Performs the PG v3 Startup + Authentication (Cleartext / SCRAM-SHA-256) handshake.
pub async fn PgConnection::handshake(
  transport : &PgTransport,
  config : PgConfig,
  scram_nonce? : String,
) -> PgConnection raise @codec.DataError {
  let conn : PgConnection = {
    transport,
    decoder: @proto.PgDecoder::PgDecoder(),
    stmt_cache: StmtLruCache::StmtLruCache(config.statement_cache_size),
    process_id: 0,
    secret_key: 0,
    tx_status: b'I',
    wire_synced: true,
    closed: false,
  }
  let startup = @proto.encode_startup(
    user=config.user,
    database=config.database,
    params=[("application_name", config.application_name)],
  )
  conn.transport.write_all(startup)
  let mut scram_client : @proto.ScramClient? = None
  let mut scram_verified = false
  for ;; {
    match conn.recv_message() {
      @proto.BackendMessage::Authentication(@proto.AuthRequest::Ok) =>
        if scram_client is Some(_) && !scram_verified {
          raise @codec.DataError::AuthFailed(
            "PostgreSQL server skipped SCRAM-SHA-256 server-final verification",
          )
        }
      @proto.BackendMessage::Authentication(
        @proto.AuthRequest::CleartextPassword,
      ) =>
        conn.transport.write_all(
          @proto.encode_password_message(config.password),
        )
      @proto.BackendMessage::Authentication(@proto.AuthRequest::Sasl(mechs)) => {
        let mut supports_scram = false
        for m in mechs {
          if m == "SCRAM-SHA-256" {
            supports_scram = true
            break
          }
        }
        if !supports_scram {
          raise @codec.DataError::AuthFailed(
            "PostgreSQL server does not advertise SCRAM-SHA-256",
          )
        }
        let nonce = match scram_nonce {
          Some(n) => n
          None => generate_scram_nonce()
        }
        let client = @proto.ScramClient::ScramClient(
          user=config.user,
          password=config.password,
          client_nonce=nonce,
        )
        let first = client.client_first_message()
        scram_client = Some(client)
        conn.transport.write_all(
          @proto.encode_sasl_initial_response("SCRAM-SHA-256", first[:]),
        )
      }
      @proto.BackendMessage::Authentication(
        @proto.AuthRequest::SaslContinue(data),
      ) =>
        match scram_client {
          Some(client) => {
            let final_msg = client.process_server_first(data[:])
            conn.transport.write_all(@proto.encode_sasl_response(final_msg[:]))
          }
          None =>
            raise @codec.DataError::AuthFailed(
              "unexpected SASLContinue without active SCRAM client",
            )
        }
      @proto.BackendMessage::Authentication(@proto.AuthRequest::SaslFinal(data)) =>
        match scram_client {
          Some(client) => {
            client.verify_server_final(data[:])
            scram_verified = true
          }
          None =>
            raise @codec.DataError::AuthFailed(
              "unexpected SASLFinal without active SCRAM client",
            )
        }
      @proto.BackendMessage::Authentication(@proto.AuthRequest::Md5Password(_)) =>
        raise @codec.DataError::AuthFailed(
          "MD5 authentication is deprecated; configure PostgreSQL with scram-sha-256",
        )
      @proto.BackendMessage::Authentication(@proto.AuthRequest::Unsupported(c)) =>
        raise @codec.DataError::AuthFailed(
          "unsupported PostgreSQL auth code: \{c}",
        )
      @proto.BackendMessage::BackendKeyData(process_id~, secret_key~) => {
        conn.process_id = process_id
        conn.secret_key = secret_key
      }
      @proto.BackendMessage::ParameterStatus(..) => ()
      @proto.BackendMessage::NoticeResponse(_) => ()
      @proto.BackendMessage::ReadyForQuery(status~) => {
        if scram_client is Some(_) && !scram_verified {
          raise @codec.DataError::AuthFailed(
            "PostgreSQL server reached ReadyForQuery without completing SCRAM-SHA-256 verification",
          )
        }
        conn.tx_status = status
        return conn
      }
      @proto.BackendMessage::ErrorResponse(err) =>
        raise @proto.map_pg_error(err)
      _ => ()
    }
  }
}

///|
pub fn PgConnection::backend_key(self : PgConnection) -> (Int32, Int32) {
  (self.process_id, self.secret_key)
}

///|
pub fn PgConnection::cached_statement_count(self : PgConnection) -> Int32 {
  self.stmt_cache.entries.length()
}

///|
pub async fn PgConnection::close(self : PgConnection) -> Unit {
  if self.closed {
    return
  }
  self.closed = true
  self.transport.write_all(@proto.encode_terminate()) catch {
    _ => ()
  }
  self.transport.close()
}

///|
/// Runs a parameterized SQL query using PostgreSQL Extended Query Protocol with LRU prepared statement caching.
pub async fn PgConnection::run_extended(
  self : PgConnection,
  sql : String,
  params : Array[@orm_schema.SqlValue],
) -> (Array[@orm_schema.SqlRow], Int64) raise @codec.DataError {
  if self.closed {
    raise @codec.DataError::ConnectionFailed("PostgreSQL connection is closed")
  }
  let encoded_params : Array[Bytes?] = params.map(@proto.encode_sql_param)
  let cached = self.stmt_cache.get(sql)
  let frames : Array[Bytes] = []
  let mut active_fields : Array[@proto.FieldDesc] = []
  let mut preparing_name : String? = None
  let mut cache_hit = false
  match cached {
    Some(entry) => {
      cache_hit = true
      active_fields = entry.fields
      frames.push(
        @proto.encode_bind(
          portal_name="",
          stmt_name=entry.name,
          params=encoded_params,
        ),
      )
      frames.push(@proto.encode_execute(portal_name="", max_rows=0))
      frames.push(@proto.encode_sync())
    }
    None => {
      let use_cache = self.stmt_cache.max_entries > 0
      let stmt_name = if use_cache { self.stmt_cache.next_name() } else { "" }
      if use_cache {
        preparing_name = Some(stmt_name)
        // Evict before parsing if already at capacity
        if self.stmt_cache.order.length() >= self.stmt_cache.max_entries {
          let oldest_sql = self.stmt_cache.order.remove(0)
          match self.stmt_cache.entries.get(oldest_sql) {
            Some(old) =>
              frames.push(@proto.encode_close(target=b'S', name=old.name))
            None => ()
          }
          self.stmt_cache.entries.remove(oldest_sql)
        }
      }
      frames.push(@proto.encode_parse(stmt_name~, sql~))
      frames.push(@proto.encode_describe(target=b'S', name=stmt_name))
      frames.push(
        @proto.encode_bind(portal_name="", stmt_name~, params=encoded_params),
      )
      frames.push(@proto.encode_execute(portal_name="", max_rows=0))
      frames.push(@proto.encode_sync())
    }
  }
  self.wire_synced = false
  self.transport.write_all(concat_frames(frames))
  let rows : Array[@orm_schema.SqlRow] = []
  let mut rows_affected = 0L
  let mut first_err : @codec.DataError? = None
  let mut saw_parse_complete = false
  let mut saw_row_desc = false
  let mut active_col_index : @orm_schema.ColumnIndex? = None
  for ;; {
    match self.recv_message() {
      @proto.BackendMessage::ParseComplete => saw_parse_complete = true
      @proto.BackendMessage::BindComplete => ()
      @proto.BackendMessage::CloseComplete => ()
      @proto.BackendMessage::ParameterDescription(_) => ()
      @proto.BackendMessage::NoData => {
        saw_row_desc = true
        active_fields = []
        active_col_index = None
      }
      @proto.BackendMessage::RowDescription(fields) => {
        saw_row_desc = true
        active_fields = fields
        let cols : Array[String] = Array(capacity=fields.length())
        for f in fields {
          cols.push(f.name)
        }
        active_col_index = Some(@orm_schema.ColumnIndex::ColumnIndex(cols))
      }
      @proto.BackendMessage::DataRow(cells) =>
        if first_err is None {
          let col_index = match active_col_index {
            Some(ci) => ci
            None => {
              let cols : Array[String] = Array(capacity=active_fields.length())
              for f in active_fields {
                cols.push(f.name)
              }
              let ci = @orm_schema.ColumnIndex::ColumnIndex(cols)
              active_col_index = Some(ci)
              ci
            }
          }
          let row = @proto.decode_sql_row_indexed(
            active_fields, col_index, cells,
          ) catch {
            e => {
              first_err = Some(e)
              @orm_schema.SqlRow::SqlRow(columns=[], values=[])
            }
          }
          if first_err is None {
            rows.push(row)
          }
        }
      @proto.BackendMessage::CommandComplete(tag) =>
        rows_affected = @proto.parse_command_complete_rows(tag)
      @proto.BackendMessage::EmptyQueryResponse => ()
      @proto.BackendMessage::NoticeResponse(_) => ()
      @proto.BackendMessage::ErrorResponse(err) =>
        if first_err is None {
          first_err = Some(@proto.map_pg_error(err))
        }
      @proto.BackendMessage::ReadyForQuery(status~) => {
        self.tx_status = status
        self.wire_synced = true
        break
      }
      _ => ()
    }
  }
  if !cache_hit {
    match preparing_name {
      Some(name) =>
        if saw_row_desc {
          ignore(self.stmt_cache.put(sql, { name, fields: active_fields, }))
        } else if saw_parse_complete {
          // Parse succeeded on server before Bind/Describe failed; close statement so it does not leak.
          let cleanup = concat_frames([
            @proto.encode_close(target=b'S', name~),
            @proto.encode_sync(),
          ])
          self.wire_synced = false
          self.transport.write_all(cleanup) catch {
            _ => ()
          }
          for ;; {
            let next_msg : @proto.BackendMessage? = Some(self.recv_message()) catch {
              _ => None
            }
            match next_msg {
              Some(@proto.BackendMessage::ReadyForQuery(status~)) => {
                self.tx_status = status
                self.wire_synced = true
                break
              }
              Some(_) => ()
              None => break
            }
          }
        }
      None => ()
    }
  }
  match first_err {
    Some(err) => raise err
    None => (rows, rows_affected)
  }
}

///|
/// Runs a simple SQL command (e.g., `BEGIN`, `COMMIT`, `ROLLBACK`, `SAVEPOINT`).
pub async fn PgConnection::run_simple(
  self : PgConnection,
  sql : String,
) -> Unit raise @codec.DataError {
  if self.closed {
    raise @codec.DataError::ConnectionFailed("PostgreSQL connection is closed")
  }
  self.transport.write_all(@proto.encode_simple_query(sql))
  let mut first_err : @codec.DataError? = None
  for ;; {
    match self.recv_message() {
      @proto.BackendMessage::ErrorResponse(err) =>
        if first_err is None {
          first_err = Some(@proto.map_pg_error(err))
        }
      @proto.BackendMessage::ReadyForQuery(status~) => {
        self.tx_status = status
        break
      }
      _ => ()
    }
  }
  match first_err {
    Some(err) => raise err
    None => ()
  }
}

///|
fn validate_pg_ident(name : String) -> String raise @codec.DataError {
  if name.is_empty() {
    raise @codec.DataError::ProtocolError("empty savepoint name")
  }
  for ch in name {
    let ok = (ch >= 'a' && ch <= 'z') ||
      (ch >= 'A' && ch <= 'Z') ||
      (ch >= '0' && ch <= '9') ||
      ch == '_'
    if !ok {
      raise @codec.DataError::ProtocolError(
        "invalid savepoint identifier: \{name}",
      )
    }
  }
  name
}

///|
/// Pooled PostgreSQL v3 `SqlDriver` with LRU prepared statement caching and cancellation propagation.
pub struct PgDriver {
  priv config : PgConfig
  priv connector : PgConnector
  priv pool : @pool.Pool[PgConnection]
  priv mut active_txs : Int32
  priv tx_cond : @async.Cond
}

///|
/// Creates a `PgDriver` using the platform's default socket connector.
pub fn PgDriver::PgDriver(config : PgConfig) -> PgDriver {
  PgDriver::with_connector(config, default_pg_connector())
}

///|
/// Creates a `PgDriver` from a `postgres://` / `postgresql://` DSN URL.
pub fn PgDriver::from_url(dsn : StringView) -> PgDriver raise @codec.DataError {
  PgDriver::PgDriver(PgConfig::from_url(dsn))
}

///|
fn coerce_pg_data_error(err : Error) -> @codec.DataError {
  match err {
    @codec.DataError::ConnectionFailed(_) as e => e
    @codec.DataError::PoolExhausted(..) as e => e
    @codec.DataError::Timeout(..) as e => e
    @codec.DataError::ProtocolError(_) as e => e
    @codec.DataError::AuthFailed(_) as e => e
    @codec.DataError::DecodeFailed(..) as e => e
    @codec.DataError::NotFound(..) as e => e
    @codec.DataError::UniqueViolation(..) as e => e
    @codec.DataError::ForeignKeyViolation(..) as e => e
    @codec.DataError::SerializationFailure(..) as e => e
    @codec.DataError::OptimisticLockConflict(..) as e => e
    @codec.DataError::TxAlreadyClosed as e => e
    @codec.DataError::BackendError(..) as e => e
    _ => @codec.DataError::ConnectionFailed("PG execution aborted: \{err}")
  }
}

///|
/// Creates a `PgDriver` with a custom `PgConnector` (for testing or custom TLS/Unix-socket transports).
pub fn PgDriver::with_connector(
  config : PgConfig,
  connector : PgConnector,
) -> PgDriver {
  let open_fn = connector.open
  let pool = @pool.Pool::Pool(
    config=config.pool,
    connect=() => {
      let transport = open_fn(config)
      errdefer (@async.protect_from_cancel(() => transport.close()) catch {
        _ => ()
      })
      PgConnection::handshake(transport, config)
    },
    health_check=conn => {
      !conn.closed && conn.wire_synced && conn.tx_status == b'I'
    },
    close=conn => conn.close(),
  )
  { config, connector, pool, active_txs: 0, tx_cond: @async.Cond::Cond(), }
}

///|
async fn PgDriver::acquire_tx_slot(
  self : PgDriver,
) -> Unit raise @codec.DataError {
  let limit = self.config.pool.max_connections
  if limit <= 0 {
    self.active_txs += 1
    return
  }
  if self.active_txs < limit {
    self.active_txs += 1
    return
  }
  let got = @async.with_timeout_opt(self.config.pool.acquire_timeout_ms, () => {
    while self.active_txs >= limit {
      self.tx_cond.wait()
    }
  }) catch {
    err => raise coerce_pg_data_error(err)
  }
  match got {
    Some(_) => self.active_txs += 1
    None =>
      raise @codec.DataError::PoolExhausted(
        timeout_ms=self.config.pool.acquire_timeout_ms,
      )
  }
}

///|
fn PgDriver::release_tx_slot(self : PgDriver) -> Unit {
  if self.active_txs > 0 {
    self.active_txs -= 1
  }
  self.tx_cond.signal()
}

///|
pub fn PgDriver::pool_stats(self : PgDriver) -> @pool.PoolStats {
  self.pool.stats()
}

///|
pub async fn PgDriver::close(self : PgDriver) -> Unit {
  self.pool.close()
}

///|
async fn PgDriver::fire_cancel(self : PgDriver, conn : PgConnection) -> Unit {
  let (pid, secret) = conn.backend_key()
  if pid != 0 {
    let cancel_fn = self.connector.cancel
    let cfg = self.config
    // Always run out-of-band cancel in an unshielded child task with bounded timeout
    @async.with_task_group(group => {
      group.spawn_bg(allow_failure=true, () => {
        ignore(
          @async.with_timeout_opt(cfg.cancel_timeout_ms, () => {
            cancel_fn(cfg, pid, secret)
          }),
        )
      })
    })
  }
}

///|
async fn PgDriver::exec_pooled(
  self : PgDriver,
  sql : String,
  params : Array[@orm_schema.SqlValue],
) -> (Array[@orm_schema.SqlRow], Int64) raise @codec.DataError {
  self.pool.with_conn(lease => {
    let conn = lease.conn()
    let completed = Ref(false)
    defer (if !completed.val && !conn.wire_synced {
      lease.mark_tainted()
      @async.protect_from_cancel(() => self.fire_cancel(conn)) catch {
        _ => ()
      }
    })
    let res = conn.run_extended(sql, params)
    completed.val = true
    res
  }) catch {
    err => raise coerce_pg_data_error(err)
  }
}

///|
priv struct PgTx {
  driver : PgDriver
  conn : PgConnection
  mut closed : Bool
}

///|
impl @driver.SqlTx for PgTx with fn dialect(_self) -> @dialect.DialectKind {
  @dialect.DialectKind::Postgres
}

///|
impl @driver.SqlTx for PgTx with fn query_rows(self, sql, params) -> Array[
  @orm_schema.SqlRow,
] raise @codec.DataError {
  if self.closed {
    raise @codec.DataError::TxAlreadyClosed
  }
  let completed = Ref(false)
  defer (if !completed.val && !self.conn.wire_synced {
    @async.protect_from_cancel(() => self.driver.fire_cancel(self.conn)) catch {
      _ => ()
    }
  })
  let (rows, _) = self.conn.run_extended(sql, params)
  completed.val = true
  rows
}

///|
impl @driver.SqlTx for PgTx with fn execute(self, sql, params) -> @driver.ExecResult raise @codec.DataError {
  if self.closed {
    raise @codec.DataError::TxAlreadyClosed
  }
  let completed = Ref(false)
  defer (if !completed.val && !self.conn.wire_synced {
    @async.protect_from_cancel(() => self.driver.fire_cancel(self.conn)) catch {
      _ => ()
    }
  })
  let (_, affected) = self.conn.run_extended(sql, params)
  completed.val = true
  @driver.ExecResult::ExecResult(rows_affected=affected)
}

///|
impl @driver.SqlTx for PgTx with fn savepoint(self, name) -> Unit raise @codec.DataError {
  if self.closed {
    raise @codec.DataError::TxAlreadyClosed
  }
  let safe = validate_pg_ident(name)
  self.conn.run_simple("SAVEPOINT \{safe}")
}

///|
impl @driver.SqlTx for PgTx with fn release_savepoint(self, name) -> Unit raise @codec.DataError {
  if self.closed {
    raise @codec.DataError::TxAlreadyClosed
  }
  let safe = validate_pg_ident(name)
  self.conn.run_simple("RELEASE SAVEPOINT \{safe}")
}

///|
impl @driver.SqlTx for PgTx with fn rollback_to_savepoint(self, name) -> Unit raise @codec.DataError {
  if self.closed {
    raise @codec.DataError::TxAlreadyClosed
  }
  let safe = validate_pg_ident(name)
  self.conn.run_simple("ROLLBACK TO SAVEPOINT \{safe}")
}

///|
impl @driver.SqlTx for PgTx with fn commit(self) -> Unit raise @codec.DataError {
  if self.closed {
    raise @codec.DataError::TxAlreadyClosed
  }
  self.closed = true
  defer {
    @async.protect_from_cancel(() => self.conn.close()) catch {
      _ => ()
    }
    self.driver.release_tx_slot()
  }
  self.conn.run_simple("COMMIT")
}

///|
impl @driver.SqlTx for PgTx with fn rollback(self) -> Unit raise @codec.DataError {
  if self.closed {
    return
  }
  self.closed = true
  defer {
    @async.protect_from_cancel(() => self.conn.close()) catch {
      _ => ()
    }
    self.driver.release_tx_slot()
  }
  self.conn.run_simple("ROLLBACK")
}

///|
pub impl @driver.SqlDriver for PgDriver with fn dialect(_self) -> @dialect.DialectKind {
  @dialect.DialectKind::Postgres
}

///|
pub impl @driver.SqlDriver for PgDriver with fn query_rows(self, sql, params) -> Array[
  @orm_schema.SqlRow,
] raise @codec.DataError {
  let (rows, _) = self.exec_pooled(sql, params)
  rows
}

///|
pub impl @driver.SqlDriver for PgDriver with fn execute(self, sql, params) -> @driver.ExecResult raise @codec.DataError {
  let (_, affected) = self.exec_pooled(sql, params)
  @driver.ExecResult::ExecResult(rows_affected=affected)
}

///|
pub impl @driver.SqlDriver for PgDriver with fn begin_tx(self) -> &@driver.SqlTx raise @codec.DataError {
  self.acquire_tx_slot()
  errdefer self.release_tx_slot()
  let transport = (self.connector.open)(self.config)
  let conn = {
    errdefer (@async.protect_from_cancel(() => transport.close()) catch {
      _ => ()
    })
    PgConnection::handshake(transport, self.config)
  }
  errdefer (@async.protect_from_cancel(() => conn.close()) catch { _ => () })
  conn.run_simple("BEGIN")
  let tx : PgTx = { driver: self, conn, closed: false, }
  tx as &@driver.SqlTx
}