///|
/// 强类型 SQL 参数与结果单元格值(四目标纯核)
#derive(Debug, Eq)
pub(all) enum SqlValue {
  Null
  Bool(Bool)
  Int32(Int32)
  Int64(Int64)
  Double(Double)
  Text(String)
  Bytes(Bytes)
  Json(Json)
}

///|
pub(open) trait ToSqlValue {
  fn to_sql_value(Self) -> SqlValue
}

///|
pub(open) trait FromSqlValue {
  fn from_sql_value(SqlValue) -> Self raise @codec.DataError
}

///|
pub impl ToSqlValue for SqlValue with fn to_sql_value(self) -> SqlValue {
  self
}

///|
pub impl FromSqlValue for SqlValue with fn from_sql_value(v) -> SqlValue raise @codec.DataError {
  v
}

///|
pub impl ToSqlValue for Bool with fn to_sql_value(self) -> SqlValue {
  SqlValue::Bool(self)
}

///|
pub impl ToSqlValue for Int32 with fn to_sql_value(self) -> SqlValue {
  SqlValue::Int32(self)
}

///|
pub impl ToSqlValue for Int64 with fn to_sql_value(self) -> SqlValue {
  SqlValue::Int64(self)
}

///|
pub impl ToSqlValue for Double with fn to_sql_value(self) -> SqlValue {
  SqlValue::Double(self)
}

///|
pub impl ToSqlValue for String with fn to_sql_value(self) -> SqlValue {
  SqlValue::Text(self)
}

///|
pub impl ToSqlValue for Bytes with fn to_sql_value(self) -> SqlValue {
  SqlValue::Bytes(self)
}

///|
pub impl ToSqlValue for Json with fn to_sql_value(self) -> SqlValue {
  SqlValue::Json(self)
}

///|
pub impl[T : ToSqlValue] ToSqlValue for T? with fn to_sql_value(self) -> SqlValue {
  match self {
    Some(v) => ToSqlValue::to_sql_value(v)
    None => SqlValue::Null
  }
}

///|
pub impl FromSqlValue for Bool with fn from_sql_value(v) -> Bool raise @codec.DataError {
  match v {
    Bool(b) => b
    Int32(n) => n != 0
    Int64(n) => n != 0L
    _ =>
      raise @codec.DataError::DecodeFailed(
        field="",
        message="expected Bool SqlValue",
      )
  }
}

///|
pub impl FromSqlValue for Int32 with fn from_sql_value(v) -> Int32 raise @codec.DataError {
  match v {
    Int32(n) => n
    Int64(n) => n.to_int()
    _ =>
      raise @codec.DataError::DecodeFailed(
        field="",
        message="expected Int32 SqlValue",
      )
  }
}

///|
pub impl FromSqlValue for Int64 with fn from_sql_value(v) -> Int64 raise @codec.DataError {
  match v {
    Int64(n) => n
    Int32(n) => n.to_int64()
    Text(s) =>
      @string.parse_int64(s) catch {
        _ =>
          raise @codec.DataError::DecodeFailed(
            field="",
            message="invalid Int64 text SqlValue: '\{s}'",
          )
      }
    _ =>
      raise @codec.DataError::DecodeFailed(
        field="",
        message="expected Int64 SqlValue",
      )
  }
}

///|
pub impl FromSqlValue for Double with fn from_sql_value(v) -> Double raise @codec.DataError {
  match v {
    Double(d) => d
    Int32(n) => n.to_double()
    Int64(n) => n.to_double()
    _ =>
      raise @codec.DataError::DecodeFailed(
        field="",
        message="expected Double SqlValue",
      )
  }
}

///|
pub impl FromSqlValue for String with fn from_sql_value(v) -> String raise @codec.DataError {
  match v {
    Text(s) => s
    _ =>
      raise @codec.DataError::DecodeFailed(
        field="",
        message="expected Text SqlValue",
      )
  }
}

///|
pub impl FromSqlValue for Bytes with fn from_sql_value(v) -> Bytes raise @codec.DataError {
  match v {
    Bytes(b) => b
    _ =>
      raise @codec.DataError::DecodeFailed(
        field="",
        message="expected Bytes SqlValue",
      )
  }
}

///|
pub impl FromSqlValue for Json with fn from_sql_value(v) -> Json raise @codec.DataError {
  match v {
    Json(j) => j
    Text(s) =>
      @json.parse(s) catch {
        err =>
          raise @codec.DataError::DecodeFailed(
            field="",
            message="invalid JSON text: \{err}",
          )
      }
    _ =>
      raise @codec.DataError::DecodeFailed(
        field="",
        message="expected Json or Text SqlValue",
      )
  }
}

///|
pub impl[T : FromSqlValue] FromSqlValue for T? with fn from_sql_value(v) -> T? raise @codec.DataError {
  match v {
    Null => None
    other => Some(FromSqlValue::from_sql_value(other))
  }
}

///|
/// 任意 ToJson/FromJson 类型自动桥接为 JSON/JSONB 列
#derive(Debug, Eq)
pub(all) struct JsonCol[T](T)

///|
pub impl[T : ToJson] ToSqlValue for JsonCol[T] with fn to_sql_value(self) -> SqlValue {
  SqlValue::Json(ToJson::to_json(self.0))
}

///|
pub impl[T : @json.FromJson] FromSqlValue for JsonCol[T] with fn from_sql_value(
  v,
) -> JsonCol[T] raise @codec.DataError {
  let j : Json = FromSqlValue::from_sql_value(v)
  let decoded : T = @json.from_json(j) catch {
    err =>
      raise @codec.DataError::DecodeFailed(
        field="",
        message="JSON decode failed: \{err}",
      )
  }
  JsonCol(decoded)
}

///|
/// Read-only shared column-name-to-index map built once per SQL result set.
/// All `SqlRow` instances from the same query share one `ColumnIndex` for O(1) lookups.
#derive(Debug, Eq)
pub struct ColumnIndex {
  priv columns : Array[String]
  priv index : Map[String, Int32]
}

///|
pub fn ColumnIndex::ColumnIndex(columns : Array[String]) -> ColumnIndex {
  let copied = columns.copy()
  let index : Map[String, Int32] = Map([])
  for i in 0.. Array[String] {
  self.columns.copy()
}

///|
pub fn ColumnIndex::index_of(self : ColumnIndex, name : StringView) -> Int32? {
  self.index.get(name.to_owned())
}

///|
/// Returns true if this result set's columns match `expected` in exact positional order.
pub fn ColumnIndex::matches_columns(
  self : ColumnIndex,
  expected : Array[String],
) -> Bool {
  if self.columns.length() != expected.length() {
    return false
  }
  for i in 0.. Bool {
  self.columns == other.columns && self.values == other.values
}

///|
pub impl Debug for SqlRow with fn to_repr(self) -> Repr {
  Repr::record({ "columns": Repr(self.columns), "values": Repr(self.values) })
}

///|
pub fn SqlRow::SqlRow(
  columns~ : Array[String],
  values~ : Array[SqlValue],
) -> SqlRow {
  { columns, values, col_index: None, }
}

///|
/// Constructs a `SqlRow` sharing an existing result-set `ColumnIndex` without copying `columns`.
pub fn SqlRow::with_index(
  index : ColumnIndex,
  values : Array[SqlValue],
) -> SqlRow {
  { columns: index.columns, values, col_index: Some(index), }
}

///|
/// Returns true if this row's columns match `expected` in exact positional order,
/// enabling O(1) `decode_at(0)`, `decode_at(1)`, ... fast paths without hash lookups.
pub fn SqlRow::matches_columns(self : SqlRow, expected : Array[String]) -> Bool {
  match self.col_index {
    Some(ci) => ci.matches_columns(expected)
    None => {
      if self.columns.length() != expected.length() {
        return false
      }
      for i in 0.. SqlValue raise @codec.DataError {
  if index < 0 || index >= self.values.length() {
    raise @codec.DataError::DecodeFailed(
      field="[\{index}]",
      message="column index \{index} out of bounds (len=\{self.values.length()})",
    )
  }
  self.values[index]
}

///|
pub fn SqlRow::get_by_name(
  self : SqlRow,
  name : StringView,
) -> SqlValue raise @codec.DataError {
  match self.col_index {
    Some(ci) =>
      match ci.index_of(name) {
        Some(idx) => return self.get_at(idx)
        None => {
          let target = name.to_owned()
          raise @codec.DataError::DecodeFailed(
            field=target,
            message="column '\{target}' not found in row",
          )
        }
      }
    None =>
      if self.columns.length() > 4 {
        let ci = ColumnIndex::ColumnIndex(self.columns)
        self.col_index = Some(ci)
        match ci.index_of(name) {
          Some(idx) => return self.get_at(idx)
          None => {
            let target = name.to_owned()
            raise @codec.DataError::DecodeFailed(
              field=target,
              message="column '\{target}' not found in row",
            )
          }
        }
      } else {
        for i in 0.. T raise @codec.DataError {
  let raw = self.get_at(index)
  FromSqlValue::from_sql_value(raw)
}

///|
pub fn[T : FromSqlValue] SqlRow::decode_by_name(
  self : SqlRow,
  name : StringView,
) -> T raise @codec.DataError {
  let raw = self.get_by_name(name)
  FromSqlValue::from_sql_value(raw)
}

///|
pub(open) trait FromRow {
  fn from_row(SqlRow) -> Self raise @codec.DataError
}

///|
pub impl FromRow for SqlRow with fn from_row(row) -> SqlRow raise @codec.DataError {
  row
}