package com.kamco.cd.training.dataset;

import com.kamco.cd.training.config.api.ApiResponseDto;
import com.kamco.cd.training.dataset.dto.DatasetDto;
import com.kamco.cd.training.dataset.dto.DatasetDto.AddDeliveriesReq;
import com.kamco.cd.training.dataset.dto.DatasetObjDto;
import com.kamco.cd.training.dataset.dto.DatasetObjDto.DatasetClass;
import com.kamco.cd.training.dataset.dto.DatasetObjDto.DatasetStorage;
import com.kamco.cd.training.dataset.service.DatasetAsyncService;
import com.kamco.cd.training.dataset.service.DatasetService;
import com.kamco.cd.training.model.dto.FileDto.FoldersDto;
import com.kamco.cd.training.model.dto.FileDto.SrchFoldersDto;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import java.io.IOException;
import java.nio.file.FileStore;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import org.springframework.core.io.Resource;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@Tag(name = "학습데이터 관리", description = "어드민 홈 > 학습데이터관리 > 전체데이터 API")
@RestController
@RequestMapping("/api/datasets")
@RequiredArgsConstructor
public class DatasetApiController {

  private final DatasetService datasetService;
  private final DatasetAsyncService datasetAsyncService;

  @Operation(summary = "학습데이터 관리 목록 조회", description = "학습데이터 목록을 조회합니다.")
  @ApiResponses(
      value = {
        @ApiResponse(
            responseCode = "200",
            description = "조회 성공",
            content =
                @Content(
                    mediaType = "application/json",
                    schema = @Schema(implementation = Page.class))),
        @ApiResponse(responseCode = "400", description = "잘못된 검색 조건", content = @Content),
        @ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
      })
  @GetMapping
  public ApiResponseDto<Page<DatasetDto.Basic>> searchDatasets(
      @Parameter(
              description = "구분",
              example = "",
              schema = @Schema(allowableValues = {"DELIVER", "PRODUCTION"}))
          @RequestParam(required = false)
          String dataType,
      @Parameter(description = "제목", example = "") @RequestParam(required = false) String title,
      @Parameter(description = "페이지 번호 (0부터 시작)", example = "0") @RequestParam(defaultValue = "0")
          int page,
      @Parameter(description = "페이지 크기", example = "20") @RequestParam(defaultValue = "20")
          int size) {
    DatasetDto.SearchReq searchReq = new DatasetDto.SearchReq();
    searchReq.setTitle(title);
    searchReq.setDataType(dataType);
    searchReq.setPage(page);
    searchReq.setSize(size);
    return ApiResponseDto.ok(datasetService.searchDatasets(searchReq));
  }

  @Operation(summary = "학습데이터관리 상세 조회", description = "학습데이터관리 상세 정보를 조회합니다.")
  @ApiResponses(
      value = {
        @ApiResponse(
            responseCode = "200",
            description = "조회 성공",
            content =
                @Content(
                    mediaType = "application/json",
                    schema = @Schema(implementation = DatasetDto.Basic.class))),
        @ApiResponse(responseCode = "404", description = "데이터셋을 찾을 수 없음", content = @Content),
        @ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
      })
  @GetMapping("/{uuid}")
  public ApiResponseDto<DatasetDto.Basic> getDatasetDetail(@PathVariable UUID uuid) {
    return ApiResponseDto.ok(datasetService.getDatasetDetail(uuid));
  }

  @Operation(summary = "학습데이터 수정", description = "학습데이터 제목, 메모 수정")
  @ApiResponses(
      value = {
        @ApiResponse(
            responseCode = "200",
            description = "수정 성공",
            content =
                @Content(
                    mediaType = "application/json",
                    schema = @Schema(implementation = Long.class))),
        @ApiResponse(responseCode = "400", description = "잘못된 요청 데이터", content = @Content),
        @ApiResponse(responseCode = "404", description = "데이터셋을 찾을 수 없음", content = @Content),
        @ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
      })
  @PutMapping("/{uuid}")
  public ApiResponseDto<UUID> updateDataset(
      @PathVariable UUID uuid, @RequestBody DatasetDto.UpdateReq updateReq) {
    datasetService.updateDataset(uuid, updateReq);
    return ApiResponseDto.ok(uuid);
  }

  @Operation(summary = "학습데이터 삭제", description = "학습데이터를 삭제합니다.(납품 데이터는 삭제 불가)")
  @ApiResponses(
      value = {
        @ApiResponse(responseCode = "201", description = "삭제 성공", content = @Content),
        @ApiResponse(responseCode = "400", description = "잘못된 요청", content = @Content),
        @ApiResponse(responseCode = "404", description = "데이터셋을 찾을 수 없음", content = @Content),
        @ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
      })
  @DeleteMapping("/{uuid}")
  public ApiResponseDto<UUID> deleteDatasets(@PathVariable UUID uuid) {

    datasetService.deleteDatasets(uuid);
    return ApiResponseDto.ok(uuid);
  }

  @Operation(summary = "학습데이터 관리 목록 조회", description = "학습데이터 목록을 조회합니다.")
  @ApiResponses(
      value = {
        @ApiResponse(
            responseCode = "200",
            description = "조회 성공",
            content =
                @Content(
                    mediaType = "application/json",
                    schema = @Schema(implementation = Page.class))),
        @ApiResponse(responseCode = "400", description = "잘못된 검색 조건", content = @Content),
        @ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
      })
  @GetMapping("/obj-list")
  public ApiResponseDto<Page<DatasetObjDto.Basic>> searchDatasetObjectList(
      @Parameter(description = "회차 uuid", example = "e9a6774b-4f81-4402-b080-51d27fac1f01")
          @RequestParam(required = true)
          UUID uuid,
      @Parameter(description = "비교년도분류", example = "container") @RequestParam(required = false)
          String compareClassCd,
      @Parameter(description = "기준년도분류", example = "waste") @RequestParam(required = false)
          String targetClassCd,
      @Parameter(description = "도엽번호", example = "36713060") @RequestParam(required = false)
          String mapSheetNum,
      @RequestParam(defaultValue = "0") int page,
      @RequestParam(defaultValue = "20") int size) {
    DatasetObjDto.SearchReq searchReq = new DatasetObjDto.SearchReq();
    searchReq.setUuid(uuid);
    searchReq.setCompareClassCd(compareClassCd);
    searchReq.setTargetClassCd(targetClassCd);
    searchReq.setMapSheetNum(mapSheetNum);
    searchReq.setPage(page);
    searchReq.setSize(size);
    return ApiResponseDto.ok(datasetService.searchDatasetObjectList(searchReq));
  }

  @Operation(summary = "학습데이터 관리 obj 삭제", description = "학습데이터 관리 obj 삭제 API")
  @ApiResponses(
      value = {
        @ApiResponse(
            responseCode = "200",
            description = "삭제 성공",
            content =
                @Content(
                    mediaType = "application/json",
                    schema = @Schema(implementation = Page.class))),
        @ApiResponse(responseCode = "400", description = "잘못된 검색 조건", content = @Content),
        @ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
      })
  @DeleteMapping("/obj/{uuid}")
  public ApiResponseDto<UUID> deleteDatasetObjByUuid(@PathVariable UUID uuid) {
    return ApiResponseDto.ok(datasetService.deleteDatasetObjByUuid(uuid));
  }

  @Operation(summary = "학습데이터 결과 class 조회", description = "학습데이터 결과 class 조회 API")
  @ApiResponses(
      value = {
        @ApiResponse(
            responseCode = "200",
            description = "조회 성공",
            content =
                @Content(
                    mediaType = "application/json",
                    schema = @Schema(implementation = Page.class))),
        @ApiResponse(responseCode = "400", description = "잘못된 검색 조건", content = @Content),
        @ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
      })
  @GetMapping("/class/{uuid}")
  public ApiResponseDto<List<DatasetClass>> getDatasetObjByUuid(
      @Parameter(description = "dataset uuid", example = "e1416f32-769f-495c-a883-3ebfacef4bac")
          @PathVariable
          UUID uuid,
      @Parameter(description = "compare, target", example = "compare") @RequestParam String type) {
    return ApiResponseDto.ok(datasetService.getDatasetObjByUuid(uuid, type));
  }

  @Operation(summary = "남은 저장공간 조회", description = "남은 저장공간 조회 API")
  @ApiResponses(
      value = {
        @ApiResponse(
            responseCode = "200",
            description = "조회 성공",
            content =
                @Content(
                    mediaType = "application/json",
                    schema = @Schema(implementation = Page.class))),
        @ApiResponse(responseCode = "404", description = "저장 공간 조회 오류", content = @Content),
        @ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
      })
  @GetMapping("/usable-bytes")
  public ApiResponseDto<DatasetStorage> getUsableBytes() throws IOException {
    FileStore store = Files.getFileStore(Path.of("."));

    long usable = store.getUsableSpace();
    DatasetStorage storage = new DatasetStorage();
    storage.setUsableBytes(String.valueOf(usable));

    //    datasetService.getUsableBytes();
    return ApiResponseDto.ok(storage);
  }

  @Operation(summary = "학습데이터 zip파일 등록", description = "학습데이터 zip파일 등록 합니다.")
  @PostMapping
  public ApiResponseDto<ApiResponseDto.ResponseObj> insertDataset(
      @RequestBody @Valid DatasetDto.AddReq addReq) {

    return ApiResponseDto.okObject(datasetService.insertDataset(addReq));
  }

  @Operation(summary = "객체별 파일 Path 조회", description = "파일 Path 조회")
  @GetMapping("/files")
  public ResponseEntity<Resource> getFile(@RequestParam UUID uuid, @RequestParam String pathType)
      throws Exception {

    String path = datasetService.getFilePathByUUIDPathType(uuid, pathType);
    return datasetService.getFilePathByFile(path);
  }

  @Operation(summary = "객체별 파일 Path 조회", description = "파일 Path 조회")
  @GetMapping("/files-to86")
  public ResponseEntity<Resource> getFileTo86(
      @RequestParam UUID uuid, @RequestParam String pathType) throws Exception {

    String path = datasetService.getFilePathByUUIDPathType(uuid, pathType);
    return datasetService.getFilePathByFile(path);
  }

  @Operation(summary = "납품 폴더 조회", description = "납품 폴더 조회 API")
  @ApiResponses(
      value = {
        @ApiResponse(
            responseCode = "200",
            description = "조회 성공",
            content =
                @Content(
                    mediaType = "application/json",
                    schema = @Schema(implementation = FoldersDto.class))),
        @ApiResponse(responseCode = "404", description = "조회 오류", content = @Content),
        @ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
      })
  @PostMapping("/folder-list")
  public ApiResponseDto<FoldersDto> getDir(@RequestBody SrchFoldersDto srchDto) throws IOException {

    return ApiResponseDto.createOK(datasetService.getFolderAll(srchDto));
  }

  @Operation(summary = "납품 학습데이터셋 등록", description = "납품 학습데이터셋 등록 API")
  @ApiResponses(
      value = {
        @ApiResponse(
            responseCode = "200",
            description = "등록 성공",
            content =
                @Content(
                    mediaType = "application/json",
                    schema = @Schema(implementation = String.class))),
        @ApiResponse(responseCode = "404", description = "조회 오류", content = @Content),
        @ApiResponse(responseCode = "500", description = "서버 오류", content = @Content)
      })
  @PostMapping("/deliveries")
  public ApiResponseDto<String> insertDeliveriesDataset(@RequestBody AddDeliveriesReq req) {

    // 폴더 구조 검증
    DatasetService.validateTrainValTestDirs(req.getFilePath());
    // 파일 개수 검증
    DatasetService.validateDirFileCount(req.getFilePath());
    // 폴더명(uid)으로 등록한 건이 있는지 체크
    datasetService.validateExistsUidChk(req.getFilePath());

    datasetAsyncService.insertDeliveriesDatasetAsync(req);
    return ApiResponseDto.createOK("ok");
  }
}
