package gc.mda.kcg.domain.analysis;

import gc.mda.kcg.config.AppProperties;
import gc.mda.kcg.permission.annotation.RequirePermission;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestClientException;

import java.util.Map;

/**
 * Prediction FastAPI 서비스 프록시.
 * app.prediction.base-url (기본: http://localhost:8001, 운영: http://192.168.1.19:18092)
 *
 * 엔드포인트:
 *   GET  /api/prediction/health              → FastAPI /health
 *   GET  /api/prediction/status              → FastAPI /api/v1/analysis/status
 *   POST /api/prediction/trigger             → FastAPI /api/v1/analysis/trigger
 *   POST /api/prediction/chat                → stub (Phase 9)
 *   GET  /api/prediction/groups/{key}/history   → FastAPI /api/v1/groups/{key}/history?hours=
 *   GET  /api/prediction/correlation/{key}/tracks → FastAPI /api/v1/correlation/{key}/tracks?hours=&min_score=
 */
@Slf4j
@RestController
@RequestMapping("/api/prediction")
@RequiredArgsConstructor
public class PredictionProxyController {

    private final AppProperties appProperties;
    private final RestClient.Builder restClientBuilder;

    private RestClient predictionClient;

    @PostConstruct
    void init() {
        String baseUrl = appProperties.getPrediction().getBaseUrl();
        predictionClient = restClientBuilder
                .baseUrl(baseUrl != null && !baseUrl.isBlank() ? baseUrl : "http://localhost:8001")
                .defaultHeader("Accept", "application/json")
                .build();
        log.info("PredictionProxyController initialized: baseUrl={}", baseUrl);
    }

    @GetMapping("/health")
    public ResponseEntity<?> health() {
        return proxyGet("/health", Map.of(
                "status", "DISCONNECTED",
                "message", "Prediction 서비스 미연결"
        ));
    }

    @GetMapping("/status")
    @RequirePermission(resource = "monitoring", operation = "READ")
    public ResponseEntity<?> status() {
        return proxyGet("/api/v1/analysis/status", Map.of("status", "DISCONNECTED"));
    }

    @PostMapping("/trigger")
    @RequirePermission(resource = "ai-operations:mlops", operation = "UPDATE")
    public ResponseEntity<?> trigger() {
        return proxyPost("/api/v1/analysis/trigger", null,
                Map.of("ok", false, "message", "Prediction 서비스 미연결"));
    }

    /**
     * AI 채팅 프록시 (POST) — Phase 9에서 실 연결.
     */
    @PostMapping("/chat")
    @RequirePermission(resource = "ai-operations:ai-assistant", operation = "READ")
    public ResponseEntity<?> chat(@RequestBody Map<String, Object> body) {
        return ResponseEntity.ok(Map.of(
                "ok", false,
                "serviceAvailable", false,
                "message", "Prediction 채팅 인증 연동 대기 중 (Phase 9에서 활성화 예정). 입력: "
                        + body.getOrDefault("message", "")
        ));
    }

    /**
     * 그룹 스냅샷 이력 (FastAPI 위임).
     */
    @GetMapping("/groups/{groupKey}/history")
    @RequirePermission(resource = "detection:gear-detection", operation = "READ")
    public ResponseEntity<?> groupHistory(
            @PathVariable String groupKey,
            @RequestParam(defaultValue = "24") int hours
    ) {
        return proxyGet("/api/v1/groups/" + groupKey + "/history?hours=" + hours,
                Map.of("serviceAvailable", false, "groupKey", groupKey));
    }

    /**
     * 상관관계 궤적 (FastAPI 위임).
     */
    @GetMapping("/correlation/{groupKey}/tracks")
    @RequirePermission(resource = "detection:gear-detection", operation = "READ")
    public ResponseEntity<?> correlationTracks(
            @PathVariable String groupKey,
            @RequestParam(defaultValue = "24") int hours,
            @RequestParam(name = "min_score", required = false) Double minScore
    ) {
        String path = "/api/v1/correlation/" + groupKey + "/tracks?hours=" + hours;
        if (minScore != null) path += "&min_score=" + minScore;
        return proxyGet(path, Map.of("serviceAvailable", false, "groupKey", groupKey));
    }

    // ── 내부 헬퍼 ──────────────────────────────────────────────────────────────

    @SuppressWarnings("unchecked")
    private ResponseEntity<?> proxyGet(String path, Map<String, Object> fallback) {
        try {
            Map<String, Object> body = predictionClient.get()
                    .uri(path)
                    .retrieve()
                    .body(Map.class);
            return ResponseEntity.ok(body != null ? body : fallback);
        } catch (RestClientException e) {
            log.debug("Prediction 호출 실패 GET {}: {}", path, e.getMessage());
            return ResponseEntity.ok(fallback);
        }
    }

    @SuppressWarnings("unchecked")
    private ResponseEntity<?> proxyPost(String path, Object requestBody, Map<String, Object> fallback) {
        try {
            var spec = predictionClient.post().uri(path);
            Map<String, Object> body;
            if (requestBody != null) {
                body = spec.body(requestBody).retrieve().body(Map.class);
            } else {
                body = spec.retrieve().body(Map.class);
            }
            return ResponseEntity.ok(body != null ? body : fallback);
        } catch (RestClientException e) {
            log.debug("Prediction 호출 실패 POST {}: {}", path, e.getMessage());
            return ResponseEntity.ok(fallback);
        }
    }
}
