"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.initProblematicNodeCache = initProblematicNodeCache;
exports.updateProblematicNodeCache = updateProblematicNodeCache;
exports.rebuildCacheFromCycleChain = rebuildCacheFromCycleChain;
exports.pruneInactiveNodesFromCache = pruneInactiveNodesFromCache;
exports.exportProblematicNodeCache = exportProblematicNodeCache;
exports.getProblematicNodes = getProblematicNodes;
exports.getRefutePercentage = getRefutePercentage;
exports.getConsecutiveRefutes = getConsecutiveRefutes;
const NodeList = __importStar(require("./NodeList"));
const Context_1 = require("./Context");
const ProblematicNodeCache_1 = require("./ProblematicNodeCache");
const CycleChain = __importStar(require("./CycleChain"));
const logger_1 = require("../logger");
// Cache instance for shadow mode
let problematicNodeCache = null;
let p2pLogger;
// Initialize the cache
function initProblematicNodeCache() {
    p2pLogger = Context_1.logger.getLogger('p2p');
    if (Context_1.config.p2p.enableProblematicNodeCacheBuilding) {
        problematicNodeCache = new ProblematicNodeCache_1.ProblematicNodeCache(Context_1.config);
        // Build initial cache from existing cycle records
        const cycles = CycleChain.newest
            ? CycleChain.getCycleChain(Math.max(0, CycleChain.newest.counter - Context_1.config.p2p.problematicNodeHistoryLength + 1), CycleChain.newest.counter)
            : [];
        if (cycles.length > 0) {
            problematicNodeCache.buildFromCycles(cycles);
            /* prettier-ignore */ if (logger_1.logFlags.p2pNonFatal)
                info(`ProblematicNodeCache initialized with ${cycles.length} cycles`);
        }
    }
}
// Update cache when new cycle is created
function updateProblematicNodeCache(cycle) {
    if (problematicNodeCache && Context_1.config.p2p.enableProblematicNodeCacheBuilding) {
        try {
            problematicNodeCache.addCycle(cycle, true); // Enable auto-prune
        }
        catch (err) {
            error('Failed to update ProblematicNodeCache:', err);
        }
    }
}
// Rebuild cache from all cycles in CycleChain
function rebuildCacheFromCycleChain() {
    if (!problematicNodeCache || !Context_1.config.p2p.enableProblematicNodeCacheBuilding) {
        return;
    }
    try {
        const cycles = CycleChain.cycles || [];
        if (cycles.length > 0) {
            problematicNodeCache.buildFromCycles(cycles);
            /* prettier-ignore */ if (logger_1.logFlags.p2pNonFatal)
                info(`ProblematicNodeCache rebuilt with ${cycles.length} cycles`);
        }
    }
    catch (err) {
        error('Failed to rebuild ProblematicNodeCache from CycleChain:', err);
    }
}
// Prune cache for nodes that are no longer active
function pruneInactiveNodesFromCache() {
    if (!problematicNodeCache || !Context_1.config.p2p.enableProblematicNodeCacheBuilding) {
        return;
    }
    try {
        const activeNodeIds = new Set(NodeList.activeByIdOrder.map((node) => node.id));
        problematicNodeCache.pruneInactiveNodes(activeNodeIds);
        /* prettier-ignore */ if (logger_1.logFlags.verbose)
            info(`Pruned inactive nodes from ProblematicNodeCache`);
    }
    catch (err) {
        error('Failed to prune inactive nodes from ProblematicNodeCache:', err);
    }
}
// Export the problematic node cache as compressed JSON
function exportProblematicNodeCache() {
    if (!problematicNodeCache || !Context_1.config.p2p.enableProblematicNodeCacheBuilding) {
        return null;
    }
    try {
        return problematicNodeCache.toCompressedJSON();
    }
    catch (err) {
        error('Failed to export ProblematicNodeCache:', err);
        return null;
    }
}
function getProblematicNodes(prevRecord) {
    // Use cache-based implementation if enabled
    if (Context_1.config.p2p.useProblematicNodeCacheV2 && problematicNodeCache) {
        const activeNodeIds = new Set(NodeList.activeByIdOrder.map((node) => node.id));
        return problematicNodeCache.getProblematicNodes(prevRecord.counter, activeNodeIds);
    }
}
function getRefutePercentage(refuteCycles, currentCycle) {
    if (Context_1.config.p2p.useProblematicNodeCacheV2 && problematicNodeCache) {
        return problematicNodeCache.getRefutePercentage(refuteCycles, currentCycle);
    }
    return 0;
}
function getConsecutiveRefutes(refuteCycles, currentCycle) {
    if (Context_1.config.p2p.useProblematicNodeCacheV2 && problematicNodeCache) {
        return problematicNodeCache.getConsecutiveRefutes(refuteCycles, currentCycle);
    }
    return 0;
}
function info(...msg) {
    const entry = `ProblemNodeHandler: ${msg.join(' ')}`;
    p2pLogger.info(entry);
}
function warn(...msg) {
    const entry = `ProblemNodeHandler: ${msg.join(' ')}`;
    p2pLogger.warn(entry);
}
function error(...msg) {
    const entry = `ProblemNodeHandler: ${msg.join(' ')}`;
    p2pLogger.error(entry);
}
//# sourceMappingURL=ProblemNodeHandler.js.map