import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Some small models send the whole call as the arguments, under "parameters" or "arguments":
 *   {"type":"function","function":"get_weather","parameters":{"city":"Pune","unit":"celsius"}}
 *   {"type":"get_weather","arguments":{"city":"Mumbai","unit":"celsius"}}
 * instead of {"city":"Pune","unit":"celsius"}. If the arguments are shaped like that envelope, return the inner object.
 * Anything else, including an object with other real keys next to the wrapper, is returned unchanged, so a genuinely invalid call still fails validation.
 */
public final class EnvelopeUnwrap {

    private static final ObjectMapper JSON = new ObjectMapper();

    public static String unwrap(String arguments) {
        try {
            JsonNode n = JSON.readTree(arguments);
            if (n != null && n.isObject()) {
                for (String key : new String[] {"parameters", "arguments"}) {
                    if (n.has(key) && n.get(key).isObject() && onlyEnvelopeKeysBesides(n, key)) {
                        return JSON.writeValueAsString(n.get(key));
                    }
                }
            }
        } catch (Exception ignored) {
            // not JSON at all: let the schema check report it
        }
        return arguments;
    }

    /** True when every other key is envelope furniture (type, function, name, label), so no real argument is thrown away. */
    private static boolean onlyEnvelopeKeysBesides(JsonNode n, String key) {
        var names = n.fieldNames();
        while (names.hasNext()) {
            String f = names.next();
            if (!f.equals(key) && !java.util.Set.of("type", "function", "name", "label").contains(f)) return false;
        }
        return true;
    }

    public static void main(String[] a) {
        System.out.println(unwrap("{\"type\":\"function\",\"function\":\"get_weather\",\"parameters\":{\"city\":\"Pune\",\"unit\":\"celsius\"}}"));
        System.out.println(unwrap("{\"type\":\"get_weather\",\"arguments\":{\"city\":\"Mumbai\",\"unit\":\"celsius\"}}"));
        System.out.println(unwrap("{\"city\":\"Pune\"}"));
        System.out.println(unwrap("{\"type\":\"object\",\"properties\":{\"minutes_from_now\":2,\"text\":{\"type\":\"string\"}}}"));
    }
}
