package com.unicorn.hgzero.meeting.infra.client;

import com.unicorn.hgzero.meeting.infra.dto.ai.ConsolidateRequest;
import com.unicorn.hgzero.meeting.infra.dto.ai.ConsolidateResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.time.Duration;

/**
 * AI Service 호출 클라이언트
 */
@Slf4j
@Component
public class AIServiceClient {

    private final RestTemplate restTemplate;
    private final String aiServiceUrl;

    public AIServiceClient(
            RestTemplateBuilder restTemplateBuilder,
            @Value("${ai.service.url:http://localhost:8087}") String aiServiceUrl,
            @Value("${ai.service.timeout:30000}") int timeout
    ) {
        this.restTemplate = restTemplateBuilder
                .setConnectTimeout(Duration.ofMillis(timeout))
                .setReadTimeout(Duration.ofMillis(timeout))
                .build();
        this.aiServiceUrl = aiServiceUrl;
    }

    /**
     * 회의록 통합 요약 API 호출
     *
     * @param request 통합 요약 요청
     * @return 통합 요약 응답
     */
    public ConsolidateResponse consolidateMinutes(ConsolidateRequest request) {
        log.info("AI Service 호출 - 회의록 통합 요약: {}", request.getMeetingId());

        try {
            String url = aiServiceUrl + "/api/transcripts/consolidate";

            // HTTP 헤더 설정
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            // HTTP 요청 생성
            HttpEntity<ConsolidateRequest> httpEntity = new HttpEntity<>(request, headers);

            // API 호출
            ResponseEntity<ConsolidateResponse> response = restTemplate.postForEntity(
                    url,
                    httpEntity,
                    ConsolidateResponse.class
            );

            ConsolidateResponse result = response.getBody();

            if (result == null) {
                throw new RuntimeException("AI Service 응답이 비어있습니다");
            }

            log.info("AI Service 응답 수신 완료 - 안건 수: {}", result.getAgendaSummaries().size());

            return result;

        } catch (Exception e) {
            log.error("AI Service 호출 실패: {}", e.getMessage(), e);
            throw new RuntimeException("AI 회의록 통합 처리 중 오류가 발생했습니다: " + e.getMessage(), e);
        }
    }
}
