using System;
using System.Text;
using System.Text.Json;

namespace AiLogia.Web.Services;

public record ChatMessage(string role, string content);
public record ChatRequest(List<ChatMessage> messages, string? mode, object? user);
public record ChatResponse(string role, string content);

public interface IAssistantProxyClient
{
    Task<ChatResponse> ChatAsync(ChatRequest req, CancellationToken ct = default);
}

public sealed class AssistantProxyClient : IAssistantProxyClient
{
    private readonly HttpClient _http;
    private readonly string _apiKey;
    private readonly string _baseUrl;
    private static readonly JsonSerializerOptions J = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };

    public AssistantProxyClient(IHttpClientFactory f, IConfiguration cfg)
    {
        _http = f.CreateClient();
        _baseUrl = cfg["AssistantProxy:BaseUrl"] ?? throw new Exception("AssistantProxy:BaseUrl not set");
        _apiKey = cfg["AssistantProxy:ApiKey"] ?? "";
    }

    public async Task<ChatResponse> ChatAsync(ChatRequest req, CancellationToken ct = default)
    {
        var httpReq = new HttpRequestMessage(HttpMethod.Post, $"{_baseUrl}/api/chat")
        {
            Content = new StringContent(JsonSerializer.Serialize(req, J), Encoding.UTF8, "application/json")
        };
        if (!string.IsNullOrEmpty(_apiKey)) httpReq.Headers.Add("X-Api-Key", _apiKey);

        var res = await _http.SendAsync(httpReq, ct);
        var body = await res.Content.ReadAsStringAsync(ct);
        if (!res.IsSuccessStatusCode) throw new Exception($"AssistantProxy error: {body}");

        return JsonSerializer.Deserialize<ChatResponse>(body, new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!;
    }
}