use std::{
    sync::atomic::{AtomicUsize, Ordering},
    time::Duration,
};
use tracing::Instrument;
fn main() {
    sd_proxy::init_tracing();
    let config = sd_proxy::load_config();

    tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .thread_keep_alive(Duration::from_secs(600)) // 10分钟
        // .event_interval(61)
        // .global_queue_interval(30)
        .thread_name_fn(|| {
            static ATOMIC_ID: AtomicUsize = AtomicUsize::new(0);
            let id = ATOMIC_ID.fetch_add(1, Ordering::SeqCst);
            format!("TokioRT-{}", id)
        })
        .build()
        .unwrap()
        .block_on(async {
            let addr = config.addr;

            let route = sd_proxy::init_router(config)
                .instrument(tracing::span!(tracing::Level::TRACE, "Init Router"))
                .await;

            let serve = route.into_make_service_with_connect_info::<std::net::SocketAddr>();
            tracing::info!("Server addr: {}", addr);
            axum::Server::bind(&addr)
                .serve(serve)
                .instrument(tracing::span!(tracing::Level::INFO, "Service"))
                .await
                .expect("server failed");
        });
}

#[cfg(test)]
mod tests {
    use sd_proxy::gmssl::sm2::*;

    #[test]
    fn test_name() {
        let private_key = "244889352ab13f8601a9871ef47dc2a694bd293f8ae156538aea036d07f47729";
        let public_key = "03a937d952388700a18e1d4c69fba338fa507440c4d710a72be80a87269cb1045f";
        let private_key = hex::decode(private_key).unwrap();
        let public_key = hex::decode(public_key).unwrap();
        println!(
            "private_key: {}, public_key:{}",
            private_key.len(),
            public_key.len()
        );

        unsafe {
            let mut arg = std::mem::zeroed::<SM2_KEY>();
            arg.private_key.clone_from_slice(&private_key);
            arg.public_key = TryFrom::<&[u8]>::try_from(&public_key).unwrap();
            let str = b"Hello";
            let mut out = [0_u8; 255];
            let mut outlen = 0;
            let r = sm2_encrypt(&arg, str.as_ptr(), str.len(), out.as_mut_ptr(), &mut outlen);

            println!("{r}: {:?}", &out[..outlen])
        }
    }


    #[test]
    fn test_file() {
        println!(file!())
    }
}
