import Foundation
import Testing

@testable import NucleicCore

@Suite struct JSONValueTests {
    @Test func roundTrip() throws {
        let value: JSONValue = [
            "string": "hello",
            "int": 42,
            "double": 3.5,
            "bool": true,
            "null": nil,
            "array": [1, "two", false],
            "nested": ["a": ["b": "c"]],
        ]
        let data = try value.encodedData()
        let decoded = try JSONValue(parsing: data)
        #expect(decoded == value)
    }

    @Test func accessors() throws {
        let value = try JSONValue(parsing: #"{"command":"ls","count":3,"flag":true,"items":[1,2]}"#)
        #expect(value["command"]?.stringValue == "ls")
        #expect(value["count"]?.intValue == 3)
        #expect(value["flag"]?.boolValue == true)
        #expect(value["items"]?[1]?.intValue == 2)
        #expect(value["missing"] == nil)
    }

    @Test func canonicalStringSortsKeys() {
        let value: JSONValue = ["zebra": 1, "alpha": 2]
        #expect(value.canonicalString() == #"{"alpha":2,"zebra":1}"#)
    }

    @Test func integersRenderWithoutDecimal() {
        let value: JSONValue = ["tokens": 1500]
        #expect(value.canonicalString() == #"{"tokens":1500}"#)
    }

    @Test func unknownShapesSurviveLenientParse() throws {
        let value = try JSONValue(parsing: #"{"new_field":{"deeply":[{"unknown":null}]}}"#)
        #expect(value["new_field"]?["deeply"]?[0]?["unknown"]?.isNull == true)
    }
}
