// Java 17+；只使用标准库。
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.time.Duration;
import java.util.HexFormat;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

class OpenApiExample {
  private static String requiredEnv(String name) {
    String value = System.getenv(name);
    if (value == null || value.isBlank()) throw new IllegalArgumentException("请设置环境变量 " + name);
    return value;
  }

  public static void main(String[] args) throws Exception {
    String baseURL = requiredEnv("OPEN_API_BASE_URL").replaceFirst("/+$", "");
    String apiKey = requiredEnv("OPEN_API_KEY");
    String secret = requiredEnv("OPEN_API_SECRET");
    String path = "/api/v1/open/watch-data/viewers/query";
    String rawBody = "{\"ticketCode\":\"demo-live\",\"playbackMode\":\"REPLAY\",\"uids\":[10000],\"minWatchSeconds\":0,\"sort\":\"WATCH_SECONDS_DESC\",\"pageSize\":100}";
    byte[] bodyBytes = rawBody.getBytes(StandardCharsets.UTF_8);
    String timestamp = Long.toString(System.currentTimeMillis() / 1000);
    byte[] nonceBytes = new byte[16];
    new SecureRandom().nextBytes(nonceBytes);
    String nonce = HexFormat.of().formatHex(nonceBytes);
    String bodyHash = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bodyBytes));
    String canonical = String.join("\n", apiKey, "POST", path, timestamp, nonce, bodyHash);
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
    String signature = HexFormat.of().formatHex(mac.doFinal(canonical.getBytes(StandardCharsets.UTF_8)));

    HttpRequest request = HttpRequest.newBuilder(URI.create(baseURL + path))
        .timeout(Duration.ofSeconds(15))
        .header("Content-Type", "application/json")
        .header("X-API-Key", apiKey)
        .header("X-Timestamp", timestamp)
        .header("X-Nonce", nonce)
        .header("X-Signature", signature)
        .POST(HttpRequest.BodyPublishers.ofByteArray(bodyBytes))
        .build();
    HttpClient client = HttpClient.newBuilder()
        .connectTimeout(Duration.ofSeconds(15))
        .followRedirects(HttpClient.Redirect.NEVER)
        .build();
    HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
    // 仅在本地对接时查看完整响应；正式业务请用项目的 JSON 库解析，禁止记录完整观众资料或登录票据。
    System.out.printf("status=%d%n%s%n", response.statusCode(), response.body());
  }
}
