/*
    This file is part of jellything (https://codeberg.org/metamuffin/jellything)
    which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
    Copyright (C) 2026 metamuffin <metamuffin.org>
*/

use core::marker::{PhantomData, Sized};
use std::fmt::Display;

#[repr(transparent)]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Tag(pub u32);

impl Default for Tag {
    fn default() -> Self {
        Self::new(b"1111")
    }
}
impl Tag {
    pub const fn new(fourcc: &[u8; 4]) -> Self {
        Self(u32::from_le_bytes(*fourcc))
    }
}
impl Display for Tag {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(str::from_utf8(&self.0.to_le_bytes()).unwrap())
    }
}

#[derive(PartialEq, Eq, PartialOrd, Ord)]
pub struct TypedTag<T: ?Sized>(pub Tag, pub PhantomData<T>);
impl<T: ?Sized> Display for TypedTag<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}
impl<T: ?Sized> Clone for TypedTag<T> {
    fn clone(&self) -> Self {
        Self(self.0, PhantomData)
    }
}
impl<T: ?Sized> Copy for TypedTag<T> {}
impl<T: ?Sized> TypedTag<T> {
    pub const fn new(tag: Tag) -> Self {
        Self(tag, PhantomData)
    }
}

pub mod types {
    use crate::Object;
    use std::any::TypeId;

    pub const OBJECT: TypeId = TypeId::of::<Object>();
    pub const STR: TypeId = TypeId::of::<&str>();
    pub const BINARY: TypeId = TypeId::of::<&[u8]>();
    pub const U32: TypeId = TypeId::of::<u32>();
    pub const U64: TypeId = TypeId::of::<u64>();
    pub const I64: TypeId = TypeId::of::<i64>();
    pub const F64: TypeId = TypeId::of::<f64>();
}

#[macro_export]
macro_rules! fields {
    ($($id:ident: $type:ty = $tag:literal;)*) => {
        $(pub const $id: $crate::TypedTag<$type> = $crate::TypedTag::new($crate::Tag::new($tag));)*
    };
}
#[macro_export]
macro_rules! enums {
    ($($id:ident = $tag:literal;)*) => {
        $(pub const $id: $crate::Tag = $crate::Tag::new($tag);)*
    };
}
