using System.Net.Http.Json;
using System.Text.Json;
using Groq.Models;

namespace Groq.Services;

public class GroqService {
    private readonly HttpClient _httpClient;
    private readonly string _apiUrl;
    private readonly string _model;
    private readonly List<ChatMessage> _conversationHistory = new();
    private ChatMessage? _systemPrompt = null;

    public GroqService(string apiKey, string apiUrl, string model) {
        _httpClient = new HttpClient();
        _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
        _apiUrl = apiUrl;
        _model = model;
    }

    // Demo 1: Podstawowe wywołanie
    public async Task<ChatResponse?> SendMessageAsync(string userMessage) {
        var messages = new List<ChatMessage>();

        if (_systemPrompt != null)
            messages.Add(_systemPrompt);

        messages.Add(new ChatMessage { role = "user", content = userMessage });

        var request = new ChatRequest {
            model = _model,
            messages = messages
        };

        var response = await _httpClient.PostAsJsonAsync(_apiUrl, request);
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadFromJsonAsync<ChatResponse>();
    }

    public async IAsyncEnumerable<string> StreamMessageAsync(string userMessage) {
        var messages = new List<ChatMessage>();

        // Add system prompt if set
        if (_systemPrompt != null)
            messages.Add(_systemPrompt);

        messages.Add(new ChatMessage { role = "user", content = userMessage });

        var requestJson = JsonSerializer.Serialize(new {
            model = _model,
            messages = messages,
            temperature = 0.7,
            max_tokens = 1000,
            stream = true
        });

        var content = new StringContent(requestJson, System.Text.Encoding.UTF8, "application/json");
        var httpRequest = new HttpRequestMessage(HttpMethod.Post, _apiUrl) {
            Content = content
        };

        using var response = await _httpClient.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead);
        response.EnsureSuccessStatusCode();

        using var stream = await response.Content.ReadAsStreamAsync();
        using var reader = new StreamReader(stream);

        while (!reader.EndOfStream) {
            var line = await reader.ReadLineAsync();

            if (string.IsNullOrWhiteSpace(line)) continue;
            if (line.StartsWith("data: ")) line = line.Substring(6);
            if (line == "[DONE]") break;

            var chunk = JsonSerializer.Deserialize<StreamingChunk>(line);
            var textContent = chunk?.choices[0]?.delta?.content;

            if (!string.IsNullOrEmpty(textContent)) {
                yield return textContent;
            }
        }
    }


    public void ClearSystemPrompt() {
        _systemPrompt = null;
    }

    public void SetSystemPrompt(string prompt) {
        _systemPrompt = new ChatMessage { role = "system", content = prompt };
    }
}