package com.miraclegarden.smsmessage.xposed.hook;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Locale;

import de.robv.android.xposed.XposedBridge;

/**
 * 拦截 root 探测命令时返回「空 / 失败」假进程，避免抛异常被 SHPSSDK 记为 tamper。
 */
public final class ProbeGuard {

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

    private ProbeGuard() {
    }

    public static boolean isBlockedCommand(String command) {
        if (command == null || command.isEmpty()) {
            return false;
        }
        String lower = command.toLowerCase(Locale.US);
        return lower.contains(" magisk")
                || lower.contains("/su")
                || lower.startsWith("su")
                || lower.contains("which su")
                || lower.contains("getprop ro.debuggable")
                || lower.contains("busybox")
                || lower.equals("su");
    }

    public static boolean isBlockedCommand(List<String> commands) {
        if (commands == null || commands.isEmpty()) {
            return false;
        }
        return isBlockedCommand(String.join(" ", commands));
    }

    public static Process fakeFailedProcess(String reason) {
        XposedBridge.log(TAG + " fake probe process: " + reason);
        return new FakeProcess();
    }

    private static final class FakeProcess extends Process {
        @Override
        public OutputStream getOutputStream() {
            return OutputStream.nullOutputStream();
        }

        @Override
        public InputStream getInputStream() {
            return new ByteArrayInputStream(new byte[0]);
        }

        @Override
        public InputStream getErrorStream() {
            return new ByteArrayInputStream(new byte[0]);
        }

        @Override
        public int waitFor() {
            return 1;
        }

        @Override
        public int exitValue() {
            return 1;
        }

        @Override
        public void destroy() {
        }
    }
}
