package gc.mda.kcg.domain.analysis;

import gc.mda.kcg.config.AppProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * Prediction 서비스(FastAPI) 상태/트리거 프록시
 * GET  /api/prediction/health  → {predictionBaseUrl}/health
 * GET  /api/prediction/status  → {predictionBaseUrl}/api/v1/analysis/status
 * POST /api/prediction/trigger → {predictionBaseUrl}/api/v1/analysis/trigger
 */
@Slf4j
@RestController
@RequestMapping("/api/prediction")
@RequiredArgsConstructor
public class PredictionProxyController {

    private final RestTemplate restTemplate;
    private final AppProperties appProperties;

    @GetMapping("/health")
    public ResponseEntity<Object> health() {
        String url = appProperties.getCollector().getPredictionBaseUrl() + "/health";
        return proxyGet(url);
    }

    @GetMapping("/status")
    public ResponseEntity<Object> status() {
        String url = appProperties.getCollector().getPredictionBaseUrl() + "/api/v1/analysis/status";
        return proxyGet(url);
    }

    @PostMapping("/trigger")
    public ResponseEntity<Object> trigger(@RequestBody(required = false) Object body) {
        String url = appProperties.getCollector().getPredictionBaseUrl() + "/api/v1/analysis/trigger";
        return proxyPost(url, body);
    }

    private ResponseEntity<Object> proxyGet(String url) {
        try {
            ResponseEntity<Object> upstream = restTemplate.exchange(
                    url, HttpMethod.GET, null, Object.class);
            return ResponseEntity.status(upstream.getStatusCode()).body(upstream.getBody());
        } catch (ResourceAccessException e) {
            log.warn("Prediction 서비스 접속 불가: {}", e.getMessage());
            return unreachable(e.getMessage());
        } catch (RestClientException e) {
            log.warn("Prediction 서비스 오류: {}", e.getMessage());
            return unreachable(e.getMessage());
        }
    }

    private ResponseEntity<Object> proxyPost(String url, Object body) {
        try {
            HttpEntity<Object> entity = new HttpEntity<>(body);
            ResponseEntity<Object> upstream = restTemplate.exchange(
                    url, HttpMethod.POST, entity, Object.class);
            return ResponseEntity.status(upstream.getStatusCode()).body(upstream.getBody());
        } catch (ResourceAccessException e) {
            log.warn("Prediction 서비스 접속 불가: {}", e.getMessage());
            return unreachable(e.getMessage());
        } catch (RestClientException e) {
            log.warn("Prediction 서비스 오류: {}", e.getMessage());
            return unreachable(e.getMessage());
        }
    }

    private ResponseEntity<Object> unreachable(String message) {
        return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
                .body(Map.of("status", "unreachable", "error", message != null ? message : "connection failed"));
    }
}
