package de.assecutor.votianlt.ai.config;

import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.anthropic.models.messages.MessageCountTokensParams;
import com.anthropic.models.messages.MessageTokensCount;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

/**
 * Configuration for LLM integration via the Anthropic Claude API.
 */
@Configuration
@Slf4j
public class LlmConfig {

    @Value("${app.ai.anthropic.api-key}")
    private String apiKey;

    @Value("${app.ai.anthropic.model:claude-opus-4-8}")
    private String model;

    @PostConstruct
    public void logConfig() {
        log.info("=== LLM Configuration ===");
        log.info("Provider: Anthropic Claude");
        log.info("Model: {}", model);
        log.info("API key: {}", apiKey != null && !apiKey.isBlank() ? "configured" : "NOT configured");
        testConnection();
    }

    /**
     * Validate API key and connectivity using the free count_tokens endpoint (no
     * tokens are billed).
     */
    private void testConnection() {
        if (apiKey == null || apiKey.isBlank()) {
            log.warn("Skipping Claude connection test - no API key configured");
            return;
        }
        try {
            AnthropicClient client = AnthropicOkHttpClient.builder().apiKey(apiKey).build();
            MessageTokensCount count = client.messages()
                    .countTokens(MessageCountTokensParams.builder().model(model).addUserMessage("ping").build());
            log.info("Claude connection test -> SUCCESS (count_tokens returned {} input tokens)",
                    count.inputTokens());
        } catch (Exception e) {
            log.error("Claude connection test -> FAILED: {} - {}", e.getClass().getSimpleName(), e.getMessage());
        }
    }

    public String getModel() {
        return model;
    }
}
