/*
    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 crate::{Object, Tag, TypedTag, ValueType};
use std::{any::type_name, fmt::Debug};

impl Debug for Object {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut s = f.debug_struct("Object");
        let mut nonexhaustive = false;
        for (i, tag) in self.keys().enumerate() {
            let kbytes = tag.0.to_le_bytes();
            let k = str::from_utf8(&kbytes).unwrap();
            let ty = self.offset_type(i);
            let sz = self.size(i);
            match (ty, sz) {
                (ValueType::String, _) => s.field(k, &self.get_typed::<str>(i).unwrap()),
                (ValueType::Binary, _) => s.field(k, &self.get_typed::<[u8]>(i).unwrap()),
                (ValueType::Object, _) => s.field(k, &self.get_typed::<Object>(i).unwrap()),
                (ValueType::UInt, 4) => s.field(k, &self.get_typed::<u32>(i).unwrap()),
                (ValueType::UInt, 8) => s.field(k, &self.get_typed::<u64>(i).unwrap()),
                (ValueType::Int, 8) => s.field(k, &self.get_typed::<i64>(i).unwrap()),
                _ => {
                    nonexhaustive = true;
                    &mut s
                }
            };
        }
        if nonexhaustive {
            s.finish_non_exhaustive()
        } else {
            s.finish()
        }
    }
}

impl<T> Debug for TypedTag<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple(&format!("TypedTag<{}>", type_name::<T>()))
            .field(&self.0)
            .finish()
    }
}
impl Debug for Tag {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let bytes = self.0.to_le_bytes();
        let name = str::from_utf8(&bytes).unwrap();
        f.debug_tuple("Tag").field(&name).finish()
    }
}
