// llm_anthropic — Minimal Anthropic Messages API client via cURL popen.
// No external library deps — cURL is invoked via popen/system.
// Promoted from primitives_gallery playground to registry, issue 0081.
// Used by the "Ask AI" panel in data_table. Domain: core (logic + HTTP via popen,
// no link-time HTTP library required).
#pragma once

#include "core/data_table_types.h"
#include <string>
#include <vector>

namespace llm_anthropic {

enum class OutputMode { TQL, SQL };

struct AskInput {
    std::string                                question;       // NL question
    std::string                                tql_current;    // current TQL (emitted)
    std::vector<std::string>                   col_names;      // schema input
    std::vector<data_table::ColumnType>        col_types;
    std::vector<std::string>                   joinable_names; // joinable tables
    OutputMode                                 mode = OutputMode::TQL;
    std::string                                model;          // empty -> default
    int                                        max_tokens = 8192;
};

struct AskResult {
    std::string code;     // extracted ```lua or ```sql block (no fences)
    std::string raw;      // full response text
    std::string error;    // non-empty on failure
    int         tokens_in  = 0;
    int         tokens_out = 0;
};

// Pure: builds the system prompt + user message JSON-escaped.
// Returns the full JSON body for POST to /v1/messages.
std::string build_request_body(const AskInput& in);

// Pure: extracts first ```<lang>\n...\n``` block from `raw`. lang = "lua"|"sql".
// If no fence found, returns raw stripped of leading/trailing whitespace.
std::string extract_code_block(const std::string& raw, const std::string& lang);

// Pure: extracts text from Anthropic JSON response body.
// Finds `"content":[{"type":"text","text":"..."}]` and returns the text.
std::string parse_response_text(const std::string& json_body);

// Impure: invokes cURL via popen, posts `body` to Anthropic /v1/messages,
// returns raw response body (JSON). API key resolution order:
//   1. `api_key` parameter (if non-empty)
//   2. env var FN_LLM_API_KEY
//   3. `pass anthropic/api-key | head -n1`
// If env FN_LLM_MOCK_RESPONSE is set, returns its value (test injection).
// On error, sets error_out and returns "".
std::string call_api(const std::string& body, const std::string& api_key,
                      std::string& error_out);

// Impure: orchestrator — build_request_body + call_api + parse_response_text.
// Convenience wrapper for the "Ask AI" panel.
AskResult ask(const AskInput& in, const std::string& api_key = "");

} // namespace llm_anthropic
