"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 (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getMaxConsecutiveRefutes = exports.getRefutePercentage = exports.getProblematicNodeInfoForSelf = exports.getProblematicNodes = exports.exportProblematicNodeCache = exports.pruneInactiveNodesFromCache = exports.rebuildCacheFromCycleChain = exports.updateProblematicNodeCache = exports.initProblematicNodeCache = void 0;
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`);
        }
    }
}
exports.initProblematicNodeCache = initProblematicNodeCache;
// 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);
        }
    }
}
exports.updateProblematicNodeCache = updateProblematicNodeCache;
// 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);
    }
}
exports.rebuildCacheFromCycleChain = rebuildCacheFromCycleChain;
// 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);
    }
}
exports.pruneInactiveNodesFromCache = pruneInactiveNodesFromCache;
// Export the problematic node cache as compressed JSON
function exportProblematicNodeCache() {
    if (!problematicNodeCache || !Context_1.config.p2p.enableProblematicNodeCacheBuilding) {
        return null;
    }
    try {
        return problematicNodeCache.toJSON();
    }
    catch (err) {
        error('Failed to export ProblematicNodeCache:', err);
        return null;
    }
}
exports.exportProblematicNodeCache = exportProblematicNodeCache;
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);
    }
}
exports.getProblematicNodes = getProblematicNodes;
// Get problematic node info for reporting to monitor - info about self node only
function getProblematicNodeInfoForSelf(nodeId) {
    if (!problematicNodeCache || !Context_1.config.p2p.enableProblematicNodeCacheBuilding) {
        return null;
    }
    try {
        const currentCycle = CycleChain.newest?.counter || 0;
        const metrics = problematicNodeCache.calculateNodeMetrics(nodeId, currentCycle);
        const refuteHistory = problematicNodeCache.refuteHistory.get(nodeId) || [];
        // Build cycle history for last 30 cycles
        const cycleHistoryLength = 30;
        const startCycle = Math.max(1, currentCycle - cycleHistoryLength + 1);
        const cycleRefuteHistory = [];
        for (let cycle = startCycle; cycle <= currentCycle; cycle++) {
            cycleRefuteHistory.push(refuteHistory.includes(cycle));
        }
        // Calculate total refutes in the history window
        const totalRefutes = refuteHistory.filter((cycle) => cycle >= startCycle && cycle <= currentCycle).length;
        const problematicNodeInfo = {
            isProblematic: metrics.consecutiveRefutes >= Context_1.config.p2p.problematicNodeConsecutiveRefuteThreshold ||
                metrics.refutePercentage >= Context_1.config.p2p.problematicNodeRefutePercentageThreshold,
            totalRefutes: totalRefutes,
            maxConsecutiveRefutes: metrics.consecutiveRefutes,
            refutePercentage: metrics.refutePercentage,
            cycleRefuteHistory: cycleRefuteHistory,
        };
        return problematicNodeInfo;
    }
    catch (err) {
        error('Failed to get problematic node info for self:', err);
        return null;
    }
}
exports.getProblematicNodeInfoForSelf = getProblematicNodeInfoForSelf;
function getRefutePercentage(refuteCycles, currentCycle) {
    if (Context_1.config.p2p.useProblematicNodeCacheV2 && problematicNodeCache) {
        return problematicNodeCache.getRefutePercentage(refuteCycles, currentCycle);
    }
    return 0;
}
exports.getRefutePercentage = getRefutePercentage;
function getMaxConsecutiveRefutes(refuteCycles, currentCycle) {
    if (Context_1.config.p2p.useProblematicNodeCacheV2 && problematicNodeCache) {
        return problematicNodeCache.getMaxConsecutiveRefutes(refuteCycles, currentCycle);
    }
    return 0;
}
exports.getMaxConsecutiveRefutes = getMaxConsecutiveRefutes;
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