package com.kamco.cd.training.model.service;

import com.kamco.cd.training.common.dto.HyperParam;
import com.kamco.cd.training.common.enums.HyperParamSelectType;
import com.kamco.cd.training.common.enums.ModelType;
import com.kamco.cd.training.common.enums.TrainType;
import com.kamco.cd.training.common.exception.CustomApiException;
import com.kamco.cd.training.dataset.dto.DatasetDto.DatasetReq;
import com.kamco.cd.training.dataset.dto.DatasetDto.SelectDataSet;
import com.kamco.cd.training.hyperparam.dto.HyperParamDto;
import com.kamco.cd.training.model.dto.ModelConfigDto;
import com.kamco.cd.training.model.dto.ModelTrainMngDto;
import com.kamco.cd.training.model.dto.ModelTrainMngDto.SearchReq;
import com.kamco.cd.training.postgres.core.HyperParamCoreService;
import com.kamco.cd.training.postgres.core.ModelTrainMngCoreService;
import com.kamco.cd.training.train.service.TrainJobService;
import java.util.List;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

  private final ModelTrainMngCoreService modelTrainMngCoreService;
  private final HyperParamCoreService hyperParamCoreService;
  private final TrainJobService trainJobService;

  /**
   * 모델학습 조회
   *
   * @param searchReq 검색 조건
   * @return 페이징 처리된 모델 목록
   */
  public Page<ModelTrainMngDto.ListDto> getModelList(SearchReq searchReq) {
    return modelTrainMngCoreService.findByModelList(searchReq);
  }

  /**
   * 모델학습 삭제
   *
   * @param uuid
   */
  @Transactional
  public void deleteModelTrain(UUID uuid) {
    modelTrainMngCoreService.deleteModel(uuid);
  }

  /**
   * 모델학습 등록
   *
   * @param req
   * @return
   */
  @Transactional
  public UUID createModelTrain(ModelTrainMngDto.AddReq req) {
    HyperParam hyperParam = req.getHyperParam();
    HyperParamDto.Basic hyper = new HyperParamDto.Basic();

    // 전이 학습은 모델 선택 필수
    if (TrainType.TRANSFER.getId().equals(req.getTrainType())) {
      if (req.getBeforeModelId() == null) {
        throw new CustomApiException("BAD_REQUEST", HttpStatus.BAD_REQUEST, "모델을 선택해 주세요.");
      }
    }

    // 하이파라미터 신규저장
    if (HyperParamSelectType.NEW.getId().equals(req.getHyperParamType())) {
      // 하이퍼파라미터 등록
      hyper = hyperParamCoreService.createHyperParam(hyperParam);
      req.setHyperUuid(hyper.getUuid());
    }

    // 모델학습 테이블 저장
    ModelTrainMngDto.Basic modelDto = modelTrainMngCoreService.saveModel(req);

    Long modelId = modelDto.getId();
    UUID modelUuid = modelDto.getUuid();

    // 모델학습 데이터셋 저장
    modelTrainMngCoreService.saveModelDataset(modelId, req);

    // 모델 데이터셋 mapping 저장
    modelTrainMngCoreService.saveModelDatasetMap(
        modelId, req.getTrainingDataset().getDatasetList());

    // 모델 config 저장
    modelTrainMngCoreService.saveModelConfig(modelId, req.getModelConfig());

    // 데이터셋 임시파일 생성
    trainJobService.createTmpFile(modelUuid);
    return modelUuid;
  }

  /**
   * 모델학습 모델학습 uuid config정보 조회
   *
   * @param uuid 모델학습 uuid
   * @return
   */
  public ModelConfigDto.Basic getModelConfigByModelId(UUID uuid) {
    return modelTrainMngCoreService.findModelConfigByModelId(uuid);
  }

  /**
   * 모델별 데이터셋 목록 조회
   *
   * @param req
   * @return
   */
  public List<SelectDataSet> getDatasetSelectList(DatasetReq req) {
    if (req.getModelNo().equals(ModelType.G1.getId())) {
      return modelTrainMngCoreService.getDatasetSelectG1List(req);
    } else {
      return modelTrainMngCoreService.getDatasetSelectG2G3List(req);
    }
  }

  public Long findModelStep1InProgressCnt() {
    return modelTrainMngCoreService.findModelStep1InProgressCnt();
  }
}
