using System.Net.Http.Json;
using System.Text.Json;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace Hc900Crawler.Infrastructure.Kb;

/// <summary>
/// Ollama nomic-embed-text(768-dim) 임베딩 클라이언트. /api/embeddings 직접 호출.
/// </summary>
public sealed class KbEmbeddingClient
{
    private readonly HttpClient _http;
    private readonly string _model;
    private readonly ILogger<KbEmbeddingClient> _logger;

    public KbEmbeddingClient(IHttpClientFactory factory, IConfiguration config, ILogger<KbEmbeddingClient> logger)
    {
        _http = factory.CreateClient("Ollama");
        _model = config["Kb:EmbeddingModel"] ?? "nomic-embed-text";
        _logger = logger;
    }

    public async Task<float[]?> EmbedAsync(string text, CancellationToken ct = default)
    {
        try
        {
            var res = await _http.PostAsJsonAsync("/api/embeddings", new { model = _model, prompt = text }, ct);
            if (!res.IsSuccessStatusCode)
            {
                _logger.LogWarning("[Kb][Embed] HTTP {Code}", (int)res.StatusCode);
                return null;
            }
            using var doc = JsonDocument.Parse(await res.Content.ReadAsStringAsync(ct));
            if (!doc.RootElement.TryGetProperty("embedding", out var arr)) return null;
            var len = arr.GetArrayLength();
            var vec = new float[len];
            int i = 0;
            foreach (var e in arr.EnumerateArray())
                vec[i++] = (float)e.GetDouble();
            return vec;
        }
        catch (Exception ex)
        {
            _logger.LogWarning(ex, "[Kb][Embed] 실패");
            return null;
        }
    }
}
