package quant.rich.emoney.util;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.agent.ByteBuddyAgent;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.dynamic.loading.ClassReloadingStrategy;
import static net.bytebuddy.matcher.ElementMatchers.*;

public class PatchOkHttpUAStatic {

  // 入口方法：只需调用一次
  public static void replace(String uaString) {
    try {
      ByteBuddyAgent.install();

      // 传递目标 UA 值到 Advice
      UserAgentAdvice.overrideValue = uaString;

      new ByteBuddy()
        .redefine(Class.forName("okhttp3.Request$Builder"))
        .visit(Advice.to(UserAgentAdvice.class)
          .on(named("header").and(takesArguments(String.class, String.class))))
        .make()
        .load(Class.forName("okhttp3.Request$Builder").getClassLoader(),
              ClassReloadingStrategy.fromInstalledAgent());

      System.out.println("[PatchOkHttpUA] Successfully installed custom User-Agent hook.");
    } catch (Exception e) {
      e.printStackTrace();
      System.err.println("[PatchOkHttpUA] Failed to patch OkHttp.");
    }
  }

  // 内部类：修改 header(name, value) 方法逻辑
  public static class UserAgentAdvice {
    public static String overrideValue = "MySpoofed-UA";

    @Advice.OnMethodEnter(skipOn = Advice.OnNonDefaultValue.class)
    static boolean intercept(
        @Advice.This Object builder,
        @Advice.Argument(0) String name,
        @Advice.Argument(value = 1, readOnly = false) String value) {
      if ("User-Agent".equalsIgnoreCase(name)) {
        value = overrideValue;
        System.out.println("[PatchOkHttpUA] Replaced User-Agent with: " + value);
      }
      return false; // 不跳过原方法，继续执行但已修改参数
    }
  }
}