// PRE-GENERATED (design session). Talks to a local Ollama server (localhost:11434).
// Detect / list models / pull with progress. Untested here.
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

namespace DansoriEQ.App.Ai;

public sealed class OllamaService
{
    private const string Base = "http://localhost:11434";
    private readonly HttpClient _http = new() { Timeout = TimeSpan.FromMinutes(60) };

    public async Task<bool> IsRunningAsync()
    {
        try { var r = await _http.GetAsync($"{Base}/api/tags"); return r.IsSuccessStatusCode; }
        catch { return false; }
    }

    public async Task<List<string>> ListModelsAsync()
    {
        var models = new List<string>();
        try
        {
            var json = await _http.GetStringAsync($"{Base}/api/tags");
            using var doc = JsonDocument.Parse(json);
            if (doc.RootElement.TryGetProperty("models", out var arr))
                foreach (var m in arr.EnumerateArray())
                    if (m.TryGetProperty("name", out var n)) models.Add(n.GetString() ?? "");
        }
        catch { }
        return models;
    }

    public async Task PullModelAsync(string model, IProgress<double>? progress, CancellationToken ct = default)
    {
        var body = JsonSerializer.Serialize(new { name = model, stream = true });
        using var req = new HttpRequestMessage(HttpMethod.Post, $"{Base}/api/pull")
        { Content = new StringContent(body, Encoding.UTF8, "application/json") };
        using var resp = await _http.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, ct);
        resp.EnsureSuccessStatusCode();

        using var stream = await resp.Content.ReadAsStreamAsync(ct);
        using var reader = new StreamReader(stream);
        string? line;
        while ((line = await reader.ReadLineAsync()) != null)
        {
            if (string.IsNullOrWhiteSpace(line)) continue;
            try
            {
                using var doc = JsonDocument.Parse(line);
                if (doc.RootElement.TryGetProperty("total", out var tot) &&
                    doc.RootElement.TryGetProperty("completed", out var comp))
                {
                    double t = tot.GetInt64(), c = comp.GetInt64();
                    if (t > 0) progress?.Report(c / t);
                }
            }
            catch { /* non-progress status line */ }
        }
        progress?.Report(1.0);
    }
}
