using Agent86.Models;
using System.Text;
using System.Text.Json;

namespace Agent86.Services
{

    public class OllamaService
    {
        private readonly HttpClient _http;

        public OllamaService(HttpClient http)
        {
            _http = http;
        }

        public async Task<string> GenerateReplyAsync(List<ChatMessage> messages, string roleplayContext)
        {
            var promptBuilder = new StringBuilder();

            // System roleplay context
            promptBuilder.AppendLine("[SYSTEM ROLEPLAY CONTEXT]");
            promptBuilder.AppendLine(roleplayContext);
            promptBuilder.AppendLine();

            // Conversation history
            foreach (var msg in messages)
            {
                promptBuilder.AppendLine($"[{msg.Role.ToUpper()}]: {msg.Content}");
            }

            promptBuilder.AppendLine("[ASSISTANT]:");

            var request = new
            {
                model = "llama3.1:8b",
                prompt = promptBuilder.ToString(),
                stream = false
            };

            //https://agent:12tf56so@ollama-api.a.ucnit.eu/v1/chat/completions
            //AI: http://localhost:11434/api/generate
            var response = await _http.PostAsync(
                "https://agent:12tf56so@ollama-api.a.ucnit.eu/api/generate",
                new StringContent(JsonSerializer.Serialize(request), Encoding.UTF8, "application/json"));

            var json = await response.Content.ReadAsStringAsync();
            using var doc = JsonDocument.Parse(json);

            return doc.RootElement.GetProperty("response").GetString();
        }
    }
}
