///|
/// Computes lowercase hex SHA-256 of a UTF-8 string using shared `unmbt/webstd/crypto`.
pub fn sha256_str_hex(s : StringView) -> String {
  @crypto.sha256_hex(@utf8.encode(s)[:])
}

///|
#derive(Debug, Eq)
pub(all) struct MigrationFile {
  version : String
  name : String
  up_sql : String
  down_sql : String?
}

///|
pub fn MigrationFile::checksum(self : MigrationFile) -> String {
  sha256_str_hex(self.up_sql)
}

///|
#derive(Debug, Eq)
pub(all) struct MigrationRecord {
  version : String
  name : String
  checksum_sha256 : String
  applied_at_ms : Int64
}

///|
#derive(Debug, Eq)
pub(all) struct MigrationStatusEntry {
  version : String
  name : String
  applied : Bool
  checksum_matches : Bool
}

///|
#derive(Debug, Eq)
pub(all) struct SeedFile {
  name : String
  sql : String
}

///|
#derive(Debug, Eq)
pub(all) suberror MigrateError {
  ChecksumDrift(version~ : String, expected~ : String, actual~ : String)
  ApplyFailed(version~ : String, message~ : String)
  RollbackFailed(version~ : String, message~ : String)
}

///|
fn migrations_table_ddl(dialect : @dialect.DialectKind) -> String {
  match dialect {
    @dialect.DialectKind::Postgres =>
      "CREATE TABLE IF NOT EXISTS \"_ciallo_migrations\" (\"version\" TEXT PRIMARY KEY, \"name\" TEXT NOT NULL, \"checksum_sha256\" TEXT NOT NULL, \"applied_at_ms\" BIGINT NOT NULL);"
    _ =>
      "CREATE TABLE IF NOT EXISTS \"_ciallo_migrations\" (\"version\" TEXT PRIMARY KEY, \"name\" TEXT NOT NULL, \"checksum_sha256\" TEXT NOT NULL, \"applied_at_ms\" INTEGER NOT NULL);"
  }
}

///|
fn seeds_table_ddl(dialect : @dialect.DialectKind) -> String {
  match dialect {
    @dialect.DialectKind::Postgres =>
      "CREATE TABLE IF NOT EXISTS \"_ciallo_seeds\" (\"name\" TEXT PRIMARY KEY, \"checksum_sha256\" TEXT NOT NULL, \"applied_at_ms\" BIGINT NOT NULL);"
    _ =>
      "CREATE TABLE IF NOT EXISTS \"_ciallo_seeds\" (\"name\" TEXT PRIMARY KEY, \"checksum_sha256\" TEXT NOT NULL, \"applied_at_ms\" INTEGER NOT NULL);"
  }
}

///|
fn insert_migration_sql(dialect : @dialect.DialectKind) -> String {
  match dialect {
    @dialect.DialectKind::Postgres =>
      "INSERT INTO \"_ciallo_migrations\" (\"version\", \"name\", \"checksum_sha256\", \"applied_at_ms\") VALUES ($1, $2, $3, $4)"
    _ =>
      "INSERT INTO \"_ciallo_migrations\" (\"version\", \"name\", \"checksum_sha256\", \"applied_at_ms\") VALUES (?, ?, ?, ?)"
  }
}

///|
fn insert_seed_sql(dialect : @dialect.DialectKind) -> String {
  match dialect {
    @dialect.DialectKind::Postgres =>
      "INSERT INTO \"_ciallo_seeds\" (\"name\", \"checksum_sha256\", \"applied_at_ms\") VALUES ($1, $2, $3)"
    _ =>
      "INSERT INTO \"_ciallo_seeds\" (\"name\", \"checksum_sha256\", \"applied_at_ms\") VALUES (?, ?, ?)"
  }
}

///|
async fn fetch_applied_records(
  driver : &@driver.SqlDriver,
) -> Array[MigrationRecord] {
  ignore(driver.execute(migrations_table_ddl(driver.dialect()), []))
  let rows = driver.query_rows(
    "SELECT \"version\", \"name\", \"checksum_sha256\", \"applied_at_ms\" FROM \"_ciallo_migrations\" ORDER BY \"version\" ASC",
    [],
  )
  let out : Array[MigrationRecord] = []
  for r in rows {
    out.push({
      version: r.decode_at(0),
      name: r.decode_at(1),
      checksum_sha256: r.decode_at(2),
      applied_at_ms: r.decode_at(3),
    })
  }
  out
}

///|
/// 校验目标库已执行迁移脚本的 SHA-256 校验和,精准拦截历史脚本漂移篡改
pub async fn verify_migrations(
  driver : &@driver.SqlDriver,
  migrations : Array[MigrationFile],
) -> Unit {
  let applied = fetch_applied_records(driver)
  let by_ver : Map[String, MigrationRecord] = Map([])
  for rec in applied {
    by_ver[rec.version] = rec
  }
  for m in migrations {
    match by_ver.get(m.version) {
      Some(rec) => {
        let actual = m.checksum()
        if rec.checksum_sha256 != actual {
          raise MigrateError::ChecksumDrift(
            version=m.version,
            expected=rec.checksum_sha256,
            actual~,
          )
        }
      }
      None => ()
    }
  }
}

///|
/// 查询所有迁移脚本的当前状态(是否已执行及校验和是否一致)
pub async fn migration_status(
  driver : &@driver.SqlDriver,
  migrations : Array[MigrationFile],
) -> Array[MigrationStatusEntry] {
  let applied = fetch_applied_records(driver)
  let by_ver : Map[String, MigrationRecord] = Map([])
  for rec in applied {
    by_ver[rec.version] = rec
  }
  let out : Array[MigrationStatusEntry] = []
  for m in migrations {
    match by_ver.get(m.version) {
      Some(rec) =>
        out.push({
          version: m.version,
          name: m.name,
          applied: true,
          checksum_matches: rec.checksum_sha256 == m.checksum(),
        })
      None =>
        out.push({
          version: m.version,
          name: m.name,
          applied: false,
          checksum_matches: true,
        })
    }
  }
  out
}

///|
/// Splits a multi-statement SQL script into individual statements while respecting
/// single-quoted literals (`'...'`), double-quoted identifiers (`"..."`),
/// dollar-quoted blocks (`$$...$$`), `--` line comments, and `/* ... */` block comments.
pub fn split_sql_statements(sql : StringView) -> Array[String] {
  let s = sql.to_owned()
  let len = s.length()
  let out : Array[String] = []
  let mut start = 0
  let mut i = 0
  let mut in_single = false
  let mut in_double = false
  let mut in_dollar = false
  let mut in_line_comment = false
  let mut in_block_comment = false
  while i < len {
    let ch = s.code_unit_at(i).unsafe_to_char()
    let next : Char? = if i + 1 < len {
      Some(s.code_unit_at(i + 1).unsafe_to_char())
    } else {
      None
    }
    if in_line_comment {
      if ch == '\n' {
        in_line_comment = false
      }
      i += 1
    } else if in_block_comment {
      if ch == '*' && next == Some('/') {
        in_block_comment = false
        i += 2
      } else {
        i += 1
      }
    } else if in_single {
      if ch == '\'' {
        if next == Some('\'') {
          i += 2
        } else {
          in_single = false
          i += 1
        }
      } else {
        i += 1
      }
    } else if in_double {
      if ch == '"' {
        if next == Some('"') {
          i += 2
        } else {
          in_double = false
          i += 1
        }
      } else {
        i += 1
      }
    } else if in_dollar {
      if ch == '$' && next == Some('$') {
        in_dollar = false
        i += 2
      } else {
        i += 1
      }
    } else if ch == '-' && next == Some('-') {
      in_line_comment = true
      i += 2
    } else if ch == '/' && next == Some('*') {
      in_block_comment = true
      i += 2
    } else if ch == '\'' {
      in_single = true
      i += 1
    } else if ch == '"' {
      in_double = true
      i += 1
    } else if ch == '$' && next == Some('$') {
      in_dollar = true
      i += 2
    } else if ch == ';' {
      let piece = s[start:i + 1].trim().to_owned()
      if !piece.is_empty() && piece != ";" {
        out.push(piece)
      }
      start = i + 1
      i += 1
    } else {
      i += 1
    }
  }
  if start < len {
    let tail = s[start:].trim().to_owned()
    if !tail.is_empty() && tail != ";" {
      out.push(tail)
    }
  }
  out
}

///|
fn is_sqlite_fk_toggle_pragma(stmt : String) -> (Bool, Bool) {
  let norm = stmt.trim().to_upper()
  if norm.has_prefix("PRAGMA FOREIGN_KEYS") && norm.contains("OFF") {
    (true, false)
  } else if norm.has_prefix("PRAGMA FOREIGN_KEYS") && norm.contains("ON") {
    (true, true)
  } else {
    (false, false)
  }
}

///|
/// Executes a potentially multi-statement migration script transactionally.
/// Splits statements so PG Extended Query and SQLite `prepare_v2` execute every statement,
/// and hoists SQLite `PRAGMA foreign_keys = OFF/ON` outside the transaction boundary.
async fn exec_script_in_tx(
  driver : &@driver.SqlDriver,
  script : String,
  post_tx_hook : async (&@driver.SqlTx) -> Unit raise @codec.DataError,
) -> Unit raise @codec.DataError {
  let raw_stmts = split_sql_statements(script)
  let is_sqlite = driver.dialect() == @dialect.DialectKind::Sqlite
  let mut disable_fk_outer = false
  let mut enable_fk_outer = false
  let tx_stmts : Array[String] = []
  for stmt in raw_stmts {
    if is_sqlite {
      let (is_toggle, turn_on) = is_sqlite_fk_toggle_pragma(stmt)
      if is_toggle {
        if !turn_on {
          disable_fk_outer = true
        } else {
          enable_fk_outer = true
        }
        continue
      }
    }
    tx_stmts.push(stmt)
  }
  if disable_fk_outer {
    ignore(driver.execute("PRAGMA foreign_keys = OFF;", []))
  }
  defer (if disable_fk_outer || enable_fk_outer {
    @async.protect_from_cancel(() => {
      ignore(driver.execute("PRAGMA foreign_keys = ON;", [])) catch {
        _ => ()
      }
    }) catch {
      _ => ()
    }
  })
  let tx = driver.begin_tx()
  let mut committed = false
  defer (if !committed {
    @async.protect_from_cancel(() => tx.rollback()) catch {
      _ => ()
    }
  })
  for stmt in tx_stmts {
    ignore(tx.execute(stmt, []))
  }
  post_tx_hook(tx)
  tx.commit()
  committed = true
}

///|
/// 事务化顺序执行未应用的迁移脚本(执行前先校验历史防漂移,失败自动回滚)
pub async fn apply_migrations(
  driver : &@driver.SqlDriver,
  migrations : Array[MigrationFile],
) -> Array[MigrationRecord] {
  verify_migrations(driver, migrations)
  let applied = fetch_applied_records(driver)
  let done : Map[String, Bool] = Map([])
  for rec in applied {
    done[rec.version] = true
  }
  let newly_applied : Array[MigrationRecord] = []
  let ins_sql = insert_migration_sql(driver.dialect())
  for m in migrations {
    if done.contains(m.version) {
      continue
    }
    let checksum = m.checksum()
    let now_ms = @async.now()
    let exec_res : Result[Unit, @codec.DataError] = try {
      exec_script_in_tx(driver, m.up_sql, tx => {
        ignore(
          tx.execute(ins_sql, [
            @orm_schema.SqlValue::Text(m.version),
            @orm_schema.SqlValue::Text(m.name),
            @orm_schema.SqlValue::Text(checksum),
            @orm_schema.SqlValue::Int64(now_ms),
          ]),
        )
      })
      Ok(())
    } catch {
      err => Err(err)
    }
    match exec_res {
      Ok(_) =>
        newly_applied.push({
          version: m.version,
          name: m.name,
          checksum_sha256: checksum,
          applied_at_ms: now_ms,
        })
      Err(err) =>
        raise MigrateError::ApplyFailed(
          version=m.version,
          message=err.summary(),
        )
    }
  }
  newly_applied
}

///|
fn delete_migration_sql(dialect : @dialect.DialectKind) -> String {
  match dialect {
    @dialect.DialectKind::Postgres =>
      "DELETE FROM \"_ciallo_migrations\" WHERE \"version\" = $1"
    _ => "DELETE FROM \"_ciallo_migrations\" WHERE \"version\" = ?"
  }
}

///|
/// Rolls back the most recently applied `steps` migrations in reverse order,
/// verifying historical checksums first and executing each migration's `down_sql` transactionally.
pub async fn rollback_migrations(
  driver : &@driver.SqlDriver,
  migrations : Array[MigrationFile],
  steps~ : Int32 = 1,
) -> Array[MigrationRecord] {
  if steps <= 0 {
    return []
  }
  verify_migrations(driver, migrations)
  let applied = fetch_applied_records(driver)
  let by_ver : Map[String, MigrationFile] = Map([])
  for m in migrations {
    by_ver[m.version] = m
  }
  let rolled_back : Array[MigrationRecord] = []
  let del_sql = delete_migration_sql(driver.dialect())
  let mut remaining = steps
  let mut idx = applied.length() - 1
  while idx >= 0 && remaining > 0 {
    let rec = applied[idx]
    let m = match by_ver.get(rec.version) {
      Some(file) => file
      None =>
        raise MigrateError::RollbackFailed(
          version=rec.version,
          message="migration file not found for applied version '\{rec.version}'",
        )
    }
    let down_sql = match m.down_sql {
      Some(sql) if !sql.trim().is_empty() => sql
      _ =>
        raise MigrateError::RollbackFailed(
          version=rec.version,
          message="migration '\{rec.version}' has no down_sql script",
        )
    }
    let exec_res : Result[Unit, @codec.DataError] = try {
      exec_script_in_tx(driver, down_sql, tx => {
        ignore(tx.execute(del_sql, [@orm_schema.SqlValue::Text(rec.version)]))
      })
      Ok(())
    } catch {
      err => Err(err)
    }
    match exec_res {
      Ok(_) => {
        rolled_back.push(rec)
        remaining -= 1
      }
      Err(err) =>
        raise MigrateError::RollbackFailed(
          version=rec.version,
          message=err.summary(),
        )
    }
    idx -= 1
  }
  rolled_back
}

///|
/// 幂等种子执行器:按种子名记录 _ciallo_seeds,重复执行安全跳过已运行种子
pub async fn run_seeds(
  driver : &@driver.SqlDriver,
  seeds : Array[SeedFile],
) -> Array[String] {
  ignore(driver.execute(seeds_table_ddl(driver.dialect()), []))
  let existing_rows = driver.query_rows(
    "SELECT \"name\", \"checksum_sha256\" FROM \"_ciallo_seeds\"",
    [],
  )
  let seen : Map[String, Bool] = Map([])
  for r in existing_rows {
    let name : String = r.decode_at(0)
    seen[name] = true
  }
  let executed : Array[String] = []
  let ins_sql = insert_seed_sql(driver.dialect())
  for s in seeds {
    if seen.contains(s.name) {
      continue
    }
    let checksum = sha256_str_hex(s.sql)
    exec_script_in_tx(driver, s.sql, tx => {
      ignore(
        tx.execute(ins_sql, [
          @orm_schema.SqlValue::Text(s.name),
          @orm_schema.SqlValue::Text(checksum),
          @orm_schema.SqlValue::Int64(@async.now()),
        ]),
      )
    })
    executed.push(s.name)
  }
  executed
}