/*
 *  Copyright (c) 2023-2026, Easy-Agents (fuhai999@gmail.com).
 *  <p>
 *  Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.easyagents.core.model.chat.log;

/**
 * 清理聊天请求日志中的大体积或敏感媒体内容。
 */
final class ChatLogSanitizer {

    private static final String DATA_URI_PREFIX = "data:image/";
    private static final String BASE64_MARKER = ";base64,";

    private ChatLogSanitizer() {
    }

    /**
     * 隐去图片 Data URI 的编码正文，仅保留 MIME 和字符长度。
     *
     * @param message 原始日志消息
     * @return 脱敏后的日志消息
     */
    static String redactImageDataUris(String message) {
        if (message == null || message.indexOf(DATA_URI_PREFIX) < 0) {
            return message;
        }

        StringBuilder sanitized = new StringBuilder(message.length());
        int cursor = 0;
        while (cursor < message.length()) {
            int dataUriStart = message.indexOf(DATA_URI_PREFIX, cursor);
            if (dataUriStart < 0) {
                sanitized.append(message, cursor, message.length());
                break;
            }
            int base64Marker = message.indexOf(BASE64_MARKER, dataUriStart);
            if (base64Marker < 0) {
                sanitized.append(message, cursor, message.length());
                break;
            }
            int payloadStart = base64Marker + BASE64_MARKER.length();
            int payloadEnd = payloadStart;
            while (payloadEnd < message.length() && isBase64Character(message.charAt(payloadEnd))) {
                payloadEnd++;
            }

            sanitized.append(message, cursor, payloadStart);
            sanitized.append("<已脱敏，编码长度=").append(payloadEnd - payloadStart).append('>');
            cursor = payloadEnd;
        }
        return sanitized.toString();
    }

    /**
     * 判断字符是否可能属于 Base64 正文。
     *
     * @param value 待判断字符
     * @return 是否属于 Base64 字符集
     */
    private static boolean isBase64Character(char value) {
        return value >= 'A' && value <= 'Z'
                || value >= 'a' && value <= 'z'
                || value >= '0' && value <= '9'
                || value == '+'
                || value == '/'
                || value == '='
                || value == '-'
                || value == '_';
    }
}
