package de.assecutor.votianlt.ai.config;

import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;

/**
 * Configuration for LLM integration via LM Studio.
 * LM Studio provides an OpenAI-compatible API.
 */
@Configuration
@Slf4j
public class LlmConfig {

    @Value("${spring.ai.openai.base-url:http://192.168.180.10:1234}")
    private String baseUrl;

    @Value("${spring.ai.openai.chat.options.model:local-model}")
    private String model;

    @PostConstruct
    public void logConfig() {
        log.info("=== LLM Configuration ===");
        log.info("Base URL: {}", baseUrl);
        log.info("Model: {}", model);
        testConnection();
    }

    private void testConnection() {
        log.info("Testing LLM connection to: {}", baseUrl);

        // Test 1: Basic connectivity
        testEndpoint(baseUrl + "/v1/models", "GET", null);

        // Test 2: Chat completions endpoint WITHOUT streaming (POST with minimal payload)
        String testPayload = "{\"model\":\"" + model + "\",\"messages\":[{\"role\":\"user\",\"content\":\"ping\"}],\"max_tokens\":1,\"stream\":false}";
        log.info("Test payload (stream=false): {}", testPayload);
        testEndpoint(baseUrl + "/v1/chat/completions", "POST", testPayload);

        // Test 3: Chat completions WITH streaming to compare behavior
        String streamPayload = "{\"model\":\"" + model + "\",\"messages\":[{\"role\":\"user\",\"content\":\"ping\"}],\"max_tokens\":1,\"stream\":true}";
        log.info("Test payload (stream=true): {}", streamPayload);
        testEndpoint(baseUrl + "/v1/chat/completions", "POST", streamPayload);
    }

    private void testEndpoint(String endpoint, String method, String payload) {
        try {
            log.info("Testing endpoint: {} {}", method, endpoint);
            URL url = URI.create(endpoint).toURL();
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod(method);
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(10000);

            if (payload != null) {
                connection.setDoOutput(true);
                connection.setRequestProperty("Content-Type", "application/json");
                try (var os = connection.getOutputStream()) {
                    os.write(payload.getBytes());
                }
            }

            int responseCode = connection.getResponseCode();
            String responseMessage = connection.getResponseMessage();

            if (responseCode >= 200 && responseCode < 300) {
                log.info("  -> SUCCESS (HTTP {} {})", responseCode, responseMessage);
            } else {
                // Read error body
                String errorBody = "";
                try (var is = connection.getErrorStream()) {
                    if (is != null) {
                        errorBody = new String(is.readAllBytes());
                    }
                }
                log.warn("  -> HTTP {} {} - {}", responseCode, responseMessage, errorBody);
            }
            connection.disconnect();
        } catch (java.net.ConnectException e) {
            log.error("  -> FAILED - Connection refused: {}", e.getMessage());
        } catch (java.net.SocketTimeoutException e) {
            log.error("  -> FAILED - Timeout: {}", e.getMessage());
        } catch (java.net.UnknownHostException e) {
            log.error("  -> FAILED - Unknown host: {}", e.getMessage());
        } catch (Exception e) {
            log.error("  -> FAILED: {} - {}", e.getClass().getSimpleName(), e.getMessage());
        }
    }

    public String getBaseUrl() {
        return baseUrl;
    }

    public String getModel() {
        return model;
    }
}
