package com.developx.szpitale.load;

import org.neo4j.driver.Driver;

import java.io.IOException;
import java.nio.file.Path;

public class LoadCommand {

    private final Driver neo4jDriver;

    public LoadCommand(Driver neo4jDriver) {
        this.neo4jDriver = neo4jDriver;
    }

    public String load(String inDir, String voivodeship, boolean createSchema, boolean wipe, boolean validate) {
        try {
            if (wipe) {
                new GraphSchema(neo4jDriver).dropAll();
                System.out.println("Graph wiped.");
            }
            if (createSchema) {
                new GraphSchema(neo4jDriver).createConstraints();
                System.out.println("Schema created.");
            }

            CanonicalReader reader = new CanonicalReader();
            var datasets = reader.readAll(Path.of(inDir), voivodeship);
            if (datasets.isEmpty()) {
                return "Error: No canonical datasets found for voivodeship: " + voivodeship;
            }

            GraphLoader loader = new GraphLoader(neo4jDriver);
            GraphLoader.LoadStats stats = loader.load(datasets);
            System.out.println(stats);

            if (validate) {
                GraphValidator validator = new GraphValidator(neo4jDriver);
                GraphValidator.ValidationReport report = validator.validate();
                System.out.println(report);

                try {
                    validator.exportOverlapCsv(Path.of("overlap_report.csv"), report.overlapReport);
                } catch (IOException e) {
                    System.err.println("Error writing overlap report: " + e.getMessage());
                }
            }

            return "Load completed successfully.";
        } catch (Exception e) {
            return "Error during load: " + e.getMessage();
        }
    }
}
