//! 独立性能参考共用的 SQLite 资源责任；仅依赖官方库，不链接 Dever。
use deadpool_sqlite::{
    Object, Pool, Runtime,
    rusqlite::{self, Connection},
};
use std::{
    error::Error,
    panic::{AssertUnwindSafe, catch_unwind},
    sync::{Arc, Mutex},
    time::Duration,
};
use tokio::{sync::Semaphore, time::Instant};
use tokio_util::{sync::CancellationToken, task::TaskTracker};
pub(crate) type Result<T> = std::result::Result<T, Box<dyn Error + Send + Sync>>;

pub(crate) struct Lease {
    pub(crate) object: Option<Object>,
    pub(crate) reusable: bool,
}
impl Drop for Lease {
    fn drop(&mut self) {
        if !self.reusable {
            drop(Object::take(self.object.take().unwrap()));
        }
    }
}

pub(crate) struct Work {
    tasks: TaskTracker,
    pub(crate) slots: Arc<Semaphore>,
    faults: Arc<Mutex<Vec<String>>>,
}
impl Work {
    pub(crate) fn new() -> Self {
        Self {
            tasks: TaskTracker::new(),
            slots: Arc::new(Semaphore::new(8)),
            faults: Default::default(),
        }
    }

    pub(crate) async fn call<T: Send + 'static>(
        &self,
        lease: &mut Option<Lease>,
        timeout: Duration,
        run: impl FnOnce(&mut Connection) -> Result<T> + Send + 'static,
    ) -> Result<T> {
        let deadline = Instant::now() + timeout;
        let cancelled = CancellationToken::new();
        let _cancel = cancelled.clone().drop_guard();
        let slot = tokio::time::timeout_at(deadline, self.slots.clone().acquire_owned()).await??;
        let mut owned = lease.take().ok_or("discarded connection")?;
        owned.reusable = false;
        let faults = self.faults.clone();
        // 令牌随结果释放，调用取消时也等到连接被归还或丢弃后才算排空。
        let tracking = self.tasks.token();
        let job = tokio::task::spawn_blocking(move || {
            let result = catch_unwind(AssertUnwindSafe(|| -> Result<T> {
                let mut connection = owned
                    .object
                    .as_ref()
                    .unwrap()
                    .lock()
                    .map_err(|_| "poisoned SQLite connection")?;
                if cancelled.is_cancelled() || Instant::now() >= deadline {
                    return Err("SQLite operation cancelled or expired".into());
                }
                let signal = cancelled.clone();
                connection.progress_handler(
                    1000,
                    Some(move || signal.is_cancelled() || Instant::now() >= deadline),
                )?;
                let value = run(&mut connection);
                connection.progress_handler(0, None::<fn() -> bool>)?;
                if cancelled.is_cancelled() || Instant::now() >= deadline {
                    return Err("SQLite operation cancelled or expired".into());
                }
                owned.reusable = connection.is_autocommit();
                value
            }));
            let result = result.unwrap_or_else(|panic| {
                let message = panic_message(panic);
                faults.lock().unwrap().push(message.clone());
                Err(message.into())
            });
            drop(slot);
            (owned, result, tracking)
        });
        let (owned, result, _tracking) = tokio::time::timeout_at(deadline, job).await??;
        *lease = Some(owned);
        result
    }

    pub(crate) async fn finish(&self) -> Result<()> {
        self.tasks.close();
        self.tasks.wait().await;
        let faults = std::mem::take(&mut *self.faults.lock().unwrap());
        if !faults.is_empty() {
            return Err(faults.join("; ").into());
        }
        Ok(())
    }
}

pub(crate) fn panic_message(panic: Box<dyn std::any::Any + Send>) -> String {
    panic
        .downcast_ref::<&str>()
        .copied()
        .or_else(|| panic.downcast_ref::<String>().map(String::as_str))
        .unwrap_or("non-text Rust panic")
        .to_owned()
}

pub(crate) async fn pool(path: &str, connections: usize) -> Result<Pool> {
    use deadpool_sqlite::{Hook, HookError, Timeouts};
    // 输入是测量驱动创建的实际路径；URI 编码避免路径中的 '?' 改写打开模式。
    const URI_PATH: &percent_encoding::AsciiSet =
        &percent_encoding::CONTROLS.add(b'%').add(b'?').add(b'#');
    let uri = format!(
        "file:{}?mode=rw",
        percent_encoding::utf8_percent_encode(path, URI_PATH)
    );
    let timeout = Duration::from_secs(30);
    Ok(deadpool_sqlite::Config::new(uri).builder(Runtime::Tokio1)?
        .max_size(connections)
        .timeouts(Timeouts { wait: Some(Duration::from_secs(5)), create: Some(timeout), recycle: Some(timeout) })
        .post_create(Hook::async_fn(move |object, _| Box::pin(async move {
            object.interact(move |connection| {
                connection.busy_timeout(timeout)?;
                connection.create_scalar_function("_dever_length", 1,
                    rusqlite::functions::FunctionFlags::SQLITE_UTF8
                    | rusqlite::functions::FunctionFlags::SQLITE_DETERMINISTIC
                    | rusqlite::functions::FunctionFlags::SQLITE_INNOCUOUS,
                    |ctx| Ok(ctx.get_raw(0).as_str()
                        .map_err(|error| rusqlite::Error::UserFunctionError(Box::new(error)))?
                        .chars().count() as i64))?;
                connection.execute_batch("PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA synchronous=NORMAL;")
            }).await.map_err(|error| HookError::message(error.to_string()))?
                .map_err(HookError::Backend)
        })))
        .build()?)
}
