using System.Text.RegularExpressions;

namespace YMhut.Box.Core.Tools;

public static class ToolResultPrivacySanitizer
{
    private static readonly Regex UrlPattern = new(
        @"https?://[^\s\]\)""'<>]+",
        RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);

    private static readonly Regex RequestUrlContextPattern = new(
        @"(?:api[_\-\s]*url|request[_\-\s]*url|api\s+request|endpoint|接口地址|请求地址)\s*[:=：]?\s*$",
        RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);

    public static IReadOnlyList<string> DefaultRedactedHostHints { get; } =
        ["ymhut.cn", "ymhut.com", "api.ymhut", "update.ymhut"];

    public static string Redact(string? value, string language, IReadOnlyList<string>? hostHints = null)
    {
        if (string.IsNullOrEmpty(value))
        {
            return string.Empty;
        }

        var hints = hostHints is { Count: > 0 } ? hostHints : DefaultRedactedHostHints;
        var placeholder = IsEnglish(language) ? "[YMhut endpoint hidden]" : "[已隐藏 YMhut 接口]";
        return UrlPattern.Replace(value, match =>
            ShouldRedact(match.Value, value, match.Index, hints) ? placeholder : match.Value);
    }

    private static bool ShouldRedact(string candidate, string fullText, int index, IReadOnlyList<string> hostHints)
    {
        if (Uri.TryCreate(candidate, UriKind.Absolute, out var uri))
        {
            var host = uri.Host;
            if (hostHints.Any(hint => host.Contains(hint, StringComparison.OrdinalIgnoreCase)))
            {
                return true;
            }
        }

        var contextStart = Math.Max(0, index - 64);
        var context = fullText[contextStart..index];
        return RequestUrlContextPattern.IsMatch(context);
    }

    private static bool IsEnglish(string? language)
        => string.Equals(language, "en-US", StringComparison.OrdinalIgnoreCase) ||
           string.Equals(language, "en", StringComparison.OrdinalIgnoreCase);
}
