package com.miraclegarden.smsmessage.xposed.hook;

import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import de.robv.android.xposed.XposedBridge;

/**
 * register 加密前 JSON 净化：{@code scene=REGISTRATION} 路径上的 deviceFingerprint / riskToken。
 */
final class MariBankRegisterPayloadUtil {

    private static final String TAG = "notiMessageHook/MariBankRegister";

    private static final Pattern DEVICE_FINGERPRINT = Pattern.compile(
            "\"deviceFingerprint\"\\s*:\\s*\"([^\"]+)\"");

    private MariBankRegisterPayloadUtil() {
    }

    static boolean isRegistrationPayload(String text) {
        if (text == null || text.length() < 24) {
            return false;
        }
        return text.contains("\"scene\":\"REGISTRATION\"")
                || text.contains("\"scene\": \"REGISTRATION\"")
                || (text.contains("rdVerifyInfo") && text.contains("\"step\":\"BE\""));
    }

    static byte[] sanitizeRegistrationBytes(byte[] data) {
        if (data == null || data.length == 0) {
            return data;
        }
        String text = new String(data, StandardCharsets.UTF_8);
        if (!isRegistrationPayload(text)) {
            return MariBankRiskTokenUtil.sanitizeBytes(data, 0, data.length);
        }
        String out = sanitizeRegistrationJson(text);
        if (out.equals(text)) {
            return data;
        }
        XposedBridge.log(TAG + " sanitized register payload len=" + data.length + " -> " + out.length());
        return out.getBytes(StandardCharsets.UTF_8);
    }

    static String sanitizeRegistrationJson(String json) {
        if (json == null) {
            return null;
        }
        String out = MariBankRiskTokenUtil.sanitizeAllInText(json);
        Matcher m = DEVICE_FINGERPRINT.matcher(out);
        StringBuffer sb = new StringBuffer();
        boolean changed = false;
        while (m.find()) {
            String old = m.group(1);
            String neu = MariBankRiskTokenUtil.sanitizeRiskToken(old);
            if (!neu.equals(old)) {
                changed = true;
            }
            m.appendReplacement(sb, Matcher.quoteReplacement(
                    "\"deviceFingerprint\":\"" + neu + "\""));
        }
        if (changed) {
            m.appendTail(sb);
            out = sb.toString();
            XposedBridge.log(TAG + " deviceFingerprint sanitized in register JSON");
        }
        return out;
    }
}
