package de.roko.genalogy.downloader.database;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

import java.sql.*;
import java.util.Objects;

public class ArchiveInserter {

    private static final String DB_FILE = "archion.db";

    public static void main(String[] args) throws Exception {
        new ArchiveInserter().run();
    }

    public void run() throws Exception {
        WebDriverManager.chromedriver().setup();
        WebDriver driver = new ChromeDriver();
        run(driver);
    }

    public void run(WebDriver driver) throws Exception {

        driver.get("https://www.archion.de/de/alle-archive");

        String html = driver.getPageSource();
        driver.quit();

        Document doc = Jsoup.parse(html);
        Elements stateDivs = doc.select("div[id^=state]");

        try (Connection conn = DriverManager.getConnection("jdbc:sqlite:" + DB_FILE)) {
            int added = 0, updated = 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 url = "https://www.archion.de" + link.attr("href").trim();

                    Integer existingId = findArchiveId(conn, bundesland, archivname);
                    if (existingId == null) {
                        insertArchive(conn, bundesland, archivname, url);
                        added++;
                    } else {
                        if (updateArchiveIfLinkChanged(conn, existingId, url)) {
                            updated++;
                        }
                    }
                }
            }

            System.out.printf("✅ Archive verarbeitet. Neu: %d, aktualisiert: %d%n", added, updated);
        }
    }

    private Integer findArchiveId(Connection conn, String bundesland, String name) throws SQLException {
        String sql = "SELECT id FROM archive WHERE bundesland = ? AND name = ?";
        try (PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setString(1, bundesland);
            stmt.setString(2, name);
            ResultSet rs = stmt.executeQuery();
            return rs.next() ? rs.getInt("id") : null;
        }
    }

    private void insertArchive(Connection conn, String bundesland, String name, String link) throws SQLException {
        String sql = "INSERT INTO archive (bundesland, name, link) VALUES (?, ?, ?)";
        try (PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setString(1, bundesland);
            stmt.setString(2, name);
            stmt.setString(3, link);
            stmt.executeUpdate();
        }
    }

    private boolean updateArchiveIfLinkChanged(Connection conn, int id, String newLink) throws SQLException {
        String sql = "SELECT link FROM archive WHERE id = ?";
        try (PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, id);
            ResultSet rs = stmt.executeQuery();
            if (rs.next() && !Objects.equals(rs.getString("link"), newLink)) {
                try (PreparedStatement updateStmt = conn.prepareStatement("UPDATE archive SET link = ? WHERE id = ?")) {
                    updateStmt.setString(1, newLink);
                    updateStmt.setInt(2, id);
                    updateStmt.executeUpdate();
                    return true;
                }
            }
        }
        return false;
    }
}

