Java.perform(function () {
    const A9VSAuthenticator = Java.use("com.amazon.vsearch.lens.network.internal.A9VSAuthenticator");
    const Map = Java.use("java.util.Map");
    const Arrays = Java.use("java.util.Arrays");

    // 1. Hook 构造函数
    A9VSAuthenticator.$init.implementation = function (credentials) {
        console.log("\n[+] A9VSAuthenticator 构造函数被调用");
        try {
            console.log("  Credentials 详情:");
            console.log("    username: " + credentials.getUsername());
            console.log("    secret: " + credentials.getSecret());
            console.log("    application: " + credentials.getApplication());
            console.log("    disableAuthTokenGeneration: " + credentials.getDisableAuthTokenGeneration());
        } catch (e) {
            console.log("  获取 Credentials 失败: " + e.message);
        }
        this.$init(credentials);
    };

    // 2. Hook generateAuthParams（通过反射获取所有键，确保完整性）
    A9VSAuthenticator.generateAuthParams.overload().implementation = function () {
        console.log("\n[+] 调用 generateAuthParams()");
        const authParams = this.generateAuthParams();
        const castedMap = Java.cast(authParams, Map);

        console.log("  返回的完整认证参数:");
        try {
            // 反射调用 keySet() 获取所有键，转换为数组
            const keySet = castedMap.keySet();
            const keyArray = Java.array('java.lang.Object', keySet.toArray()); // 转换为 JS 可遍历的数组

            // 遍历所有键
            for (let i = 0; i < keyArray.length; i++) {
                const key = keyArray[i];
                const value = castedMap.get(key);
                console.log(`    ${key}: ${value}`);
            }
        } catch (e) {
            console.log("  遍历参数失败，使用已知参数 fallback:");
            // 已知参数 fallback（确保至少能获取核心参数）
            const knownKeys = ["application", "username", "ts", "authtoken"];
            knownKeys.forEach(key => {
                if (castedMap.containsKey(key)) {
                    console.log(`    ${key}: ${castedMap.get(key)}`);
                }
            });
        }
        return authParams;
    };

    // 3. Hook generateAuthToken
    A9VSAuthenticator.generateAuthToken.overload("java.lang.String").implementation = function (timestamp) {
        console.log("\n[+] 调用 generateAuthToken(timestamp)");
        console.log("  入参 timestamp: " + timestamp);
        const authToken = this.generateAuthToken(timestamp);
        console.log("  返回的 authtoken: " + authToken);
        return authToken;
    };
});