// PRE-GENERATED (design session). Fetches the models available to the user's ACCOUNT
// from each cloud provider's list-models API, using the stored API key. Untested here.
// Returns [] on failure (caller falls back to a static list).
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;

namespace DansoriEQ.App.Ai;

public static class CloudModelLister
{
    private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromSeconds(20) };

    public static Task<List<string>> ListAsync(string provider, string apiKey) => provider switch
    {
        "openai" => OpenAiAsync(apiKey),
        "gemini" => GeminiAsync(apiKey),
        _ => ClaudeAsync(apiKey)
    };

    private static async Task<List<string>> ClaudeAsync(string key)
    {
        var result = new List<string>();
        try
        {
            using var req = new HttpRequestMessage(HttpMethod.Get, "https://api.anthropic.com/v1/models?limit=100");
            req.Headers.Add("x-api-key", key);
            req.Headers.Add("anthropic-version", "2023-06-01");
            using var resp = await Http.SendAsync(req);
            if (!resp.IsSuccessStatusCode) return result;
            using var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync());
            if (doc.RootElement.TryGetProperty("data", out var arr))
                foreach (var m in arr.EnumerateArray())
                    if (m.TryGetProperty("id", out var id)) result.Add(id.GetString() ?? "");
        }
        catch { }
        return result;
    }

    private static async Task<List<string>> OpenAiAsync(string key)
    {
        var result = new List<string>();
        try
        {
            using var req = new HttpRequestMessage(HttpMethod.Get, "https://api.openai.com/v1/models");
            req.Headers.Add("Authorization", "Bearer " + key);
            using var resp = await Http.SendAsync(req);
            if (!resp.IsSuccessStatusCode) return result;
            using var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync());
            if (doc.RootElement.TryGetProperty("data", out var arr))
                foreach (var m in arr.EnumerateArray())
                    if (m.TryGetProperty("id", out var idEl))
                    {
                        var id = idEl.GetString() ?? "";
                        // chat-capable families only (skip embeddings/tts/whisper/image…)
                        if (id.StartsWith("gpt") || id.StartsWith("o1") || id.StartsWith("o3") ||
                            id.StartsWith("o4") || id.StartsWith("chatgpt"))
                            result.Add(id);
                    }
            result.Sort();
        }
        catch { }
        return result;
    }

    private static async Task<List<string>> GeminiAsync(string key)
    {
        var result = new List<string>();
        try
        {
            var url = "https://generativelanguage.googleapis.com/v1beta/models?key=" + Uri.EscapeDataString(key);
            using var resp = await Http.GetAsync(url);
            if (!resp.IsSuccessStatusCode) return result;
            using var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync());
            if (doc.RootElement.TryGetProperty("models", out var arr))
                foreach (var m in arr.EnumerateArray())
                {
                    var supportsGen = false;
                    if (m.TryGetProperty("supportedGenerationMethods", out var methods))
                        foreach (var meth in methods.EnumerateArray())
                            if (meth.GetString() == "generateContent") { supportsGen = true; break; }
                    if (supportsGen && m.TryGetProperty("name", out var nameEl))
                    {
                        var name = nameEl.GetString() ?? "";
                        if (name.StartsWith("models/")) name = name.Substring("models/".Length);
                        result.Add(name);
                    }
                }
        }
        catch { }
        return result;
    }
}
