// SDK de Nexo Auth para Java 8 o superior (plugins de Minecraft: Spigot, Paper, Bukkit, Velocity, BungeeCord…).
// Un solo archivo y sin dependencias. Cópialo dentro de tu plugin y cambia la línea "package" por la de tu plugin:
// así cada plugin lleva su propia copia y no choca con otros plugins que también usen Nexo Auth.
//
// Uso básico:
//   NexoAuth auth = new NexoAuth("https://api.nexoauth.dev", "ID_PUBLICO", "MiPlugin", "1.0.0", "04…CLAVE_PUBLICA");
//   NexoAuth.Result r = auth.license(keyDelConfig);
//   if (!r.ok) { ...desactivar el plugin... }
//   auth.startHeartbeat(res -> { if (!res.ok) ...desactivar... });
//
// Todas las llamadas son bloqueantes: en Bukkit no las hagas en el hilo principal mientras el servidor está en marcha
// (en onEnable sí se puede: el servidor todavía está arrancando).
package nexo.auth;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.AlgorithmParameters;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.ECParameterSpec;
import java.security.spec.ECPoint;
import java.security.spec.ECPublicKeySpec;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

public final class NexoAuth {
    /** Tiempo máximo sin contacto con el servidor antes de dar la sesión por perdida. */
    private static final long GRACE_MS = 150_000;
    private static final int RETRY_SECONDS = 15;
    private static final SecureRandom RANDOM = new SecureRandom();

    private final String baseUrl;
    private final String productId;
    private final String clientName;
    private final String clientVersion;
    private final PublicKey publicKey;
    private String hwid;
    private String pcName;
    private String programHash = "";
    private volatile String sessionToken = "";
    private volatile long lastContact;
    private int heartbeatSeconds = 45;
    private ScheduledExecutorService heartbeat;
    private Map<String, Object> variables = Collections.emptyMap();
    private Map<String, Object> license;
    private Map<String, Object> user;

    /**
     * @param baseUrl       URL de la API, por ejemplo https://api.nexoauth.dev
     * @param productId     ID público del producto (panel → Productos)
     * @param clientName    nombre de tu plugin
     * @param clientVersion versión de tu plugin; si es menor que la del producto, la API responde UPDATE_REQUIRED
     * @param publicKey     clave pública del producto (130 caracteres que empiezan por 04). Con ella cada respuesta
     *                      se comprueba con ECDSA P-256 y nadie puede falsificar un "acceso correcto".
     */
    public NexoAuth(String baseUrl, String productId, String clientName, String clientVersion, String publicKey) {
        this.baseUrl = baseUrl.replaceAll("/+$", "");
        URL url;
        try { url = new URL(this.baseUrl); } catch (Exception e) { throw new IllegalArgumentException("baseUrl inválida"); }
        String host = url.getHost();
        if (!"https".equals(url.getProtocol()) && !host.equals("localhost") && !host.equals("127.0.0.1")) {
            throw new IllegalArgumentException("HTTP sin TLS solo está permitido para localhost");
        }
        if (publicKey == null || !publicKey.matches("(?i)^04[0-9a-f]{128}$")) {
            throw new IllegalArgumentException("publicKey inválida: copia la clave pública desde el panel (empieza por 04)");
        }
        this.productId = productId;
        this.clientName = clientName == null ? "NexoPlugin" : clientName;
        this.clientVersion = clientVersion == null ? "1.0.0" : clientVersion;
        this.publicKey = decodePublicKey(publicKey.toLowerCase());
        this.hwid = defaultHwid("");
        this.pcName = hostName();
    }

    // ---------------------------------------------------------------- Identidad del servidor

    /**
     * Identificador estable del equipo/servidor. Para plugins combina el identificador de la máquina, el nombre del host
     * y la carpeta del servidor, así dos servidores en la misma máquina (o en el mismo hosting) cuentan como distintos.
     * extra: cualquier dato tuyo que quieras sumar (por ejemplo el puerto). Si mueves el servidor de carpeta o de
     * máquina, libera la key desde el panel con "Reset HWID".
     */
    public static String defaultHwid(String extra) {
        String machine = "";
        try {
            String os = System.getProperty("os.name", "").toLowerCase();
            if (os.contains("win")) {
                Process p = new ProcessBuilder("reg", "query", "HKLM\\SOFTWARE\\Microsoft\\Cryptography", "/v", "MachineGuid", "/reg:64").redirectErrorStream(true).start();
                String out = new String(readAll(p.getInputStream()), StandardCharsets.UTF_8);
                java.util.regex.Matcher m = java.util.regex.Pattern.compile("[0-9a-fA-F-]{36}").matcher(out);
                if (m.find()) machine = m.group();
            } else {
                for (String path : new String[] {"/etc/machine-id", "/var/lib/dbus/machine-id"}) {
                    if (Files.isReadable(Paths.get(path))) { machine = new String(Files.readAllBytes(Paths.get(path)), StandardCharsets.UTF_8).trim(); break; }
                }
            }
        } catch (Exception ignored) { }
        String folder = new File("").getAbsolutePath();
        return sha256Hex(("nexo-java|" + machine + "|" + hostName() + "|" + folder + "|" + (extra == null ? "" : extra)).getBytes(StandardCharsets.UTF_8));
    }

    /** Cambia el identificador que se envía (por defecto, defaultHwid("")). */
    public void setHwid(String hwid) { this.hwid = hwid; }
    /** Nombre que verás en el panel en la columna "Equipo" (por defecto, el nombre del host). */
    public void setPcName(String pcName) { this.pcName = pcName; }

    // ---------------------------------------------------------------- Llamadas a la API

    /** Comprueba que el producto existe y está activo. programHash: SHA-256 del .jar, opcional (ver sha256File). */
    public Result init(String programHash) {
        // Se recuerda y se envía en todas las llamadas: si el producto tiene un hash configurado, la API lo exige siempre.
        this.programHash = programHash == null ? "" : programHash.trim().toLowerCase();
        return post("/v1/auth/init", base(), false, false);
    }

    /** Acceso solo con la key (lo normal en un plugin). */
    public Result license(String licenseKey) {
        Map<String, Object> body = base();
        body.put("licenseKey", licenseKey == null ? "" : licenseKey.trim());
        body.put("hwid", hwid);
        return post("/v1/auth/license", body, false, true);
    }

    /** Registro con usuario, contraseña y key. */
    public Result register(String username, String password, String licenseKey) {
        Map<String, Object> body = base();
        body.put("licenseKey", licenseKey);
        body.put("username", username);
        body.put("password", password);
        body.put("hwid", hwid);
        return post("/v1/auth/register-credentials", body, false, true);
    }

    /** Inicio de sesión con usuario y contraseña. */
    public Result login(String username, String password) {
        Map<String, Object> body = base();
        body.put("username", username);
        body.put("password", password);
        body.put("hwid", hwid);
        return post("/v1/auth/login", body, false, true);
    }

    /** Canjea otra key para sumar tiempo a una cuenta. */
    public Result upgrade(String username, String password, String licenseKey) {
        Map<String, Object> body = base();
        body.put("username", username);
        body.put("password", password);
        body.put("licenseKey", licenseKey);
        return post("/v1/auth/upgrade", body, false, false);
    }

    /** Variable del producto leída en el momento (las de la sesión están en getVar). */
    public Result fetchVar(String key) { return session("/v1/auth/var", map("key", key)); }
    /** Guarda un dato propio de este cliente en el servidor. */
    public Result setVar(String key, String value) { return session("/v1/auth/setvar", map("key", key, "value", value)); }
    /** Lee un dato propio de este cliente. */
    public Result getUserVar(String key) { return session("/v1/auth/getvar", map("key", key)); }
    /** Envía un mensaje que verás en el panel, en Logs y Telemetría. */
    public Result log(String message) { return session("/v1/auth/log", map("message", message, "pcName", pcName)); }

    /** Avisa al servidor que la sesión sigue activa. Tolera cortes de red de hasta 150 s. */
    public Result heartbeat() {
        Result r = session("/v1/auth/heartbeat", new LinkedHashMap<String, Object>());
        if (r.ok) lastContact = System.currentTimeMillis();
        else if (r.isTransient && System.currentTimeMillis() - lastContact < GRACE_MS) return r;
        else { r.isTransient = false; sessionToken = ""; }
        return r;
    }

    /** Cierra la sesión (llámalo en onDisable). */
    public Result logout() {
        stopHeartbeat();
        if (sessionToken.isEmpty()) return Result.local("SESSION_REQUIRED", "No hay una sesión iniciada");
        Result r = post("/v1/auth/logout", new LinkedHashMap<String, Object>(), true, false);
        sessionToken = "";
        return r;
    }

    /**
     * Heartbeat automático en un hilo propio. El callback recibe cada resultado definitivo: si r.ok es false la key fue
     * pausada, baneada, venció o se cerró la sesión desde el panel. En Bukkit, vuelve al hilo principal con
     * Bukkit.getScheduler().runTask(...) antes de desactivar el plugin.
     */
    public synchronized void startHeartbeat(final Consumer<Result> callback) {
        stopHeartbeat();
        final ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor(r -> {
            Thread t = new Thread(r, "NexoAuth-heartbeat");
            t.setDaemon(true);
            return t;
        });
        heartbeat = exec;
        exec.schedule(new Runnable() {
            public void run() {
                if (exec.isShutdown()) return;
                Result r = heartbeat();
                if (exec.isShutdown()) return;
                if (r.isTransient) { exec.schedule(this, RETRY_SECONDS, TimeUnit.SECONDS); return; }
                try { if (callback != null) callback.accept(r); } catch (RuntimeException ignored) { }
                if (r.ok && !exec.isShutdown()) {
                    heartbeatSeconds = Math.max(15, r.heartbeatSeconds());
                    exec.schedule(this, heartbeatSeconds, TimeUnit.SECONDS);
                } else exec.shutdown();
            }
        }, heartbeatSeconds, TimeUnit.SECONDS);
    }

    public synchronized void stopHeartbeat() {
        if (heartbeat != null) heartbeat.shutdownNow();
        heartbeat = null;
    }

    public boolean isAuthenticated() { return !sessionToken.isEmpty(); }
    /** Variable del producto recibida al iniciar sesión (panel → Productos → Variables). */
    public String getVar(String key, String fallback) { Object v = variables.get(key); return v == null ? fallback : String.valueOf(v); }
    /** Datos de la licencia de la sesión actual (id, keyPrefix, expiresAt, secondsLeft…). */
    public Map<String, Object> getLicense() { return license; }
    /** Usuario de la sesión actual, si entró con usuario y contraseña. */
    public Map<String, Object> getUser() { return user; }

    /** SHA-256 de un archivo, por ejemplo el .jar del plugin, para usarlo en init(). */
    public static String sha256File(File file) {
        try (InputStream in = new FileInputStream(file)) { return sha256Hex(readAll(in)); }
        catch (Exception e) { return ""; }
    }

    // ---------------------------------------------------------------- Resultado

    public static final class Result {
        public boolean ok;
        public int httpStatus;
        /** true si fue un corte de red o del servidor (se puede reintentar); false si fue un rechazo real y firmado. */
        public boolean isTransient;
        public String errorCode = "";
        public String message = "";
        public Map<String, Object> data = Collections.emptyMap();
        public String rawJson = "";

        static Result local(String code, String message) {
            Result r = new Result();
            r.errorCode = code;
            r.message = message;
            return r;
        }
        public String getString(String key) { Object v = data.get(key); return v == null ? null : String.valueOf(v); }
        /** Segundos que le quedan a la licencia; -1 si es de por vida o no se conoce. */
        public long secondsLeft() { Object v = data.get("secondsLeft"); return v instanceof Number ? ((Number) v).longValue() : -1; }
        int heartbeatSeconds() {
            Object v = data.get("nextHeartbeatSeconds");
            if (!(v instanceof Number)) v = data.get("heartbeatIntervalSeconds");
            return v instanceof Number ? ((Number) v).intValue() : 45;
        }
        /** Texto listo para mostrar en la consola. */
        public String describe() {
            if (ok) return "OK";
            String text = message == null || message.isEmpty() ? "Error" : message;
            return errorCode == null || errorCode.isEmpty() ? text : text + " (" + errorCode + ")";
        }
        @Override public String toString() { return "Result{ok=" + ok + ", status=" + httpStatus + ", error=" + errorCode + ", message=" + message + "}"; }
    }

    // ---------------------------------------------------------------- Interno

    private Map<String, Object> base() {
        Map<String, Object> body = new LinkedHashMap<String, Object>();
        body.put("productId", productId);
        Map<String, Object> client = new LinkedHashMap<String, Object>();
        client.put("name", clientName);
        client.put("version", clientVersion);
        client.put("platform", "java");
        client.put("pcName", pcName);
        body.put("client", client);
        return body;
    }

    private static Map<String, Object> map(Object... kv) {
        Map<String, Object> m = new LinkedHashMap<String, Object>();
        for (int i = 0; i < kv.length; i += 2) m.put((String) kv[i], kv[i + 1]);
        return m;
    }

    private Result session(String path, Map<String, Object> body) {
        if (sessionToken.isEmpty()) return Result.local("SESSION_REQUIRED", "No hay una sesión iniciada");
        return post(path, body, true, false);
    }

    @SuppressWarnings("unchecked")
    private Result post(String endpoint, Map<String, Object> payload, boolean authorized, boolean saveSession) {
        Result r = new Result();
        HttpURLConnection con = null;
        try {
            byte[] nonceBytes = new byte[16];
            RANDOM.nextBytes(nonceBytes);
            String nonce = hex(nonceBytes);
            con = (HttpURLConnection) new URL(baseUrl + endpoint).openConnection();
            con.setRequestMethod("POST");
            con.setConnectTimeout(10_000);
            con.setReadTimeout(15_000);
            con.setInstanceFollowRedirects(false);
            con.setDoOutput(true);
            con.setRequestProperty("Content-Type", "application/json");
            con.setRequestProperty("Accept", "application/json");
            con.setRequestProperty("User-Agent", "NexoAuth-Java/1.0");
            con.setRequestProperty("X-Nexo-Nonce", nonce);
            if (authorized && !sessionToken.isEmpty()) con.setRequestProperty("Authorization", "Bearer " + sessionToken);
            if (!programHash.isEmpty()) con.setRequestProperty("X-Nexo-Program-Hash", programHash);
            byte[] body = Json.write(payload).getBytes(StandardCharsets.UTF_8);
            try (OutputStream out = con.getOutputStream()) { out.write(body); }

            r.httpStatus = con.getResponseCode();
            InputStream in = r.httpStatus >= 400 ? con.getErrorStream() : con.getInputStream();
            r.rawJson = in == null ? "" : new String(readAll(in), StandardCharsets.UTF_8);

            // Se comprueba el texto tal como llegó: la firma cubre nonce, estado HTTP y cuerpo, también en los errores.
            boolean verified = verify(nonce + "." + r.httpStatus + "." + r.rawJson, con.getHeaderField("x-nexo-signature-v2"));
            Object parsed;
            try { parsed = Json.parse(r.rawJson); } catch (RuntimeException e) { parsed = null; }
            if (!(parsed instanceof Map)) {
                r.errorCode = verified ? "INVALID_RESPONSE" : "INVALID_SIGNATURE";
                r.message = "Respuesta inválida del servidor";
                r.isTransient = true;
                return r;
            }
            Map<String, Object> doc = (Map<String, Object>) parsed;
            Object data = doc.get("data"), error = doc.get("error");
            boolean ok = r.httpStatus >= 200 && r.httpStatus < 300 && Boolean.TRUE.equals(doc.get("success"));
            if (!verified) {
                // Una respuesta sin firma válida pudo ser alterada o inventada: nunca cuenta como acceso correcto.
                r.errorCode = "INVALID_SIGNATURE";
                r.message = "Firma criptográfica del servidor inválida";
                r.isTransient = !ok; // un error sin firma se trata como corte de red, no como rechazo
                return r;
            }
            if (data instanceof Map) r.data = (Map<String, Object>) data;
            if (ok && !nonce.equals(r.data.get("nonce"))) {
                r.errorCode = "REPLAY_DETECTED";
                r.message = "Nonce de respuesta inválido";
                return r;
            }
            if (error instanceof Map) {
                Object code = ((Map<String, Object>) error).get("code"), msg = ((Map<String, Object>) error).get("message");
                r.errorCode = code == null ? "" : String.valueOf(code);
                r.message = msg == null ? "" : String.valueOf(msg);
            }
            r.ok = ok;
            r.isTransient = !ok && !"MAINTENANCE".equals(r.errorCode) && (r.httpStatus >= 500 || r.httpStatus == 429);
            if (ok && saveSession && r.data.get("sessionToken") != null) {
                sessionToken = String.valueOf(r.data.get("sessionToken"));
                Object hb = r.data.get("heartbeatIntervalSeconds");
                heartbeatSeconds = Math.max(15, hb instanceof Number ? ((Number) hb).intValue() : 45);
                Object vars = r.data.get("variables");
                variables = vars instanceof Map ? (Map<String, Object>) vars : Collections.<String, Object>emptyMap();
                license = r.data.get("license") instanceof Map ? (Map<String, Object>) r.data.get("license") : null;
                user = r.data.get("user") instanceof Map ? (Map<String, Object>) r.data.get("user") : null;
                lastContact = System.currentTimeMillis();
            }
            return r;
        } catch (Exception e) {
            r.ok = false;
            r.httpStatus = 0;
            r.errorCode = "NETWORK_ERROR";
            r.message = e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage();
            r.isTransient = true;
            return r;
        } finally {
            if (con != null) con.disconnect();
        }
    }

    private boolean verify(String message, String signatureHex) {
        if (signatureHex == null || !signatureHex.matches("(?i)^[0-9a-f]{128}$")) return false;
        try {
            byte[] raw = unhex(signatureHex);
            Signature s = Signature.getInstance("SHA256withECDSA");
            s.initVerify(publicKey);
            s.update(message.getBytes(StandardCharsets.UTF_8));
            return s.verify(rawToDer(raw));
        } catch (Exception e) {
            return false;
        }
    }

    private static PublicKey decodePublicKey(String hex) {
        try {
            byte[] raw = unhex(hex);
            byte[] x = new byte[32], y = new byte[32];
            System.arraycopy(raw, 1, x, 0, 32);
            System.arraycopy(raw, 33, y, 0, 32);
            AlgorithmParameters params = AlgorithmParameters.getInstance("EC");
            params.init(new ECGenParameterSpec("secp256r1"));
            ECParameterSpec spec = params.getParameterSpec(ECParameterSpec.class);
            return KeyFactory.getInstance("EC").generatePublic(new ECPublicKeySpec(new ECPoint(new BigInteger(1, x), new BigInteger(1, y)), spec));
        } catch (Exception e) {
            throw new IllegalArgumentException("publicKey inválida: " + e.getMessage());
        }
    }

    /** La API firma en formato r||s (64 bytes); Java espera DER. */
    private static byte[] rawToDer(byte[] raw) {
        byte[] r = derInt(raw, 0), s = derInt(raw, 32);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        out.write(0x30);
        out.write(r.length + s.length);
        out.write(r, 0, r.length);
        out.write(s, 0, s.length);
        return out.toByteArray();
    }

    private static byte[] derInt(byte[] raw, int offset) {
        byte[] v = new BigInteger(1, java.util.Arrays.copyOfRange(raw, offset, offset + 32)).toByteArray();
        byte[] out = new byte[v.length + 2];
        out[0] = 0x02;
        out[1] = (byte) v.length;
        System.arraycopy(v, 0, out, 2, v.length);
        return out;
    }

    /** Nombre del equipo o contenedor donde corre el servidor. */
    public static String hostName() {
        String env = System.getenv("COMPUTERNAME");
        if (env == null || env.isEmpty()) env = System.getenv("HOSTNAME");
        if (env != null && !env.isEmpty()) return env;
        try { return InetAddress.getLocalHost().getHostName(); } catch (Exception e) { return "Servidor"; }
    }

    private static byte[] readAll(InputStream in) throws java.io.IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buf = new byte[8192];
        for (int n; (n = in.read(buf)) > 0; ) out.write(buf, 0, n);
        in.close();
        return out.toByteArray();
    }

    private static String sha256Hex(byte[] data) {
        try { return hex(MessageDigest.getInstance("SHA-256").digest(data)); }
        catch (Exception e) { throw new IllegalStateException(e); }
    }

    private static String hex(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length * 2);
        for (byte b : bytes) sb.append(String.format("%02x", b));
        return sb.toString();
    }

    private static byte[] unhex(String hex) {
        byte[] out = new byte[hex.length() / 2];
        for (int i = 0; i < out.length; i++) out[i] = (byte) Integer.parseInt(hex.substring(i * 2, i * 2 + 2), 16);
        return out;
    }

    // ---------------------------------------------------------------- JSON mínimo (sin librerías)

    static final class Json {
        private final String s;
        private int i;
        private Json(String s) { this.s = s; }

        static Object parse(String text) {
            Json p = new Json(text);
            p.ws();
            Object v = p.value();
            p.ws();
            if (p.i != p.s.length()) throw new IllegalArgumentException("JSON con texto sobrante");
            return v;
        }

        private void ws() { while (i < s.length() && Character.isWhitespace(s.charAt(i))) i++; }

        private Object value() {
            if (i >= s.length()) throw new IllegalArgumentException("JSON incompleto");
            char c = s.charAt(i);
            if (c == '{') return object();
            if (c == '[') return array();
            if (c == '"') return string();
            if (s.startsWith("true", i)) { i += 4; return Boolean.TRUE; }
            if (s.startsWith("false", i)) { i += 5; return Boolean.FALSE; }
            if (s.startsWith("null", i)) { i += 4; return null; }
            return number();
        }

        private Map<String, Object> object() {
            Map<String, Object> m = new LinkedHashMap<String, Object>();
            i++; ws();
            if (s.charAt(i) == '}') { i++; return m; }
            while (true) {
                ws();
                String key = string();
                ws();
                if (s.charAt(i++) != ':') throw new IllegalArgumentException("Se esperaba ':'");
                ws();
                m.put(key, value());
                ws();
                char c = s.charAt(i++);
                if (c == '}') return m;
                if (c != ',') throw new IllegalArgumentException("Se esperaba ',' o '}'");
            }
        }

        private List<Object> array() {
            List<Object> l = new ArrayList<Object>();
            i++; ws();
            if (s.charAt(i) == ']') { i++; return l; }
            while (true) {
                ws();
                l.add(value());
                ws();
                char c = s.charAt(i++);
                if (c == ']') return l;
                if (c != ',') throw new IllegalArgumentException("Se esperaba ',' o ']'");
            }
        }

        private String string() {
            if (s.charAt(i) != '"') throw new IllegalArgumentException("Se esperaba texto");
            StringBuilder sb = new StringBuilder();
            i++;
            while (true) {
                char c = s.charAt(i++);
                if (c == '"') return sb.toString();
                if (c != '\\') { sb.append(c); continue; }
                char e = s.charAt(i++);
                switch (e) {
                    case 'n': sb.append('\n'); break;
                    case 't': sb.append('\t'); break;
                    case 'r': sb.append('\r'); break;
                    case 'b': sb.append('\b'); break;
                    case 'f': sb.append('\f'); break;
                    case 'u': sb.append((char) Integer.parseInt(s.substring(i, i + 4), 16)); i += 4; break;
                    default: sb.append(e);
                }
            }
        }

        private Number number() {
            int start = i;
            while (i < s.length() && "+-0123456789.eE".indexOf(s.charAt(i)) >= 0) i++;
            String n = s.substring(start, i);
            if (n.isEmpty()) throw new IllegalArgumentException("Valor JSON inválido");
            if (n.matches("-?\\d{1,18}")) return Long.parseLong(n);
            return Double.parseDouble(n);
        }

        @SuppressWarnings("unchecked")
        static String write(Object v) {
            if (v == null) return "null";
            if (v instanceof Boolean || v instanceof Number) return String.valueOf(v);
            if (v instanceof Map) {
                StringBuilder sb = new StringBuilder("{");
                for (Map.Entry<String, Object> e : ((Map<String, Object>) v).entrySet()) {
                    if (sb.length() > 1) sb.append(',');
                    sb.append(write(e.getKey())).append(':').append(write(e.getValue()));
                }
                return sb.append('}').toString();
            }
            if (v instanceof List) {
                StringBuilder sb = new StringBuilder("[");
                for (Object o : (List<Object>) v) { if (sb.length() > 1) sb.append(','); sb.append(write(o)); }
                return sb.append(']').toString();
            }
            String str = String.valueOf(v);
            StringBuilder sb = new StringBuilder("\"");
            for (int k = 0; k < str.length(); k++) {
                char c = str.charAt(k);
                switch (c) {
                    case '"': sb.append("\\\""); break;
                    case '\\': sb.append("\\\\"); break;
                    case '\n': sb.append("\\n"); break;
                    case '\r': sb.append("\\r"); break;
                    case '\t': sb.append("\\t"); break;
                    default:
                        if (c < 0x20) sb.append(String.format("\\u%04x", (int) c));
                        else sb.append(c);
                }
            }
            return sb.append('"').toString();
        }
    }
}
