Documentation
use std::{
    cell::UnsafeCell,
    future::Future,
    pin::Pin,
    sync::{Arc, Mutex},
    task::{Context, Poll, Waker},
};

/// The inner shared state.
struct Inner<T> {
    locked: bool,
    waiters: Vec<Waker>, // FIFO queue of waiters
    // The protected data is stored outside the std::sync::Mutex to allow
    // handing out a &mut T to the guard without holding the sync mutex.
    data: UnsafeCell<T>,
}

// Safety:
// - We require T: Send. AsyncMutex<T> is Send+Sync if T: Send.
// - UnsafeCell<T> is !Sync, but we ensure exclusivity via `locked` flag.
unsafe impl<T: Send> Send for Inner<T> {}
unsafe impl<T: Send> Sync for Inner<T> {}

#[derive(Clone)]
pub struct AsyncMutex<T> {
    inner: Arc<Mutex<Inner<T>>>,
}

pub struct AsyncMutexGuard<T> {
    inner: Arc<Mutex<Inner<T>>>,
    // raw pointer to the data inside UnsafeCell<T>
    data_ptr: *mut T,
}

impl<T> AsyncMutex<T> {
    /// create a new AsyncMutex
    pub fn new(t: T) -> Self {
        Self {
            inner: Arc::new(Mutex::new(Inner {
                locked: false,
                waiters: Vec::new(),
                data: UnsafeCell::new(t),
            })),
        }
    }

    /// Returns a Future that resolves to AsyncMutexGuard<T>
    pub fn lock(&self) -> LockFuture<T> {
        LockFuture {
            inner: Some(self.inner.clone()),
        }
    }

    /// try to acquire immediately (non-blocking)
    pub fn try_lock(&self) -> Option<AsyncMutexGuard<T>> {
        let mut guard = self.inner.lock().unwrap();
        if guard.locked {
            None
        } else {
            guard.locked = true;
            let ptr = guard.data.get();
            Some(AsyncMutexGuard {
                inner: self.inner.clone(),
                data_ptr: ptr,
            })
        }
    }
}

pub struct LockFuture<T> {
    inner: Option<Arc<Mutex<Inner<T>>>>,
}

impl<T> Future for LockFuture<T> {
    type Output = AsyncMutexGuard<T>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        // take the arc (if it's still there)
        let inner = match &self.inner {
            Some(a) => a.clone(),
            None => panic!("polled after ready"),
        };

        let mut state = inner.lock().unwrap();

        if !state.locked {
            // acquire and return guard
            state.locked = true;
            let ptr = state.data.get();
            // drop mutex before returning (so guard drop can lock again)
            drop(state);
            // consume self.inner so future won't be polled again
            self.inner = None;
            Poll::Ready(AsyncMutexGuard {
                inner,
                data_ptr: ptr,
            })
        } else {
            // push our waker and return Pending
            // replace any previous waker for the same task is optional; we append for FIFO fairness
            state.waiters.push(cx.waker().clone());
            Poll::Pending
        }
    }
}

// Implement guard methods to access the data safely
impl<T> AsyncMutexGuard<T> {
    /// Borrow the protected value as mutable
    pub fn get_mut(&mut self) -> &mut T {
        unsafe { &mut *self.data_ptr }
    }

    /// Borrow immutably (convenience)
    pub fn get(&self) -> &T {
        unsafe { &*self.data_ptr }
    }
}

// Implement Send/Sync for the AsyncMutex and guard conditions
unsafe impl<T: Send> Send for AsyncMutex<T> {}
unsafe impl<T: Send> Sync for AsyncMutex<T> {}

unsafe impl<T: Send> Send for AsyncMutexGuard<T> {}
// not Sync: &mut access forbids Sync

// ---- Improved, correct FIFO unlocking (replacement Drop impl) ----

impl<T> Drop for AsyncMutexGuard<T> {
    fn drop(&mut self) {
        // release lock and wake one waiter (FIFO)
        use std::collections::VecDeque;

        // We need to temporarily extract waiters into a VecDeque to pop_front.
        // Since the Inner currently stores Vec, we reconstruct safely.
        let mut state = self.inner.lock().unwrap();
        state.locked = false;

        if state.waiters.is_empty() {
            return;
        }

        // move waiters into a VecDeque, pop front, and put the rest back.
        let mut dq: VecDeque<Waker> = state.waiters.drain(..).collect();
        if let Some(next) = dq.pop_front() {
            // put remaining back into Vec
            state.waiters = dq.into();
            // wake the next waiter
            next.wake();
        } else {
            // unlikely — restore empty vec
            state.waiters = Vec::new();
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use midsync::*;

    #[test]
    fn it_works() {
        let m = AsyncMutex::new(0usize);

        let mut pool = Pool::default();

        let m1 = m.clone();
        pool.add(async move {
            let mut g = m1.lock().await;
            let v = g.get_mut();
            *v += 1;
            println!("task1 set -> {}", *v);
            // guard dropped on scope exit
        });

        let m2 = m.clone();
        pool.add(async move {
            let mut g = m2.lock().await;
            let v = g.get_mut();
            *v += 10;
            println!("task2 set -> {}", *v);
        });

        while pool.poll() {}

        // final value
        pool.add(async {
            let g = m.lock().await;
            assert_eq!(g.get(), &11)
        });

        while pool.poll() {}
    }
}