package com.suixingpay.serialsdk.utils;

import android.util.Log;

import org.json.JSONObject;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class JsonBufferHelper {

    private static final String TAG = "JsonBufferHelper";
    private final StringBuilder buffer = new StringBuilder();

    public synchronized List<JSONObject> append(byte[] fragment) {
        if (fragment == null || fragment.length == 0) {
            return new ArrayList<>();
        }

        String incoming = new String(fragment, StandardCharsets.UTF_8);
        buffer.append(incoming);
        return extractJsonObjects();
    }

    private List<JSONObject> extractJsonObjects() {
        List<JSONObject> result = new ArrayList<>();
        String data = buffer.toString();
        int braceCount = 0;
        int start = -1;

        for (int i = 0; i < data.length(); i++) {
            char c = data.charAt(i);
            if (c == '{') {
                if (braceCount == 0) start = i;
                braceCount++;
            } else if (c == '}') {
                braceCount--;
                if (braceCount == 0 && start != -1) {
                    String jsonStr = data.substring(start, i + 1);
                    try {
                        JSONObject json = new JSONObject(jsonStr);
                        result.add(json);
                    } catch (Exception e) {
                        Log.w(TAG, "⚠️ 忽略损坏 JSON：" + jsonStr);
                    }
                    start = -1;
                }
            }
        }

        // 清理 buffer 中已消费的部分
        int lastEnd = data.lastIndexOf('}');
        if (lastEnd != -1 && lastEnd + 1 < data.length()) {
            buffer.setLength(0);
            buffer.append(data.substring(lastEnd + 1));
        } else if (lastEnd != -1) {
            buffer.setLength(0);
        }

        // 如果太多垃圾字符，自动清理
        if (buffer.length() > 4096) {
            Log.w(TAG, "⚠️ 缓冲区过长，自动清空");
            buffer.setLength(0);
        }

        return result;
    }

    public synchronized void clear() {
        buffer.setLength(0);
    }
}
