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;

/**
 * SHPSSDK riskToken 净化：尾部 |09|1 → |00|0（Root+Emulator+Hook 标记）。
 */
final class MariBankRiskTokenUtil {

    private static final String TAG = "notiMessageHook/MariBankRoot";
    private static final Pattern RISK_TOKEN_JSON = Pattern.compile(
            "\"riskToken\"\\s*:\\s*\"([^\"]+)\"");
    private static final Pattern DEVICE_TOKEN_JSON = Pattern.compile(
            "\"deviceToken\"\\s*:\\s*\"([^\"]+)\"");
    private static final Pattern RISK_TOKEN_BODY = Pattern.compile(
            "([A-Za-z0-9+/=]{8,}\\|[A-Za-z0-9+/=_-]{8,}\\|[A-Za-z0-9+/=_-]{3,}\\|)\\d+(\\|\\d+)");

    private MariBankRiskTokenUtil() {
    }

    static String sanitizeRiskToken(String token) {
        if (token == null || token.isEmpty() || !token.contains("|")) {
            return token;
        }
        if (!RISK_TOKEN_BODY.matcher(token).find() && !token.matches(".*\\|\\d+\\|\\d+$")) {
            return token;
        }
        int secondLast = token.lastIndexOf('|');
        if (secondLast <= 0) {
            return token;
        }
        secondLast = token.lastIndexOf('|', secondLast - 1);
        if (secondLast <= 0) {
            return token;
        }
        String oldTail = token.substring(secondLast + 1);
        String neu = token.substring(0, secondLast) + "|00|0";
        XposedBridge.log(TAG + " sanitized riskToken tail " + oldTail + " -> 00|0");
        return neu;
    }

    static String sanitizeAllInText(String text) {
        if (text == null || !text.contains("|")) {
            return text;
        }
        Matcher m = RISK_TOKEN_BODY.matcher(text);
        StringBuffer sb = new StringBuffer();
        boolean changed = false;
        while (m.find()) {
            m.appendReplacement(sb, Matcher.quoteReplacement(m.group(1) + "00|0"));
            changed = true;
        }
        if (!changed) {
            String out = sanitizeJsonField(text, RISK_TOKEN_JSON);
            out = sanitizeJsonField(out, DEVICE_TOKEN_JSON);
            return out;
        }
        m.appendTail(sb);
        XposedBridge.log(TAG + " sanitized riskToken in text len=" + text.length());
        return sb.toString();
    }

    static byte[] sanitizeBytes(byte[] data, int offset, int length) {
        if (data == null || length <= 0) {
            return data;
        }
        String text = new String(data, offset, length, StandardCharsets.UTF_8);
        if (!text.contains("|")) {
            return data;
        }
        String sanitized = sanitizeAllInText(text);
        return sanitized.equals(text) ? data : sanitized.getBytes(StandardCharsets.UTF_8);
    }

    private static String sanitizeJsonField(String text, Pattern fieldPattern) {
        Matcher json = fieldPattern.matcher(text);
        if (!json.find()) {
            return text;
        }
        String oldToken = json.group(1);
        String newToken = sanitizeRiskToken(oldToken);
        return oldToken.equals(newToken) ? text : text.replace(oldToken, newToken);
    }

    static String tail(String token) {
        if (token == null || !token.contains("|")) {
            return "n/a";
        }
        int last = token.lastIndexOf('|');
        int second = token.lastIndexOf('|', last - 1);
        if (second < 0) {
            return "n/a";
        }
        return token.substring(second + 1);
    }
}
