package kz.konturai.parser.service;

import kz.konturai.parser.dto.DeepResearchRequest;
import kz.konturai.parser.dto.DeepResearchResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import reactor.core.publisher.Mono;

import java.time.Duration;

@Service
public class DeepResearchService {

    private final WebClient webClient;

    private static final Logger log = LoggerFactory.getLogger(DeepResearchService.class);

    @Value("${deep-research.api.url:http://185.35.223.45:3051}")
    private String apiUrl;

    @Value("${deep-research.api.timeout:300000}") // Set to 0 or negative to disable timeout
    private long timeoutMs;

    public DeepResearchService() {
        this.webClient = WebClient.builder()
                .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
                .build();
    }

    /**
     * Вызывает deep-research API для генерации отчёта
     */
    public DeepResearchResponse generateReport(DeepResearchRequest request) {
        try {
            Mono<DeepResearchResponse> call = webClient.post()
                    .uri(apiUrl + "/api/research")
                    .bodyValue(request)
                    .retrieve()
                    .bodyToMono(DeepResearchResponse.class);
            if (timeoutMs > 0) {
                call = call.timeout(Duration.ofMillis(timeoutMs));
            }
            return call.block();
        } catch (WebClientResponseException e) {
            throw new RuntimeException("Deep research API error: " + e.getResponseBodyAsString(), e);
        } catch (Exception e) {
            throw new RuntimeException("Failed to call deep research API", e);
        }
    }

    /**
     * Асинхронный вызов deep-research API
     */

    public Mono<DeepResearchResponse> generateReportAsync(DeepResearchRequest request) {
        log.info("*************");
        Mono<DeepResearchResponse> temp = webClient.post()
                .uri(apiUrl + "/api/research")
                .bodyValue(request)
                .retrieve()
                .bodyToMono(DeepResearchResponse.class)
                // 👇 Log the successful response object here
                .doOnSuccess(response -> {
                    if (response != null) {
                        log.info("Deep research API response: {}", response.getLearnings());
                        log.info("Deep research API response: {}", response.getMainContent());
                        log.info("Deep research API response: {}", response.getError());
                        log.info("Deep research API response: {}", response.getStatus());
                        log.info("Deep research API response: {}", response.getVisitedUrls());
                    }
                });
        if (timeoutMs > 0) {
            temp = temp.timeout(Duration.ofMillis(timeoutMs));
        }
        temp = temp.onErrorMap(WebClientResponseException.class,
                e -> new RuntimeException("Deep research API error: " + e.getResponseBodyAsString(), e))
                .onErrorMap(Exception.class, e -> new RuntimeException("Failed to call deep research API", e));
        log.info("*************");
        return temp;
    }
}
