//! F15 — Interop monomers: MC_120–MC_127
//!
//! JSON encode/decode are real implementations; rest are stubs.

/// MC_120 — JSON_ENCODE: encode key-value pairs as a JSON object string.
///
/// ```
/// use brik64_core::mc::json_encode;
/// let s = json_encode(&[("name", "brik"), ("version", "4")]);
/// assert!(s.contains("\"name\":\"brik\""));
/// ```
pub fn json_encode(pairs: &[(&str, &str)]) -> String {
    let mut s = String::from("{");
    for (i, (k, v)) in pairs.iter().enumerate() {
        if i > 0 { s.push(','); }
        s.push('"');
        s.push_str(&escape_json(k));
        s.push_str("\":\"");
        s.push_str(&escape_json(v));
        s.push('"');
    }
    s.push('}');
    s
}

/// MC_121 — JSON_DECODE: extract value for a key from a JSON object string.
///
/// Simple parser — handles flat `{"key":"value"}` objects only.
///
/// ```
/// use brik64_core::mc::json_decode;
/// assert_eq!(json_decode("{\"a\":\"1\"}", "a"), Some("1".to_string()));
/// assert_eq!(json_decode("{\"a\":\"1\"}", "b"), None);
/// ```
pub fn json_decode(json: &str, key: &str) -> Option<String> {
    let needle = format!("\"{}\":\"", key);
    let start = json.find(&needle)? + needle.len();
    let rest = &json[start..];
    let end = rest.find('"')?;
    Some(rest[..end].to_string())
}

fn escape_json(s: &str) -> String {
    s.replace('\\', "\\\\")
     .replace('"', "\\\"")
     .replace('\n', "\\n")
     .replace('\r', "\\r")
     .replace('\t', "\\t")
}

/// MC_122 — XML_ENCODE: stub.
pub fn xml_encode(_tag: &str, _content: &str) -> String { String::new() }
/// MC_123 — XML_DECODE: stub.
pub fn xml_decode(_xml: &str, _tag: &str) -> Option<String> { None }
/// MC_124 — MSGPACK_ENCODE: stub.
pub fn msgpack_encode(_data: &[u8]) -> Vec<u8> { Vec::new() }
/// MC_125 — MSGPACK_DECODE: stub.
pub fn msgpack_decode(_data: &[u8]) -> Vec<u8> { Vec::new() }
/// MC_126 — FFI_CALL: stub.
pub fn ffi_call(_sym: &str, _args: &[i64]) -> i64 { 0 }
/// MC_127 — FFI_LOAD: stub.
pub fn ffi_load(_lib: &str) -> i64 { 0 }

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

    #[test]
    fn json_roundtrip() {
        let encoded = json_encode(&[("name", "brik64"), ("ver", "4")]);
        assert_eq!(json_decode(&encoded, "name"), Some("brik64".to_string()));
        assert_eq!(json_decode(&encoded, "ver"), Some("4".to_string()));
        assert_eq!(json_decode(&encoded, "missing"), None);
    }

    #[test]
    fn json_escape() {
        let encoded = json_encode(&[("msg", "hello \"world\"")]);
        assert!(encoded.contains("\\\"world\\\""));
    }
}
