package ru.first;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Comparator;

import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
import static java.util.Objects.isNull;

public class Main {

    public static final String INPUT_PATH = System.getenv("INPUT_PATH");
    public static final String OUTPUT_PATH = System.getenv("OUTPUT_PATH");
    public static final String RESULT_FILE_NAME = "data.txt";

    public static void main(String[] args) throws IOException {
        if (isNull(INPUT_PATH) || INPUT_PATH.isEmpty() || isNull(OUTPUT_PATH) || OUTPUT_PATH.isEmpty()) {
            System.out.printf("Отсутствуют переменные окружения INPUT_PATH = '%s' или OUTPUT_PATH = '%s'%n",
                    INPUT_PATH, OUTPUT_PATH);
            return;
        }
        var inputPathDir = Path.of(INPUT_PATH);
        if (!Files.exists(inputPathDir)) {
            Files.createDirectory(inputPathDir);
        }
        var inputDirectory = new File(INPUT_PATH);
        var allDirFiles = inputDirectory.listFiles();
        if (isNull(allDirFiles) || allDirFiles.length == 0) {
            System.out.println("Директория пуста");
            return;
        }
        var dirFiles = Arrays.stream(allDirFiles).filter(File::isFile).toList();
        if (dirFiles.isEmpty()) {
            System.out.println("В указанной директории нет подходящих для обработки файлов");
            return;
        }

        var shortestName = dirFiles.stream().min(Comparator.comparing(file -> file.getName().length())).get();

        var outputPathDir = Path.of(OUTPUT_PATH);
        if (!Files.exists(outputPathDir)) {
            Files.createDirectory(outputPathDir);
        }
        var resultFilePath = Path.of(OUTPUT_PATH + File.separator + RESULT_FILE_NAME);
        Files.move(Path.of(INPUT_PATH + File.separator + shortestName.getName()), resultFilePath, REPLACE_EXISTING);
    }
}