package incheon.sgp.ipd.llm.service.impl;

import incheon.sgp.ipd.llm.service.LlmService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Service("llmService")
@Slf4j
public class LlmServiceImpl implements LlmService {

	// 정식 서비스 시 아래와 같이 LLM 서버 URL이 변경되어야 합니다.
	// http://all4solution.iptime.org:14142 (연구소 LLM 서버) => http://27.96.155.156 (네이버 클라우드 LLM 서버)
	// 현재는 인천시 정식 서비스 도메인이 작동하지 않아 네이버 클라우드 LLM 사용 시 인천시 DT의 주소검색,POI 검색 기능이 포함하는 서비스에 대해 일부 기능이 제한됩니다.(26.01.13)
    @Value("${llm.server.url:http://27.96.155.156}")
    private String llmServerUrl;

    @Value("${llm.server.timeout:300000}")
    private int timeout;

    @Autowired private RestTemplate restTemplate;


    @Override
    @SuppressWarnings("unchecked")
    public Map<String, Object> chat(Map<String, Object> request) throws Exception {
        String url = llmServerUrl + "/api/v1/chat/complete";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(request, headers);

        log.debug("LLM 서버 요청: {}", url);

        Map<String, Object> response = restTemplate.postForObject(url, entity, Map.class);

        log.debug("LLM 서버 응답: {}", response);

        return response;
    }
}
