/*
    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, ValueType};
use serde_json::{Map, Value};

pub fn object_to_json(ob: &Object) -> Value {
    let mut o = Map::new();
    let mut nonexhaustive = false;
    for (i, tag) in ob.keys().enumerate() {
        let kbytes = tag.0.to_le_bytes();
        let k = str::from_utf8(&kbytes).unwrap().to_string();
        let ty = ob.offset_type(i);
        let sz = ob.size(i);
        let val = match (ty, sz) {
            (ValueType::String, _) => ob.get_typed::<str>(i).unwrap().to_string().into(),
            (ValueType::Object, _) => object_to_json(ob.get_typed::<Object>(i).unwrap()),
            (ValueType::Tag, 4) => ob.get_typed::<Tag>(i).unwrap().to_string().into(),
            (ValueType::UInt, 4) => ob.get_typed::<u32>(i).unwrap().into(),
            (ValueType::UInt, 8) => ob.get_typed::<u64>(i).unwrap().into(),
            (ValueType::Int, 8) => ob.get_typed::<i64>(i).unwrap().into(),
            (ValueType::Float, 8) => ob.get_typed::<f64>(i).unwrap().into(),
            _ => {
                nonexhaustive = true;
                continue;
            }
        };
        multi_insert(&mut o, k, val);
    }
    if nonexhaustive {
        o.insert("_nonexhaustive".to_owned(), Value::Bool(true));
    }

    Value::Object(o)
}

fn multi_insert(m: &mut Map<String, Value>, key: String, val: Value) {
    if let Some(cur) = m.get_mut(&key) {
        if let Some(cur) = cur.as_array_mut() {
            cur.push(val);
        } else {
            *cur = Value::Array(vec![cur.clone(), val])
        }
    } else {
        m.insert(key, val);
    }
}
