//! 逐操作交接的独立 Job 对端；保留轻量队列参考，不用较慢参考覆盖它。
#[allow(dead_code)]
#[cfg(not(feature = "contract"))]
mod queue;
#[cfg(feature = "contract")]
#[allow(dead_code)]
#[path = "queue.rs"]
mod base_queue;
#[cfg(feature = "contract")]
#[path = "contract.rs"]
mod queue;
mod sqlite_resource;
use deadpool_sqlite::rusqlite::TransactionBehavior;
use futures_util::FutureExt;
use queue::{Batch, Claim, Payload, Submit};
use sqlite_resource::{Lease, Result, Work, panic_message, pool};
use std::{future::Future, panic::AssertUnwindSafe, sync::Arc, time::Duration};
use tokio::time::Instant;

const IO_TIMEOUT: Duration = Duration::from_secs(30);

async fn submit(
    work: &Work,
    lease: &mut Option<Lease>,
    inputs: Vec<Submit>,
) -> Result<Vec<String>> {
    work.call(lease, IO_TIMEOUT, |connection| {
        connection.execute_batch("BEGIN IMMEDIATE")?;
        Ok(())
    })
    .await?;
    let mut ids = Vec::with_capacity(inputs.len());
    for value in inputs {
        ids.push(
            work.call(lease, IO_TIMEOUT, move |connection| {
                queue::enqueue(connection, value)
            })
            .await?,
        );
    }
    work.call(lease, IO_TIMEOUT, |connection| {
        connection.execute_batch("COMMIT")?;
        Ok(())
    })
    .await?;
    Ok(ids)
}

async fn handle(work: &Work, lease: &mut Option<Lease>, input: Payload) -> Result<()> {
    work.call(lease, IO_TIMEOUT, |connection| {
        connection.execute_batch("BEGIN IMMEDIATE")?;
        Ok(())
    })
    .await?;
    let saved = work
        .call(lease, IO_TIMEOUT, move |connection| {
            queue::insert(connection, input)
        })
        .await?;
    if saved.3 < 0 {
        return Err("negative amount".into());
    }
    Ok(())
}

async fn wait<T>(
    work: &Work,
    deadline: Instant,
    handler: impl Future<Output = Result<T>>,
) -> Result<T> {
    let outcome = AssertUnwindSafe(tokio::time::timeout_at(deadline, handler))
        .catch_unwind()
        .await
        .map_err(|panic| panic_message(panic).into())
        .and_then(|value| value.map_err(Into::into))
        .and_then(|value| value);
    // 单 worker 没有并行的其他 Job；复用其 tracker，每次确认前等待真实后代退出。
    let cleanup = work.finish().await;
    match (outcome, cleanup) {
        (Ok(value), Ok(())) if Instant::now() < deadline => Ok(value),
        (Ok(_), Ok(())) => Err("handler deadline expired during cleanup".into()),
        (Err(cause), Ok(())) | (Ok(_), Err(cause)) => Err(cause),
        (Err(cause), Err(cleanup)) => Err(format!("{cause}; cleanup: {cleanup}").into()),
    }
}

async fn process(
    work: &Work,
    lease: &mut Option<Lease>,
    database: &deadpool_sqlite::Pool,
    claim: Claim,
) -> Result<()> {
    let claim = Arc::new(claim);
    let deadline = Instant::now() + Duration::from_secs(1);
    let outcome = wait(work, deadline, async {
        #[cfg(not(feature = "contract"))]
        let input = serde_json::from_str(&claim.payload)?;
        #[cfg(feature = "contract")]
        let input = queue::decode(&claim)?;
        handle(work, lease, input).await
    })
    .await;
    match outcome {
        Ok(()) => {
            let value = claim.clone();
            work.call(lease, IO_TIMEOUT, move |connection| {
                queue::transition(connection, &value, "completed", None)
            })
            .await?;
            work.call(lease, IO_TIMEOUT, |connection| {
                connection.execute_batch("COMMIT")?;
                Ok(())
            })
            .await?;
        }
        Err(error) => {
            eprintln!("Job handler: {error}");
            #[cfg(feature = "contract")]
            let rejected = error.is::<queue::Rejected>();
            #[cfg(not(feature = "contract"))]
            let rejected = false;
            if lease.is_none() {
                // wait 已等待取消的阻塞操作释放连接；此处重新借用，不能复用未提交租约。
                *lease = Some(Lease {
                    object: Some(database.get().await?),
                    reusable: true,
                });
            } else {
                work.call(lease, IO_TIMEOUT, |connection| {
                    if !connection.is_autocommit() {
                        connection.execute_batch("ROLLBACK")?;
                    }
                    Ok(())
                })
                .await?;
            }
            work.call(lease, IO_TIMEOUT, move |connection| {
                let tx = connection.transaction_with_behavior(TransactionBehavior::Immediate)?;
                queue::transition(
                    &tx,
                    &claim,
                    if rejected {
                        "blocked"
                    } else if claim.attempt >= 2 {
                        "dead"
                    } else {
                        "pending"
                    },
                    Some("handler failed"),
                )?;
                tx.commit()?;
                Ok(())
            })
            .await?;
        }
    }
    Ok(())
}

async fn worker(
    work: &Work,
    lease: &mut Option<Lease>,
    database: &deadpool_sqlite::Pool,
) -> Result<()> {
    let mut stop = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?;
    loop {
        let stopping = tokio::select! { biased;
            _ = stop.recv() => true,
            _ = std::future::ready(()) => false,
        };
        if stopping {
            break;
        }
        match work.call(lease, IO_TIMEOUT, queue::claim).await? {
            Some(claim) => process(work, lease, database, claim).await?,
            None => tokio::select! {
                _ = stop.recv() => break,
                _ = tokio::time::sleep(Duration::from_millis(1)) => {},
            },
        }
    }
    Ok(())
}

async fn run(args: &[String]) -> Result<()> {
    let database = pool(&args[1], 2).await?;
    let work = Work::new();
    let mut lease = Some(Lease {
        object: Some(database.get().await?),
        reusable: true,
    });
    let result = async {
        if args[2] == "worker" {
            worker(&work, &mut lease, &database).await?;
        } else {
            let inputs = match args[2].as_str() {
                "submitAll" => serde_json::from_str::<Batch>(&args[3])?
                    .inputs
                    .into_iter()
                    .map(|input| Submit {
                        key: input.name.clone(),
                        input,
                    })
                    .collect(),
                "submit" => vec![serde_json::from_str::<Submit>(&args[3])?],
                _ => return Err("unknown command".into()),
            };
            let ids = submit(&work, &mut lease, inputs).await?;
            let out = if args[2] == "submit" {
                serde_json::to_value(&ids[0])?
            } else {
                serde_json::to_value(ids)?
            };
            println!("{out}");
        }
        Ok(())
    }
    .await;
    // 未提交的连接直接丢弃，SQLite 回滚；等待后台析构，保留清理中的原始错误。
    drop(lease);
    let cleanup = work.finish().await;
    drop(database);
    if let Err(cause) = cleanup {
        if result.is_ok() {
            return Err(cause);
        }
        eprintln!("cleanup: {cause}");
    }
    result
}

fn main() -> Result<()> {
    let args = std::env::args().collect::<Vec<_>>();
    tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()?
        .block_on(run(&args))
}

#[cfg(test)]
mod tests {
    use super::*;
    use deadpool_sqlite::rusqlite::Connection;

    struct File(std::path::PathBuf);
    impl File {
        fn new() -> Self {
            let mut id = [0; 16];
            getrandom::getrandom(&mut id).unwrap();
            let directory =
                std::env::temp_dir().join(format!("job-boundary-{:032x}", u128::from_ne_bytes(id)));
            std::fs::create_dir(&directory).unwrap();
            Connection::open(directory.join("queue.db"))
                .unwrap()
                .execute_batch("CREATE TABLE effects(value INTEGER)")
                .unwrap();
            Self(directory)
        }
    }
    impl Drop for File {
        fn drop(&mut self) {
            std::fs::remove_dir_all(&self.0).unwrap();
        }
    }

    async fn scenario(
        handler_pending: bool,
        expired: bool,
        late_panic: bool,
        handler_panic: bool,
    ) -> Result<()> {
        let file = File::new();
        let path = file.0.join("queue.db");
        let database = pool(path.to_str().unwrap(), 2).await?;
        let work = Work::new();
        let mut lease = Some(Lease {
            object: Some(database.get().await?),
            reusable: true,
        });
        let (release, released) = std::sync::mpsc::channel();
        let (entered, ready) = tokio::sync::oneshot::channel();
        let deadline = Instant::now()
            + if expired {
                Duration::from_millis(50)
            } else {
                IO_TIMEOUT
            };
        let handler = async {
            let (started, blocking) = tokio::sync::oneshot::channel();
            {
                let operation = work.call(&mut lease, IO_TIMEOUT, move |connection| {
                    connection.execute_batch("BEGIN IMMEDIATE; INSERT INTO effects VALUES(1)")?;
                    started.send(()).unwrap();
                    released.recv()?;
                    assert!(!late_panic, "late SQLite panic");
                    Ok(())
                });
                tokio::pin!(operation);
                tokio::select! {
                    result = &mut operation => panic!("operation finished before release: {result:?}"),
                    result = blocking => result.unwrap(),
                }
            }
            // 丢弃 SQL future 后真实阻塞工作仍在运行，持有未提交的连接。
            entered.send(()).unwrap();
            assert!(!handler_panic, "handler panic");
            if handler_pending {
                std::future::pending::<()>().await;
            }
            Ok(())
        };
        {
            let result = wait(&work, deadline, handler);
            tokio::pin!(result);
            tokio::select! {
                result = &mut result => panic!("boundary returned before descendant exit: {result:?}"),
                result = ready => result.unwrap(),
            }
            if expired {
                tokio::time::sleep_until(deadline).await;
            }
            assert!(futures_util::poll!(&mut result).is_pending());
            release.send(()).unwrap();
            let result = result.await;
            if expired || late_panic || handler_panic {
                let message = result.unwrap_err().to_string();
                if late_panic {
                    assert!(message.contains("late SQLite panic"), "{message}");
                }
                if handler_panic {
                    assert!(message.contains("handler panic"), "{message}");
                }
                if expired && handler_pending {
                    assert!(message.contains("deadline"), "{message}");
                }
            } else {
                result?;
            }
        }
        assert!(lease.is_none());
        assert_eq!(
            Connection::open(&path)?.query_row("SELECT count(*) FROM effects", [], |row| row
                .get::<_, i64>(0))?,
            0
        );
        // tracker 在首个边界后仍可跟踪下一项工作；事务回滚完成后才允许重试。
        let mut lease = Some(Lease {
            object: Some(database.get().await?),
            reusable: true,
        });
        wait(
            &work,
            Instant::now() + IO_TIMEOUT,
            work.call(&mut lease, IO_TIMEOUT, |connection| {
                connection.execute("INSERT INTO effects VALUES(2)", [])?;
                Ok(())
            }),
        )
        .await?;
        assert_eq!(
            Connection::open(&path)?
                .query_row("SELECT sum(value) FROM effects", [], |row| row
                    .get::<_, i64>(0))?,
            2
        );
        drop(lease);
        work.finish().await?;
        drop(database);
        Ok(())
    }

    #[tokio::test]
    async fn waits_for_cancelled_sql_and_rolls_back_before_next_job() -> Result<()> {
        scenario(false, false, false, false).await
    }

    #[tokio::test]
    async fn rejects_success_when_descendant_cleanup_exceeds_deadline() -> Result<()> {
        scenario(false, true, false, false).await
    }

    #[tokio::test]
    async fn timeout_drains_and_preserves_late_panic() -> Result<()> {
        scenario(true, true, true, false).await
    }

    #[tokio::test]
    async fn handler_panic_still_drains_and_preserves_late_panic() -> Result<()> {
        scenario(false, false, true, true).await
    }
}
