// PRE-GENERATED (design session). Anthropic Messages API client for the NL->EQ tool call.
// No APO needed. Won't run without a real API key, but the code path is complete.
// Dev session: verify the current model id + response shape.
using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Threading;
using System.Threading.Tasks;

namespace DansoriEQ.Core.Ai;

public sealed class ClaudeClient : IAiEqProvider
{
    private const string Endpoint = "https://api.anthropic.com/v1/messages";
    public const string DefaultModel = "claude-sonnet-4-6";   // verify current public API model id

    private readonly HttpClient _http;
    private readonly string _apiKey;
    private readonly string _model;

    public ClaudeClient(string apiKey, string? model = null, HttpClient? http = null)
    {
        _apiKey = apiKey;
        _model = model ?? DefaultModel;
        _http = http ?? new HttpClient();
    }

    public async Task<EqDelta> RequestEqAsync(string headphoneName, string type, string currentEqText,
                                              string userRequest, CancellationToken ct = default)
    {
        var toolSchema = JsonNode.Parse(EqPromptBuilder.ToolInputSchemaJson)!;
        var body = new JsonObject
        {
            ["model"] = _model,
            ["max_tokens"] = 1024,
            ["system"] = EqPromptBuilder.SystemPrompt,
            ["tools"] = new JsonArray(new JsonObject
            {
                ["name"] = EqPromptBuilder.ToolName,
                ["description"] = "Set the parametric equalizer bands and preamp.",
                ["input_schema"] = toolSchema
            }),
            ["tool_choice"] = new JsonObject { ["type"] = "tool", ["name"] = EqPromptBuilder.ToolName },
            ["messages"] = new JsonArray(new JsonObject
            {
                ["role"] = "user",
                ["content"] = EqPromptBuilder.BuildUserContext(headphoneName, type, currentEqText, userRequest)
            })
        };

        using var req = new HttpRequestMessage(HttpMethod.Post, Endpoint);
        req.Headers.Add("x-api-key", _apiKey);
        req.Headers.Add("anthropic-version", "2023-06-01");
        req.Content = new StringContent(body.ToJsonString(), Encoding.UTF8, "application/json");

        using var resp = await _http.SendAsync(req, ct).ConfigureAwait(false);
        var json = await resp.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
        if (!resp.IsSuccessStatusCode)
            throw new InvalidOperationException($"AI 요청 실패 ({(int)resp.StatusCode}): {json}");

        using var doc = JsonDocument.Parse(json);
        foreach (var block in doc.RootElement.GetProperty("content").EnumerateArray())
        {
            if (block.TryGetProperty("type", out var t) && t.GetString() == "tool_use")
                return EqDeltaParser.FromJson(block.GetProperty("input"));
        }
        throw new InvalidOperationException("AI 응답에 EQ 도구 호출이 없습니다.");
    }

}
