use serde::{Deserializer, Serialize, Serializer};
use spin::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use std::cell::UnsafeCell;
use std::fmt::{Debug, Formatter};
use std::ops::{Deref, DerefMut, Index, IndexMut};
use std::slice::{Iter as SliceIter};
use std::sync::Arc;
use std::vec::IntoIter;

/// Synchronous vector supporting fine-grained lock control
/// 同步向量类型，支持细粒度锁控制，更安全地访问数据
/// 
/// Locking strategy:
/// - Read operations like `get`: Vec read lock + value read lock
/// - Value modification operations like `get_mut`: Vec read lock + value write lock
/// - Structure modification operations like `push`/`remove`: Vec write lock
/// 锁策略:
/// - get 等读取操作: Vec读锁 + 值的读锁
/// - get_mut 等修改值操作: Vec读锁 + 值的写锁
/// - push/remove 等修改结构操作: Vec写锁
/// 
/// This allows:
/// - Multiple threads can read different values simultaneously
/// - When one thread modifies a value, other threads can still read other values
/// - Exclusive access when modifying the Vec structure
/// 这样可以实现:
/// - 多个线程可以同时读取不同的值
/// - 一个线程修改某个值时，其他线程仍可读取其他值
/// - 修改Vec结构时独占访问
pub struct SyncVec<V> {
    dirty: UnsafeCell<Vec<RwLock<V>>>,
    lock: RwLock<()>,
}

/// This is safe, dirty mutex ensures safety
/// 这是安全的，dirty 互斥锁保证了安全性
unsafe impl<V> Send for SyncVec<V> {}

/// This is safe, dirty mutex ensures safety
/// 这是安全的，dirty 互斥锁保证了安全性
unsafe impl<V> Sync for SyncVec<V> {}

impl<V> Default for SyncVec<V> {
    fn default() -> Self {
        Self::new()
    }
}

impl<V> From<Vec<V>> for SyncVec<V> {
    fn from(v: Vec<V>) -> Self {
        Self::with_vec(v)
    }
}

impl<V> SyncVec<V> {
    pub fn new_arc() -> Arc<Self> {
        Arc::new(Self::new())
    }

    pub const fn new() -> Self {
        Self {
            dirty: UnsafeCell::new(Vec::new()),
            lock: RwLock::new(()),
        }
    }

    pub fn with_vec(vec: Vec<V>) -> Self {
        let mut v = Vec::with_capacity(vec.len());
        for item in vec {
            v.push(RwLock::new(item));
        }
        Self {
            dirty: UnsafeCell::new(v),
            lock: RwLock::new(()),
        }
    }

    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            dirty: UnsafeCell::new(Vec::with_capacity(capacity)),
            lock: RwLock::new(()),
        }
    }

    #[inline(always)]
    fn as_arr(&self) -> &Vec<RwLock<V>> {
        unsafe { &*self.dirty.get() }
    }

    #[inline(always)]
    fn as_arr_mut(&self) -> &mut Vec<RwLock<V>> {
        unsafe { &mut *self.dirty.get() }
    }

    #[inline(always)]
    pub fn insert(&self, index: usize, v: V) {
        let _lock = self.lock.write();
        self.as_arr_mut().insert(index, RwLock::new(v));
    }

    #[inline(always)]
    pub fn push(&self, v: V) {
        let _lock = self.lock.write();
        self.as_arr_mut().push(RwLock::new(v));
    }

    #[inline(always)]
    pub fn push_return(&self, v: V) -> usize {
        let _lock = self.lock.write();
        let u = self.as_arr_mut();
        let index = u.len();
        u.push(RwLock::new(v));
        index
    }

    #[inline(always)]
    pub fn push_vec(&self, input_arr: Vec<V>) {
        let mut _lock = self.lock.write();
        let u = self.as_arr_mut();
        for ele in input_arr.into_iter() {
            u.push(RwLock::new(ele));
        }
    }

    pub fn pop(&self) -> Option<V> {
        let _lock = self.lock.write();
        let u = self.as_arr_mut();
        u.pop().map(|v| v.into_inner())
    }

    pub fn remove(&self, index: usize) -> Option<V> {
        let _lock = self.lock.write();
        let u = self.as_arr_mut();
        if u.len() > index {
            let v = u.remove(index);
            Some(v.into_inner())
        } else {
            None
        }
    }

    pub fn len(&self) -> usize {
        let _lock = self.lock.read();
        let u = self.as_arr();
        u.len()
    }

    pub fn is_empty(&self) -> bool {
        let _lock = self.lock.read();
        let u = self.as_arr();
        u.is_empty()
    }

    pub fn clear(&self) {
        let _lock = self.lock.write();
        let u = self.as_arr_mut();
        u.clear();
    }

    pub fn shrink_to_fit(&self) {
        let _lock = self.lock.write();
        let u = self.as_arr_mut();
        u.shrink_to_fit();
    }

    /// Get a reference to the value at index, protected by Vec read lock + value read lock
    /// 获取索引处的值引用，使用Vec读锁 + 值的读锁保护
    #[inline]
    pub fn get(&self, index: usize) -> Option<ReadGuard<'_, V>> {
        let _lock = self.lock.read();
        let u = self.as_arr();
        if let Some(v_lock) = u.get(index) {
            let _value_lock = v_lock.read();
            Some(ReadGuard {
                _vec_lock: _lock,
                _value_lock,
            })
        } else {
            None
        }
    }

    /// Get a reference to the value at index (unchecked), protected by Vec read lock + value read lock
    /// 获取索引处的值引用（无检查），使用Vec读锁 + 值的读锁保护
    #[inline]
    pub fn get_uncheck(&self, index: usize) -> ReadGuard<'_, V> {
        let _lock = self.lock.read();
        let u = self.as_arr();
        let v_lock = &u[index];
        let _value_lock = v_lock.read();
        ReadGuard {
            _vec_lock: _lock,
            _value_lock,
        }
    }

    /// Get a mutable reference to the value at index, protected by Vec read lock + value write lock
    /// 获取索引处的可变值引用，使用Vec读锁 + 值的写锁保护
    #[inline]
    pub fn get_mut(&self, index: usize) -> Option<WriteGuard<'_, V>> {
        let _lock = self.lock.read();
        let u = self.as_arr();
        if let Some(v_lock) = u.get(index) {
            let _value_lock = v_lock.write();
            Some(WriteGuard {
                _vec_lock: _lock,
                _value_lock,
            })
        } else {
            None
        }
    }

    #[inline]
    pub fn contains(&self, x: &V) -> bool
    where
        V: PartialEq,
    {
        let _lock = self.lock.read();
        let u = self.as_arr();
        for item in u {
            if *item.read() == *x {
                return true;
            }
        }
        false
    }

    pub fn iter(&self) -> Iter<'_, V> {
        let _lock = self.lock.read();
        let u = self.as_arr();
        Iter {
            _lock,
            inner: u.iter(),
        }
    }

    pub fn iter_mut(&self) -> IterMut<'_, V> {
        let _lock = self.lock.read();
        let u = self.as_arr();
        IterMut {
            _lock,
            inner: u.iter(),
        }
    }

    pub fn into_iter(self) -> IntoIter<V> {
        let _lock = self.lock.write();
        let m = self.dirty.into_inner();
        let mut v = Vec::with_capacity(m.len());
        for item in m {
            v.push(item.into_inner());
        }
        v.into_iter()
    }

    pub fn dirty_ref(&self) -> ReadGuardVec<'_, V> {
        ReadGuardVec {
            _lock: self.lock.read(),
            v: self.as_arr(),
        }
    }

    pub fn into_inner(self) -> Vec<V> {
        let m = self.dirty.into_inner();
        let mut v = Vec::with_capacity(m.len());
        for item in m {
            v.push(item.into_inner());
        }
        v
    }
    
    pub fn to_vec(&self) -> Vec<V> 
    where V: Clone
    {
        let _lock = self.lock.read();
        let u = self.as_arr();
        let mut v = Vec::with_capacity(u.len());
        for item in u {
            v.push(item.read().clone());
        }
        v
    }
}

pub struct ReadGuard<'a, V> {
    _vec_lock: RwLockReadGuard<'a, ()>,
    _value_lock: RwLockReadGuard<'a, V>,
}

impl<'a, V> Deref for ReadGuard<'a, V> {
    type Target = V;
    fn deref(&self) -> &Self::Target {
        &*self._value_lock
    }
}

impl<'a, V> Debug for ReadGuard<'_, V>
where
    V: Debug,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", &*self._value_lock)
    }
}

impl<'a, V> PartialEq for ReadGuard<'a, V>
where
    V: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        (*self._value_lock).eq(&*other._value_lock)
    }
}

impl<'a, V> Eq for ReadGuard<'a, V> where V: Eq {}

impl<'a, V> std::fmt::Display for ReadGuard<'_, V>
where
    V: std::fmt::Display,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        (*self._value_lock).fmt(f)
    }
}

impl<'a, V> AsRef<V> for ReadGuard<'a, V> {
    fn as_ref(&self) -> &V {
        &*self._value_lock
    }
}

pub struct ReadGuardVec<'a, V> {
    _lock: RwLockReadGuard<'a, ()>,
    v: &'a Vec<RwLock<V>>,
}

impl<'a, V> Deref for ReadGuardVec<'a, V> {
    type Target = Vec<RwLock<V>>;
    fn deref(&self) -> &Self::Target {
        self.v
    }
}

impl<'a, V> AsRef<Vec<RwLock<V>>> for ReadGuardVec<'a, V> {
    fn as_ref(&self) -> &Vec<RwLock<V>> {
        self.v
    }
}

impl<'a, V> Debug for ReadGuardVec<'_, V>
where
    V: Debug,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_list().entries(self.v.iter().map(|x| x.read())).finish()
    }
}

pub struct WriteGuard<'a, V> {
    _vec_lock: RwLockReadGuard<'a, ()>,
    _value_lock: RwLockWriteGuard<'a, V>,
}

impl<'a, V> AsRef<V> for WriteGuard<'a, V> {
    fn as_ref(&self) -> &V {
        &*self._value_lock
    }
}

impl<'a, V> AsMut<V> for WriteGuard<'a, V> {
    fn as_mut(&mut self) -> &mut V {
        &mut *self._value_lock
    }
}

impl<'a, V> Deref for WriteGuard<'_, V> {
    type Target = V;

    fn deref(&self) -> &Self::Target {
        &*self._value_lock
    }
}

impl<'a, V> DerefMut for WriteGuard<'_, V> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut *self._value_lock
    }
}

impl<'a, V> Debug for WriteGuard<'_, V>
where
    V: Debug,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", &*self._value_lock)
    }
}

impl<'a, V> std::fmt::Display for WriteGuard<'_, V> 
where V: std::fmt::Display
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        (*self._value_lock).fmt(f)
    }
}

pub struct Iter<'a, V> {
    _lock: RwLockReadGuard<'a, ()>,
    inner: SliceIter<'a, RwLock<V>>,
}

impl<'a, V> Iterator for Iter<'a, V> {
    type Item = RwLockReadGuard<'a, V>;
    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().map(|v| v.read())
    }
}

pub struct IterMut<'a, V> {
    _lock: RwLockReadGuard<'a, ()>,
    inner: SliceIter<'a, RwLock<V>>,
}

impl<'a, V> Iterator for IterMut<'a, V> {
    type Item = RwLockWriteGuard<'a, V>;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().map(|v| v.write())
    }
}

impl<'a, V> IntoIterator for &'a SyncVec<V> {
    type Item = RwLockReadGuard<'a, V>;
    type IntoIter = Iter<'a, V>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<V> IntoIterator for SyncVec<V> {
    type Item = V;
    type IntoIter = IntoIter<V>;

    fn into_iter(self) -> Self::IntoIter {
        self.into_iter()
    }
}

impl<V> Serialize for SyncVec<V>
where
    V: Serialize,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        use serde::ser::SerializeSeq;
        let _lock = self.lock.read();
        let v = unsafe { &*self.dirty.get() };
        let mut seq = serializer.serialize_seq(Some(v.len()))?;
        for element in v {
            seq.serialize_element(&*element.read())?;
        }
        seq.end()
    }
}

impl<'de, V> serde::Deserialize<'de> for SyncVec<V>
where
    V: serde::Deserialize<'de>,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let m = Vec::deserialize(deserializer)?;
        Ok(Self::from(m))
    }
}

impl<V> Debug for SyncVec<V>
where
    V: Debug,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", self.dirty_ref())
    }
}

impl<V: std::fmt::Display> std::fmt::Display for SyncVec<V> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let _lock = self.lock.read();
        let v = unsafe { &*self.dirty.get() };
        write!(f, "[")?;
        for (i, item) in v.iter().enumerate() {
            if i > 0 {
                write!(f, ", ")?;
            }
            write!(f, "{}", item.read())?;
        }
        write!(f, "]")
    }
}

impl<V: PartialEq> PartialEq for SyncVec<V> {
    fn eq(&self, other: &Self) -> bool {
        let _lock1 = self.lock.read();
        let _lock2 = other.lock.read();
        let v1 = unsafe { &*self.dirty.get() };
        let v2 = unsafe { &*other.dirty.get() };
        if v1.len() != v2.len() {
            return false;
        }
        for (i1, i2) in v1.iter().zip(v2.iter()) {
            if *i1.read() != *i2.read() {
                return false;
            }
        }
        true
    }
}

impl<V: Clone> Clone for SyncVec<V> {
    fn clone(&self) -> Self {
        let _lock = self.lock.read();
        let v = unsafe { &*self.dirty.get() };
        let mut new_vec = Vec::with_capacity(v.len());
        for item in v {
            new_vec.push(RwLock::new(item.read().clone()));
        }
        Self {
            dirty: UnsafeCell::new(new_vec),
            lock: RwLock::new(()),
        }
    }
}

impl<V> Index<usize> for SyncVec<V> {
    type Output = V;

    /// Get a reference to the value at index, bypassing the lock.
    /// 获取索引处的值引用，绕过锁。
    /// 
    /// # Safety
    /// This method is unsafe because it bypasses the `RwLock` protecting the value.
    /// It should only be used when you are sure that no other thread is modifying the value.
    /// Concurrent access using this method is undefined behavior.
    /// 
    /// # 安全性
    /// 此方法是不安全的，因为它绕过了保护值的 `RwLock`。
    /// 仅当您确定没有其他线程正在修改该值时才应使用它。
    /// 使用此方法进行并发访问是未定义行为。
    fn index(&self, index: usize) -> &Self::Output {
        unsafe {
            let v = &*self.dirty.get();
            // We need to get &V from &RwLock<V> without locking.
            // Since we are in an unsafe block and claiming it's unsafe/no concurrent access,
            // we can cast the &RwLock<V> to &mut RwLock<V> (conceptually) to use get_mut(),
            // or rely on the fact that we are bypassing the lock.
            // However, RwLock::get_mut requires &mut RwLock.
            // We only have &RwLock.
            // We can cast &RwLock to &mut RwLock because we are asserting exclusive access (via the safety contract).
            let lock_ptr = &v[index] as *const RwLock<V> as *mut RwLock<V>;
            (*lock_ptr).get_mut()
        }
    }
}

impl<V> IndexMut<usize> for SyncVec<V> {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        // This is unsafe because we are bypassing the `RwLock` protecting the value.
        // 这是不安全的，因为我们绕过了保护值的 `RwLock`。
        let v = self.dirty.get_mut();
        v[index].get_mut()
    }
}

#[macro_export]
macro_rules! sync_vec {
    () => (
        $crate::SyncVec::new()
    );
    ($elem:expr; $n:expr) => (
        $crate::SyncVec::with_vec(vec![$elem;$n])
    );
    ($($x:expr),+ $(,)?) => (
        $crate::SyncVec::with_vec(vec![$($x),+,])
    );
}

#[test]
fn test_case() {
    struct D {}
    impl D {
        fn is_some(&self) -> bool {
            println!("is_some");
            true
        }
        fn take(&mut self) -> Option<bool> {
            println!("take");
            Some(true)
        }
    }

    let mut d = D {};
    if let (true, Some(d)) = (d.is_some(), d.take()) {
        println!("d is {d}");
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Arc;
    use std::thread;

    #[test]
    fn test_new_and_capacity() {
        let vec: SyncVec<i32> = SyncVec::new();
        assert!(vec.is_empty());
        assert_eq!(vec.len(), 0);

        let vec: SyncVec<i32> = SyncVec::with_capacity(10);
        assert!(vec.is_empty());
        assert_eq!(vec.len(), 0);
    }

    #[test]
    fn test_push_and_get() {
        let vec = SyncVec::new();
        vec.push(1);
        vec.push(2);
        vec.push(3);

        assert_eq!(vec.len(), 3);
        assert_eq!(*vec.get(0).unwrap(), 1);
        assert_eq!(*vec.get(1).unwrap(), 2);
        assert_eq!(*vec.get(2).unwrap(), 3);
        assert!(vec.get(3).is_none());
    }

    #[test]
    fn test_index_methods() {
        let mut vec = SyncVec::new();
        vec.push(10);
        vec.push(20);

        assert_eq!(vec[0], 10);
        assert_eq!(vec[1], 20);

        {
            let val = &mut vec[0];
            *val = 100;
        }
        assert_eq!(vec[0], 100);
    }

    #[test]
    #[should_panic(expected = "index out of bounds")]
    fn test_index_panic() {
        let vec = SyncVec::new();
        vec.push(1);
        let _ = vec[1];
    }

    #[test]
    #[should_panic(expected = "index out of bounds")]
    fn test_index_mut_panic() {
        let mut vec = SyncVec::new();
        vec.push(1);
        let _ = &mut vec[1];
    }

    #[test]
    fn test_remove_and_pop() {
        let vec = SyncVec::new();
        vec.push(1);
        vec.push(2);
        vec.push(3);

        assert_eq!(vec.pop(), Some(3));
        assert_eq!(vec.len(), 2);

        assert_eq!(vec.remove(0), Some(1));
        assert_eq!(vec.len(), 1);
        assert_eq!(*vec.get(0).unwrap(), 2);
    }

    #[test]
    fn test_concurrency() {
        let vec = Arc::new(SyncVec::new());
        let mut handles = vec![];

        // Multiple writers
        for i in 0..10 {
            let vec = vec.clone();
            handles.push(thread::spawn(move || {
                for j in 0..100 {
                    vec.push(i * 100 + j);
                }
            }));
        }

        for handle in handles {
            handle.join().unwrap();
        }

        assert_eq!(vec.len(), 1000);
    }

    #[test]
    fn test_concurrent_modify() {
        let vec = Arc::new(SyncVec::new());
        for i in 0..100 {
            vec.push(i);
        }

        let vec_clone = vec.clone();
        let handle = thread::spawn(move || {
            for i in 0..100 {
                if let Some(mut guard) = vec_clone.get_mut(i) {
                    *guard += 1;
                }
            }
        });

        // Concurrent read
        for i in 0..100 {
            if let Some(val) = vec.get(i) {
                let _ = *val; // Just read
            }
        }

        handle.join().unwrap();

        // Verify modifications
        for i in 0..100 {
            assert_eq!(*vec.get(i).unwrap(), i + 1);
        }
    }

    #[test]
    fn test_iter() {
        let vec = SyncVec::new();
        vec.push(1);
        vec.push(2);
        vec.push(3);

        let mut sum = 0;
        for item in vec.iter() {
            sum += *item;
        }
        assert_eq!(sum, 6);
    }

    #[test]
    fn test_iter_mut() {
        let vec = SyncVec::new();
        vec.push(1);
        vec.push(2);
        vec.push(3);

        for mut item in vec.iter_mut() {
            *item *= 2;
        }

        assert_eq!(*vec.get(0).unwrap(), 2);
        assert_eq!(*vec.get(1).unwrap(), 4);
        assert_eq!(*vec.get(2).unwrap(), 6);
    }

    #[test]
    fn test_clear() {
        let vec = SyncVec::new();
        vec.push(1);
        vec.clear();
        assert!(vec.is_empty());
    }

    #[test]
    fn test_contains() {
        let vec = SyncVec::new();
        vec.push(1);
        vec.push(2);
        assert!(vec.contains(&1));
        assert!(!vec.contains(&3));
    }
}