#include "ClaudeClient.h"
#include "WinHttpClient.h"
#include <nlohmann/json.hpp>
#include <iostream>

using json = nlohmann::json;

namespace secondvoice {

ClaudeClient::ClaudeClient(const std::string& api_key)
    : api_key_(api_key) {
}

std::optional<ClaudeResponse> ClaudeClient::translate(
    const std::string& chinese_text,
    const std::string& system_prompt,
    int max_tokens,
    float temperature) {

    // Build request JSON
    json request_json = {
        {"model", MODEL},
        {"max_tokens", max_tokens},
        {"temperature", temperature},
        {"messages", json::array({
            {
                {"role", "user"},
                {"content", "Traduis en français: " + chinese_text}
            }
        })}
    };

    if (!system_prompt.empty()) {
        request_json["system"] = system_prompt;
    }

    std::string request_body = request_json.dump();

    WinHttpClient client;
    std::map<std::string, std::string> headers = {
        {"x-api-key", api_key_},
        {"anthropic-version", API_VERSION},
        {"content-type", "application/json"}
    };

    auto response = client.postJson("api.anthropic.com", "/v1/messages", request_body, headers);

    if (!response) {
        std::cerr << "Claude API request failed" << std::endl;
        return std::nullopt;
    }

    if (response->statusCode != 200) {
        std::cerr << "Claude API error " << response->statusCode << ": " << response->body << std::endl;
        return std::nullopt;
    }

    // Parse response
    try {
        json response_json = json::parse(response->body);

        if (!response_json.contains("content") || !response_json["content"].is_array()) {
            std::cerr << "Invalid Claude API response format" << std::endl;
            return std::nullopt;
        }

        ClaudeResponse result;
        result.text = response_json["content"][0]["text"].get<std::string>();
        return result;
    } catch (const json::exception& e) {
        std::cerr << "Failed to parse Claude response: " << e.what() << std::endl;
        return std::nullopt;
    }
}

} // namespace secondvoice
