package de.roko.genalogy.downloader.archion;

import de.roko.genalogy.downloader.archiv.Archiv;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

public class ArchionArchiveToCSV {


    private static final String CSV_FILE = "archive.csv";


    public static void writeArchionArchiveToCSV(Elements stateDivs) {
       Map<String, Archiv> archiveMap = readCsvAsMap(CSV_FILE);

        int updated = 0;
        int added = 0;

        for (Element stateDiv : stateDivs) {
            String bundesland = stateDiv.selectFirst("a.h6.text-muted").text().trim();
            Elements archiveLinks = stateDiv.select("ul > li > a");

            for (Element link : archiveLinks) {
                String archivname = link.text().trim();
                String href = "https://www.archion.de" + link.attr("href").trim();

                String key = bundesland + ";" + archivname;
                if (archiveMap.containsKey(key)) {
                    Archiv existing = archiveMap.get(key);
                    if (!existing.link.equals(href)) {
                        existing.link = href; // Link aktualisieren
                        updated++;
                    }
                } else {
                    archiveMap.put(key, new Archiv(bundesland, archivname, href));
                    added++;
                }
            }
        }

        // Sortieren nach Bundesland > Archiv
        List<Archiv> sorted = new ArrayList<>(archiveMap.values());
        sorted.sort(Comparator.comparing((Archiv e) -> e.bundesland)
                .thenComparing(e -> e.archivname));

        // Schreiben
        try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(CSV_FILE))) {
            for (Archiv entry : sorted) {
                writer.write(entry.toCsvLine());
                writer.newLine();
            }
        }catch (IOException e) {
            e.printStackTrace();
        }

        System.out.printf("✅ Fertig. %d neue, %d aktualisierte Einträge. Gesamt: %d\n", added, updated, sorted.size());
    }





    private static Map<String, Archiv> readCsvAsMap(String filePath) {
        Map<String, Archiv> map = new HashMap<>();
        Path path = Paths.get(filePath);

        if (!Files.exists(path)) return map;

        try (BufferedReader reader = Files.newBufferedReader(path)) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.trim().split(";", 3);
                if (parts.length == 3) {
                    String key = parts[0] + ";" + parts[1];
                    map.put(key, new Archiv(parts[0], parts[1], parts[2]));
                }
            }
        } catch (IOException e) {
            System.err.println("⚠️ Fehler beim Lesen von " + filePath + ": " + e.getMessage());
        }

        return map;
    }

}
