package com.gnx.telemedicine.health;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * Custom health indicator for Google Gemini API connectivity.
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class GeminiApiHealthIndicator implements HealthIndicator {

    @Value("${gemini.api-key:}")
    private String apiKey;

    private static final String GEMINI_API_BASE_URL = "https://generativelanguage.googleapis.com";
    private static final int TIMEOUT_SECONDS = 5;

    @Override
    public Health health() {
        Map<String, Object> details = new HashMap<>();
        
        // Check if API key is configured
        if (apiKey == null || apiKey.isEmpty()) {
            return Health.down()
                    .withDetail("status", "DOWN")
                    .withDetail("error", "Gemini API key not configured")
                    .withDetail("service", "Google Gemini API")
                    .build();
        }
        
        try {
            // Create HTTP client with timeout
            HttpClient client = HttpClient.newBuilder()
                    .connectTimeout(Duration.ofSeconds(TIMEOUT_SECONDS))
                    .build();
            
            // Test API connectivity with a simple request
            // Note: This is a lightweight check - actual API calls would require proper request body
            String testUrl = GEMINI_API_BASE_URL + "/v1/models?key=" + apiKey;
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(testUrl))
                    .timeout(Duration.ofSeconds(TIMEOUT_SECONDS))
                    .GET()
                    .build();
            
            long startTime = System.currentTimeMillis();
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            long responseTime = System.currentTimeMillis() - startTime;
            
            details.put("status", "UP");
            details.put("service", "Google Gemini API");
            details.put("baseUrl", GEMINI_API_BASE_URL);
            details.put("responseTime", responseTime + "ms");
            details.put("httpStatus", response.statusCode());
            
            if (response.statusCode() == 200) {
                return Health.up()
                        .withDetails(details)
                        .withDetail("connectivity", "Connected")
                        .build();
            } else if (response.statusCode() == 401 || response.statusCode() == 403) {
                return Health.down()
                        .withDetails(details)
                        .withDetail("error", "API key authentication failed")
                        .build();
            } else {
                return Health.down()
                        .withDetails(details)
                        .withDetail("error", "Unexpected response code: " + response.statusCode())
                        .build();
            }
            
        } catch (java.net.http.HttpTimeoutException e) {
            log.warn("Gemini API health check timeout: {}", e.getMessage());
            return Health.down()
                    .withDetails(details)
                    .withDetail("status", "DOWN")
                    .withDetail("error", "Connection timeout: " + e.getMessage())
                    .withDetail("service", "Google Gemini API")
                    .withException(e)
                    .build();
        } catch (Exception e) {
            log.error("Gemini API health check failed", e);
            return Health.down()
                    .withDetails(details)
                    .withDetail("status", "DOWN")
                    .withDetail("error", "Cannot connect to Gemini API: " + e.getMessage())
                    .withDetail("service", "Google Gemini API")
                    .withException(e)
                    .build();
        }
    }
}

