using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace Health.Infrastructure.AI;

/// <summary>
/// FastGPT 知识库检索客户端（仅做 RAG 检索，不参与生成）。
/// 我们后端的 DeepSeek 依旧负责对话生成与工具调用；
/// 这里只把检索到的医学知识片段拼回 system prompt，提升回答准确度。
/// </summary>
public sealed class FastGptKnowledgeClient(HttpClient http, IConfiguration config, ILogger<FastGptKnowledgeClient> logger)
{
    private readonly HttpClient _http = http;
    private readonly string _datasetId = config["FASTGPT_DATASET_ID"] ?? "";
    private readonly float _similarity = float.TryParse(config["FASTGPT_SIMILARITY"], out var s) ? s : 0.4f;
    private readonly int _limit = int.TryParse(config["FASTGPT_LIMIT"], out var l) ? l : 3000;
    private readonly ILogger<FastGptKnowledgeClient> _logger = logger;
    private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };

    public bool IsEnabled => !string.IsNullOrWhiteSpace(_datasetId);

    /// <summary>
    /// 按用户问题检索知识库，返回最相关的文档片段。
    /// 失败或未配置时返回空字符串，调用方应当容错——RAG 只是增强，不是必需。
    /// </summary>
    public async Task<string> SearchAsync(string question, CancellationToken ct = default)
    {
        if (!IsEnabled || string.IsNullOrWhiteSpace(question)) return "";

        try
        {
            var payload = new
            {
                datasetId = _datasetId,
                text = question,
                limit = _limit,
                similarity = _similarity,
                searchMode = "embedding",
            };
            var json = JsonSerializer.Serialize(payload);
            var content = new StringContent(json, Encoding.UTF8, "application/json");
            using var response = await _http.PostAsync("core/dataset/searchTest", content, ct);
            if (!response.IsSuccessStatusCode)
            {
                _logger.LogWarning("FastGPT 检索失败: {Status}", response.StatusCode);
                return "";
            }

            var body = await response.Content.ReadAsStringAsync(ct);
            using var doc = JsonDocument.Parse(body);
            if (!doc.RootElement.TryGetProperty("data", out var data)) return "";
            if (!data.TryGetProperty("list", out var list) || list.ValueKind != JsonValueKind.Array) return "";

            var snippets = new List<string>();
            foreach (var item in list.EnumerateArray())
            {
                var q = item.TryGetProperty("q", out var qEl) ? qEl.GetString() ?? "" : "";
                var a = item.TryGetProperty("a", out var aEl) ? aEl.GetString() ?? "" : "";
                if (string.IsNullOrWhiteSpace(q) && string.IsNullOrWhiteSpace(a)) continue;
                snippets.Add(string.IsNullOrWhiteSpace(a) ? q : $"{q}：{a}");
            }

            return snippets.Count == 0 ? "" : string.Join("\n", snippets);
        }
        catch (Exception ex)
        {
            _logger.LogWarning(ex, "FastGPT 检索异常，已忽略");
            return "";
        }
    }
}
