package com.developx.szpitale.ingest;

import com.developx.szpitale.ingest.normalize.Deduplicator;
import com.developx.szpitale.ingest.source.MarkdownRegistrySource;
import com.developx.szpitale.ingest.source.VoivodeshipSource;
import com.developx.szpitale.model.RawHospitalRecord;

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

public class IngestCommand {

    public String ingest(String voivodeship, String source, String outDir, boolean split) {
        if (!"markdown".equals(source)) {
            return "Error: Only 'markdown' source is currently supported.";
        }

        Path outputDir = Path.of(outDir).toAbsolutePath().normalize();
        Path researchDir = Path.of("data").toAbsolutePath().normalize();

        List<VoivodeshipSource> sources = MarkdownRegistrySource.discoverAllSources(researchDir);
        if (sources.isEmpty()) {
            return "Error: No research-*.{md,markdown} files found in data/ directory.";
        }

        if (!"all".equals(voivodeship)) {
            String target = voivodeship.toLowerCase();
            sources = sources.stream()
                    .filter(s -> s.voivodeship().equals(target))
                    .collect(Collectors.toList());
            if (sources.isEmpty()) {
                return "Warning: No source found for voivodeship: " + voivodeship;
            }
        }

        IngestResults totalResults = new IngestResults();
        CanonicalWriter writer = new CanonicalWriter();

        for (VoivodeshipSource src : sources) {
            System.out.println("\nProcessing voivodeship: " + src.voivodeship());
            List<RawHospitalRecord> records = src.fetch();
            System.out.println("  Found " + records.size() + " hospital records");

            IngestResults results = new IngestResults();
            try {
                writer.write(outputDir, records, src.voivodeship(), results);
                System.out.println("  Written: " + outputDir.resolve("canonical").resolve(src.voivodeship() + ".json"));
            } catch (IOException e) {
                System.err.println("  Error writing: " + e.getMessage());
            }
            totalResults.addHospitals(results.getHospitalCount());
            totalResults.addPeople(results.getPersonCount());
            totalResults.addRoles(results.getRoleCount());
            totalResults.addAffiliations(results.getAffiliationCount());
        }

        try {
            writeIngestReport(outputDir, totalResults, sources);
        } catch (IOException e) {
            System.err.println("Error writing ingest report: " + e.getMessage());
        }

        return totalResults.toString();
    }

    private void writeIngestReport(Path outputDir, IngestResults results, List<VoivodeshipSource> sources) throws IOException {
        Path reportPath = outputDir.resolve("ingest-report.json");
        String report = "{" +
                "\"schemaVersion\":\"1.0\"," +
                "\"generatedAt\":\"" + java.time.LocalDateTime.now() + "\"," +
                "\"voivodeshipsProcessed\":" + sources.size() + "," +
                "\"hospitals\":" + results.getHospitalCount() + "," +
                "\"people\":" + results.getPersonCount() + "," +
                "\"roles\":" + results.getRoleCount() + "," +
                "\"affiliations\":" + results.getAffiliationCount() + "," +
                "\"gaps\":" + results.getGapCount() +
                "}";
        Files.writeString(reportPath, report);
        System.out.println("\nIngest report written to: " + reportPath);
    }
}
