package com.developx.szpitale.load;

import com.developx.szpitale.model.CanonicalDataset;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

public class CanonicalReader {

    private final ObjectMapper objectMapper = new ObjectMapper();

    public CanonicalReader() {
        objectMapper.registerModule(new JavaTimeModule());
    }

    public List<CanonicalDataset> readAll(Path inputDir, String voivodeship) throws IOException {
        List<CanonicalDataset> datasets = new ArrayList<>();
        Path canonicalDir = inputDir.resolve("canonical").toAbsolutePath().normalize();

        if (!Files.exists(canonicalDir)) {
            System.err.println("Error: canonical directory not found: " + canonicalDir);
            return datasets;
        }

        try (var paths = Files.list(canonicalDir)) {
            paths.filter(p -> p.getFileName().toString().endsWith(".json"))
                    .filter(p -> {
                        if ("all".equalsIgnoreCase(voivodeship)) return true;
                        String base = p.getFileName().toString().replace(".json", "");
                        return base.equalsIgnoreCase(voivodeship);
                    })
                    .forEach(p -> {
                        try {
                            CanonicalDataset ds = objectMapper.readValue(p.toFile(), CanonicalDataset.class);
                            datasets.add(ds);
                        } catch (IOException e) {
                            System.err.println("Error reading " + p + ": " + e.getMessage());
                        }
                    });
        }

        return datasets;
    }

    public CanonicalDataset readSingle(Path inputDir, String voivodeship) throws IOException {
        return readAll(inputDir, voivodeship).stream().findFirst().orElse(null);
    }
}
