using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;

namespace AiLogia.AssistantProxy;

record Msg(string role, string content);
record ChatReq(List<Msg> messages, string? mode, object? user);
record ChatRes(string role, string content);

record OaiMsg(string role, string content);
record OaiReq(string model, List<OaiMsg> messages, bool stream = false);
record OaiChoice(int index, OaiMsg message);
record OaiResp(List<OaiChoice> choices);

internal class Program
{
    private static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);
        builder.Configuration.AddJsonFile("config.json", optional: true, reloadOnChange: true)
                             .AddEnvironmentVariables();
        builder.Services.AddHttpClient();
        var app = builder.Build();

        var cfg = app.Configuration;
        var apiKey = cfg["Auth:ApiKey"] ?? "";
        var llmUrl = cfg["Llm:BaseUrl"] ?? "";
        var llmModel = cfg["Llm:Model"] ?? "qwen2.5";
        var llmKey = cfg["Llm:ApiKey"] ?? "";
        var hrPath = cfg["Prompts:HrSystemPath"] ?? "Prompts/hr.system.md";

        bool CheckKey(HttpRequest r) =>
            r.Headers.TryGetValue("X-Api-Key", out var v) && v.ToString() == apiKey;

        app.MapGet("/api/health", () => Results.Ok(new { ok = true }));

        app.MapPost("/api/chat", async (HttpContext http, ChatReq req, IHttpClientFactory f) =>
        {
            if (!CheckKey(http.Request)) return Results.Unauthorized();

            var sys = await File.ReadAllTextAsync(hrPath);
            var userJson = req.user is null ? "" : JsonSerializer.Serialize(req.user);
            var msgs = new List<OaiMsg> { new("system", sys + (string.IsNullOrEmpty(userJson) ? "" : $"\n\nUserProfile: {userJson}")) };
            msgs.AddRange(req.messages.Select(m => new OaiMsg(m.role, m.content)));

            var oaiReq = new OaiReq(llmModel, msgs, stream: false);
            var client = f.CreateClient();

            var httpReq = new HttpRequestMessage(HttpMethod.Post, llmUrl)
            {
                Content = new StringContent(JsonSerializer.Serialize(oaiReq), Encoding.UTF8, "application/json")
            };
            if (!string.IsNullOrEmpty(llmKey))
                httpReq.Headers.Authorization = new AuthenticationHeaderValue("Bearer", llmKey);

            var httpRes = await client.SendAsync(httpReq, HttpCompletionOption.ResponseHeadersRead);
            var body = await httpRes.Content.ReadAsStringAsync();

            if (!httpRes.IsSuccessStatusCode)
                return Results.Problem(body, statusCode: (int)httpRes.StatusCode);

            var oai = JsonSerializer.Deserialize<OaiResp>(body, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
            var msg = oai?.choices?.FirstOrDefault()?.message;
            if (msg is null) return Results.BadRequest(new { error = "Empty LLM response" });

            return Results.Ok(new ChatRes(msg.role, msg.content));
        });

        app.Run();

    }
}
