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.List;
import java.util.Map;

/**
 * 분석 데이터 API — group_polygon_snapshots / gear_correlation_scores 직접 DB 조회
 * + signal-batch 선박 항적 프록시.
 */

/**
 * 분석 데이터 API — group_polygon_snapshots / gear_correlation_scores 직접 DB 조회.
 *
 * 라우팅:
 *   GET /api/vessel-analysis/groups               → 어구/선단 그룹 + parentResolution 합성
 *   GET /api/vessel-analysis/groups/{key}/detail  → 단일 그룹 상세 + 24h 이력
 *   GET /api/vessel-analysis/groups/{key}/correlations → 상관관계 점수
 *
 * 권한: detection:gear-detection (READ)
 */
@Slf4j
@RestController
@RequestMapping("/api/vessel-analysis")
@RequiredArgsConstructor
public class VesselAnalysisProxyController {

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

    private RestClient signalBatchClient;

    @PostConstruct
    void init() {
        String sbUrl = appProperties.getSignalBatch().getBaseUrl();
        signalBatchClient = restClientBuilder
                .baseUrl(sbUrl != null && !sbUrl.isBlank() ? sbUrl : "http://192.168.1.18:18090/signal-batch")
                .defaultHeader("Accept", "application/json")
                .build();
    }

    @GetMapping
    @RequirePermission(resource = "detection:dark-vessel", operation = "READ")
    public ResponseEntity<?> getVesselAnalysis() {
        // vessel_analysis_results 직접 조회는 /api/analysis/vessels 를 사용.
        // 이 엔드포인트는 하위 호환을 위해 빈 구조 반환.
        return ResponseEntity.ok(Map.of(
                "serviceAvailable", true,
                "message", "vessel_analysis_results는 /api/analysis/vessels 에서 제공됩니다.",
                "items", List.of(),
                "stats", Map.of(),
                "count", 0
        ));
    }

    /**
     * 그룹 목록 + 자체 DB의 parentResolution 합성.
     */
    @GetMapping("/groups")
    @RequirePermission(resource = "detection:gear-detection", operation = "READ")
    public ResponseEntity<?> getGroups(
            @org.springframework.web.bind.annotation.RequestParam(required = false) String groupType
    ) {
        Map<String, Object> result = groupService.getGroups(groupType);
        return ResponseEntity.ok(result);
    }

    @GetMapping("/groups/{groupKey}/detail")
    @RequirePermission(resource = "detection:gear-detection", operation = "READ")
    public ResponseEntity<?> getGroupDetail(@PathVariable String groupKey) {
        Map<String, Object> result = groupService.getGroupDetail(groupKey);
        return ResponseEntity.ok(result);
    }

    @GetMapping("/groups/{groupKey}/correlations")
    @RequirePermission(resource = "detection:gear-detection", operation = "READ")
    public ResponseEntity<?> getGroupCorrelations(
            @PathVariable String groupKey,
            @RequestParam(required = false) Double minScore
    ) {
        Map<String, Object> result = groupService.getGroupCorrelations(groupKey, minScore);
        return ResponseEntity.ok(result);
    }

    /**
     * 후보 상세 raw metrics (최근 20건 관측 이력).
     */
    @GetMapping("/groups/{groupKey}/candidates/{targetMmsi}/metrics")
    @RequirePermission(resource = "detection:gear-detection", operation = "READ")
    public ResponseEntity<?> getCandidateMetrics(
            @PathVariable String groupKey,
            @PathVariable String targetMmsi
    ) {
        return ResponseEntity.ok(groupService.getCandidateMetrics(groupKey, targetMmsi));
    }

    /**
     * 모선 확정/제외.
     * POST body: { "action": "confirm"|"reject", "targetMmsi": "...", "comment": "..." }
     */
    @PostMapping("/groups/{groupKey}/resolve")
    @RequirePermission(resource = "detection:gear-detection", operation = "UPDATE")
    public ResponseEntity<?> resolveParent(
            @PathVariable String groupKey,
            @RequestBody Map<String, String> body
    ) {
        String action = body.getOrDefault("action", "");
        String targetMmsi = body.getOrDefault("targetMmsi", "");
        String comment = body.getOrDefault("comment", "");
        return ResponseEntity.ok(groupService.resolveParent(groupKey, action, targetMmsi, comment));
    }

    /**
     * 선박 항적 일괄 조회 (signal-batch 프록시).
     * POST /api/vessel-analysis/tracks → signal-batch /api/v2/tracks/vessels
     */
    @PostMapping("/tracks")
    @RequirePermission(resource = "detection:gear-detection", operation = "READ")
    public ResponseEntity<?> vesselTracks(@RequestBody Map<String, Object> body) {
        try {
            String json = signalBatchClient.post()
                    .uri("/api/v2/tracks/vessels")
                    .body(body)
                    .retrieve()
                    .body(String.class);
            return ResponseEntity.ok()
                    .header("Content-Type", "application/json")
                    .body(json != null ? json : "[]");
        } catch (RestClientException e) {
            log.warn("signal-batch 항적 조회 실패: {}", e.getMessage());
            return ResponseEntity.ok("[]");
        }
    }
}
