"use strict";
/**
 * Crawler module, public API and lifecycle management
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.MidnightCrawler = exports.BlockProcessor = void 0;
exports.startCrawler = startCrawler;
exports.stopCrawler = stopCrawler;
exports.isCrawlerRunning = isCrawlerRunning;
const MidnightNodeProvider_1 = require("../providers/MidnightNodeProvider");
const Crawler_1 = require("./Crawler");
var BlockProcessor_1 = require("./BlockProcessor");
Object.defineProperty(exports, "BlockProcessor", { enumerable: true, get: function () { return BlockProcessor_1.BlockProcessor; } });
var Crawler_2 = require("./Crawler");
Object.defineProperty(exports, "MidnightCrawler", { enumerable: true, get: function () { return Crawler_2.MidnightCrawler; } });
let activeCrawler = null;
let activeNodeProvider = null;
/**
 * Start the crawler. Idempotent, calling twice is a no-op.
 */
async function startCrawler(config) {
    if (activeCrawler) {
        console.warn('[Crawler] Already running');
        return;
    }
    const nodeProvider = new MidnightNodeProvider_1.MidnightNodeProvider({
        nodeUrl: config.nodeUrl,
        requestTimeout: config.requestTimeout || 30000
    });
    const crawler = new Crawler_1.MidnightCrawler(nodeProvider, config);
    try {
        await crawler.start();
    }
    catch (err) {
        // Crawler start can fail after the provider connected; ensure no socket leaks.
        try {
            await nodeProvider.disconnect();
        }
        catch {
            // Ignore disconnect errors while handling startup failure.
        }
        throw err;
    }
    activeCrawler = crawler;
    activeNodeProvider = nodeProvider;
    console.log('[Crawler] Started');
}
/**
 * Stop the crawler and disconnect the node provider.
 */
async function stopCrawler() {
    if (activeCrawler) {
        await activeCrawler.stop();
        activeCrawler = null;
    }
    if (activeNodeProvider) {
        try {
            await activeNodeProvider.disconnect();
        }
        catch { /* ignore disconnect errors */ }
        activeNodeProvider = null;
    }
    console.log('[Crawler] Stopped');
}
/**
 * True when the crawler lifecycle wrapper currently has an active crawler instance.
 */
function isCrawlerRunning() {
    return activeCrawler !== null;
}
