package com.kamco.cd.kamcoback.inference.service;

import com.kamco.cd.kamcoback.inference.dto.InferenceResultDto;
import com.kamco.cd.kamcoback.inference.dto.InferenceResultDto.Dashboard;
import com.kamco.cd.kamcoback.inference.dto.InferenceResultDto.Detail;
import com.kamco.cd.kamcoback.inference.dto.InferenceResultDto.MapSheet;
import com.kamco.cd.kamcoback.postgres.core.InferenceResultCoreService;
import jakarta.validation.constraints.NotNull;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class InferenceResultService {

  private final InferenceResultCoreService inferenceResultCoreService;

  /**
   * 추론관리 > 분석결과 목록 조회
   *
   * @param searchReq
   * @return
   */
  public Page<InferenceResultDto.AnalResList> getInferenceResultList(
      InferenceResultDto.SearchReq searchReq) {
    return inferenceResultCoreService.getInferenceResultList(searchReq);
  }

  /**
   * 분석결과 요약정보
   *
   * @param id
   * @return
   */
  public InferenceResultDto.AnalResSummary getInferenceResultSummary(Long id) {
    return inferenceResultCoreService.getInferenceResultSummary(id);
  }

  /**
   * 분석결과 상세 class name별 탐지 개수
   *
   * @param id
   * @return
   */
  public List<Dashboard> getDashboard(Long id) {
    return inferenceResultCoreService.getDashboard(id);
  }

  /**
   * 분석결과 상세 목록
   *
   * @param searchGeoReq
   * @return
   */
  public Page<InferenceResultDto.Geom> getInferenceResultGeomList(
      Long id, InferenceResultDto.SearchGeoReq searchGeoReq) {
    return inferenceResultCoreService.getInferenceResultGeomList(id, searchGeoReq);
  }

  /**
   * 분석결과 상세 목록
   *
   * @param searchReq
   * @return
   */
  public Page<InferenceResultDto.DetailListEntity> listInferenceResultWithGeom(
      @NotNull Long id, InferenceResultDto.SearchGeoReq searchReq) {

    return inferenceResultCoreService.listInferenceResultWithGeom(id, searchReq);
  }

  /**
   * 분석결과 상제 정보 Summary, DashBoard
   *
   * @param id
   * @return
   */
  public Detail getDetail(Long id) {
    // summary
    InferenceResultDto.AnalResSummary summary = this.getInferenceResultSummary(id);

    // Dashboard
    List<Dashboard> dashboards = this.getDashboard(id);

    // 전체 탐지건수
    Long totalCnt = dashboards.stream().mapToLong(Dashboard::getClassAfterCnt).sum();

    return new Detail(summary, dashboards, totalCnt);
  }

  /**
   * 추론된 5000:1 도엽 목록
   *
   * @param id
   * @return
   */
  public List<String> getSheets(Long id) {
    return inferenceResultCoreService.getSheets(id).stream().map(String::valueOf).toList();
  }

  public List<MapSheet> listGetScenes5k(Long id) {
    return inferenceResultCoreService.listGetScenes5k(id);
  }
}
