///|
/// SQLite production configuration (WAL mode, busy timeout, foreign keys, 1-Writer + N-Readers pool).
#derive(Debug, Eq)
pub(all) struct SqliteConfig {
  path : String
  wal_mode : Bool
  synchronous : String
  foreign_keys : Bool
  busy_timeout_ms : Int32
  reader_pool_size : Int32
  acquire_timeout_ms : Int32
}

///|
pub fn SqliteConfig::SqliteConfig(
  path~ : String = ":memory:",
  wal_mode~ : Bool = true,
  synchronous~ : String = "NORMAL",
  foreign_keys~ : Bool = true,
  busy_timeout_ms~ : Int32 = 5000,
  reader_pool_size~ : Int32 = 4,
  acquire_timeout_ms~ : Int32 = 5000,
) -> SqliteConfig {
  {
    path,
    wal_mode,
    synchronous,
    foreign_keys,
    busy_timeout_ms,
    reader_pool_size,
    acquire_timeout_ms,
  }
}

///|
pub fn SqliteConfig::in_memory() -> SqliteConfig {
  SqliteConfig::SqliteConfig(
    path=":memory:",
    wal_mode=false,
    reader_pool_size=1,
  )
}

///|
pub fn SqliteConfig::is_memory(self : SqliteConfig) -> Bool {
  self.path == ":memory:" || self.path.is_empty()
}

///|
/// Maps SQLite extended error codes (e.g. `2067` UNIQUE, `1555` PRIMARYKEY, `787` FOREIGNKEY)
/// and fallback error messages into structured `@codec.DataError`.
pub fn map_sqlite_error(ext_code : Int32, message : String) -> @codec.DataError {
  if ext_code == 2067 || ext_code == 1555 {
    return @codec.DataError::UniqueViolation(
      constraint=if ext_code == 1555 { "sqlite_pk" } else { "sqlite_unique" },
      detail=message,
    )
  }
  if ext_code == 787 {
    return @codec.DataError::ForeignKeyViolation(
      constraint="sqlite_fk",
      detail=message,
    )
  }
  if ext_code == 5 || ext_code == 6 {
    return @codec.DataError::Timeout(op="sqlite_busy", elapsed_ms=0L)
  }
  if message.contains("UNIQUE constraint failed") ||
    message.contains("PRIMARY KEY constraint failed") {
    return @codec.DataError::UniqueViolation(
      constraint="sqlite_unique",
      detail=message,
    )
  }
  if message.contains("FOREIGN KEY constraint failed") {
    return @codec.DataError::ForeignKeyViolation(
      constraint="sqlite_fk",
      detail=message,
    )
  }
  if message.contains("database is locked") || message.contains("SQLITE_BUSY") {
    return @codec.DataError::Timeout(op="sqlite_busy", elapsed_ms=0L)
  }
  @codec.DataError::BackendError(code="SQLITE_\{ext_code}", message~)
}

///|
fn strip_leading_sql_comments(sql : StringView) -> String {
  let s = sql.to_owned()
  let len = s.length()
  let mut i = 0
  while i < len {
    let ch = s.code_unit_at(i).to_int()
    if ch == 32 || ch == 9 || ch == 10 || ch == 13 {
      i += 1
      continue
    }
    if ch == 45 && i + 1 < len && s.code_unit_at(i + 1).to_int() == 45 {
      // Line comment: -- ... \n
      i += 2
      while i < len && s.code_unit_at(i).to_int() != 10 {
        i += 1
      }
      continue
    }
    if ch == 47 && i + 1 < len && s.code_unit_at(i + 1).to_int() == 42 {
      // Block comment: /* ... */
      i += 2
      while i + 1 < len &&
            !(s.code_unit_at(i).to_int() == 42 &&
            s.code_unit_at(i + 1).to_int() == 47) {
        i += 1
      }
      if i + 1 < len {
        i += 2
      } else {
        i = len
      }
      continue
    }
    break
  }
  s[i:].trim().to_owned()
}

///|
/// Determines whether a SQL statement is safely read-only and eligible for the Reader pool.
pub fn is_read_only_sql(sql : StringView) -> Bool {
  let trimmed = strip_leading_sql_comments(sql)
  let upper = trimmed.to_upper()
  if upper.has_prefix("SELECT") || upper.has_prefix("EXPLAIN") {
    return true
  }
  if upper.has_prefix("PRAGMA") {
    return !upper.contains("=")
  }
  if upper.has_prefix("WITH") {
    return !upper.contains("INSERT") &&
      !upper.contains("UPDATE") &&
      !upper.contains("DELETE")
  }
  false
}

///|
fn validate_savepoint_name(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
}