"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.init = init;
exports.reset = reset;
exports.getTxs = getTxs;
exports.validateRecordTypes = validateRecordTypes;
exports.dropInvalidTxs = dropInvalidTxs;
exports.updateRecord = updateRecord;
exports.parseRecord = parseRecord;
exports.queueRequest = queueRequest;
exports.sendRequests = sendRequests;
exports.getExpiredRemoved = getExpiredRemoved;
const utils_1 = require("../utils");
const Context_1 = require("./Context");
const NodeList = __importStar(require("./NodeList"));
const Self = __importStar(require("./Self"));
const CycleCreator = __importStar(require("./CycleCreator"));
const CycleChain = __importStar(require("./CycleChain"));
const nestedCounters_1 = require("../utils/nestedCounters");
const CycleCreator_1 = require("./CycleCreator");
const ModeSystemFuncs_1 = require("./ModeSystemFuncs");
const logger_1 = require("../logger");
const lib_types_1 = require("@shardeum-foundation/lib-types");
/** STATE */
let p2pLogger;
let lastLoggedCycle;
/** ROUTES */
// const routes = {
//   internal: {},
// }
/** FUNCTIONS */
/** CycleCreator Functions */
function init() {
    // Init logger
    p2pLogger = Context_1.logger.getLogger('p2p');
    // Init state
    reset();
    lastLoggedCycle = 0;
    // Register routes
    // for (const [name, handler] of Object.entries(routes.internal)) {
    //   Comms.registerInternal(name, handler)
    // }
}
function reset() {
    return;
}
function getTxs() {
    return {};
}
function validateRecordTypes(rec) {
    const err = (0, utils_1.validateTypes)(rec, { expired: 'n', removed: 'a' });
    if (err)
        return err;
    for (const item of rec.removed) {
        if (typeof item !== 'string')
            return 'items of removed array must be strings';
    }
    return '';
}
function dropInvalidTxs(txs) {
    return txs;
}
/** Given the `txs` and `prev` cycle record, mutate the referenced `record` */
function updateRecord(txs, record, prev) {
    if (!prev) {
        record.expired = 0;
        record.removed = [];
        return;
    }
    {
        const { expired, removed } = getExpiredRemoved(prev.start, prev.desired, txs);
        nestedCounters_1.nestedCountersInstance.countEvent('p2p', `results of getExpiredRemoved: expired: ${expired} removed: ${removed.length}`, 1);
        if (logger_1.logFlags && logger_1.logFlags.verbose)
            console.log(`results of getExpiredRemoved: expired: ${expired} removed: ${removed.length} array: ${removed}`);
    }
    const problemNodeRemovalEnabled = Context_1.config.p2p.enableProblematicNodeRemoval && CycleCreator_1.currentCycle >= Context_1.config.p2p.enableProblematicNodeRemovalOnCycle;
    // we only want to use the problematic node removal logic if we are past the enableProblematicNodeRemovalOnCycle and have a full history of refutes
    // note: we may want to wait an additional config.p2p.problematicNodeHistoryLength cycles before we start removing problematic nodes
    //       this would give us a full history of refutes before we start removing problematic nodes
    if (problemNodeRemovalEnabled === false) {
        // Allow the autoscale module to set this value
        const { expired, removed } = (0, ModeSystemFuncs_1.getExpiredRemovedV2)(prev, lastLoggedCycle, txs, info);
        nestedCounters_1.nestedCountersInstance.countEvent('p2p', `results of getExpiredRemovedV2: expired: ${expired} removed: ${removed.length}`, 1);
        if (logger_1.logFlags && logger_1.logFlags.verbose)
            console.log(`results of getExpiredRemovedV2: expired: ${expired} removed: ${removed.length} array: ${removed}`);
        record.expired = expired;
        record.removed = removed; // already sorted
    }
    else {
        const { expired, removed, problematic } = (0, ModeSystemFuncs_1.getExpiredRemovedV3)(prev, lastLoggedCycle, txs, info);
        nestedCounters_1.nestedCountersInstance.countEvent('p2p', `results of getExpiredRemovedV3: expired: ${expired} removed: ${removed.length} problematic: ${problematic}`, 1);
        /* prettier-ignore */ if (logger_1.logFlags?.node_rotation_debug)
            Context_1.logger.mainLog_debug('GETEXPIREDREMOVEDV3_STATS', `results of getExpiredRemovedV3: expired: ${expired} removed: ${removed.length} problematic: ${problematic}`);
        // record.problematic = problematic // may want to write this to cycle record for
        record.expired = expired;
        record.removed = removed; // already sorted
    }
}
function parseRecord(record) {
    // Look at the removed id's and make Self emit 'removed' if your own id is there
    if (record.removed.includes(Self.id)) {
        /* prettier-ignore */ nestedCounters_1.nestedCountersInstance.countEvent('p2p', `self-removed c:${CycleCreator_1.currentCycle}`, 1);
        Self.emitter.emit('removed', Self.id);
    }
    return {
        added: [],
        removed: record.removed,
        updated: [],
    };
}
function queueRequest() {
    return;
}
function sendRequests() {
    return;
}
/** Module Functions */
/** Returns the number of expired nodes and the list of removed nodes */
function getExpiredRemoved(start, desired, txs) {
    let expired = 0;
    const removed = [];
    NodeList.potentiallyRemoved.clear();
    // Don't expire/remove any if nodeExpiryAge is negative
    if (Context_1.config.p2p.nodeExpiryAge < 0)
        return { expired, removed };
    const active = NodeList.activeByIdOrder.length;
    let expireTimestamp = (start - Context_1.config.p2p.nodeExpiryAge) * 1000;
    if (expireTimestamp < 0)
        expireTimestamp = 0;
    // initialize the max amount to remove to our config value
    let maxRemove = Context_1.config.p2p.maxRotatedPerCycle;
    // initialize `scaleDownRemove` to at most any "excess" nodes more than
    // desired. it can't be less than zero.
    let scaleDownRemove = Math.max(active - desired, 0);
    //only let the scale factor impart a partial influence based on scaleInfluenceForShrink
    const scaledAmountToShrink = getScaledAmountToShrink(); //ITN3 example = 36
    //limit the scale down by scaledAmountToShrink
    if (scaleDownRemove > scaledAmountToShrink) {
        scaleDownRemove = scaledAmountToShrink;
    }
    //maxActiveNodesToRemove is a percent of the active nodes that is set as a 0-1 value in maxShrinkMultiplier
    //this is to prevent the network from shrinking too fast
    //make sure the value is at least 1
    //ITN3 example: maxShrinkMultiplier: 0.02, active: 640 = floor(12.8) = 12
    const maxActiveNodesToRemove = Math.max(Math.floor(Context_1.config.p2p.maxShrinkMultiplier * active), 1);
    const cycle = CycleChain.newest.counter;
    if (cycle > lastLoggedCycle && scaleDownRemove > 0) {
        lastLoggedCycle = cycle;
        /* prettier-ignore */ if (logger_1.logFlags?.node_rotation_debug)
            Context_1.logger.mainLog_debug('GETEXPIREDREMOVED_DUMPNODES', 'scale down dump:' + lib_types_1.Utils.safeStringify({ cycle, scaleFactor: CycleCreator.scaleFactor, scaleDownRemove, maxActiveNodesToRemove, desired, active, scaledAmountToShrink, maxRemove, expired, }));
    }
    // Allows the network to scale down even if node rotation is turned off
    if (maxRemove < 1) {
        maxRemove = scaleDownRemove;
    }
    else {
        //else pick the higher of the two
        maxRemove = Math.max(maxRemove, scaleDownRemove);
    }
    // never remove more nodes than the difference between active and desired
    if (maxRemove > active - desired)
        maxRemove = active - desired;
    // final clamp of max remove, but only if it is more than amountToShrink
    // to avoid messing up the calculation above this next part can only make maxRemove smaller.
    // maxActiveNodesToRemove is a percent of the active nodes that is set as a 0-1 value in maxShrinkMultiplier
    // ITN3 example amountToShrink = 5.   maxActiveNodesToRemove = 12
    if (maxRemove > Context_1.config.p2p.amountToShrink && maxRemove > maxActiveNodesToRemove) {
        // yes, this max could be baked in earlier, but I like it here for clarity
        maxRemove = Math.max(Context_1.config.p2p.amountToShrink, maxActiveNodesToRemove);
    }
    // get list of nodes that have been requested to be removed
    const apoptosizedNodesList = [];
    for (const request of txs.apoptosis) {
        const node = NodeList.nodes.get(request.id);
        if (node) {
            apoptosizedNodesList.push(node.id);
        }
    }
    // Oldest node has index 0
    for (const node of NodeList.byJoinOrder) {
        // don't count syncing nodes in our expired count
        if (node.status === 'syncing')
            continue;
        // once we've hit the first node that's not expired, stop counting
        if (node.joinRequestTimestamp > expireTimestamp)
            break;
        // otherwise, count this node as expired
        expired++;
        // Add it to removed if it isn't full
        if (Context_1.config.p2p.uniqueRemovedIds) {
            // Limit the number of nodes that can be removed by removed + apoptosized
            if (removed.length + apoptosizedNodesList.length < maxRemove) {
                NodeList.potentiallyRemoved.add(node.id);
                if (!apoptosizedNodesList.includes(node.id)) {
                    (0, utils_1.insertSorted)(removed, node.id);
                }
            }
            else
                break;
        }
        else {
            if (removed.length < maxRemove) {
                NodeList.potentiallyRemoved.add(node.id);
                (0, utils_1.insertSorted)(removed, node.id);
            }
        }
    }
    return { expired, removed };
}
function info(...msg) {
    const entry = `Rotation: ${msg.join(' ')}`;
    p2pLogger.info(entry);
}
function warn(...msg) {
    const entry = `Rotation: ${msg.join(' ')}`;
    p2pLogger.warn(entry);
}
function error(...msg) {
    const entry = `Rotation: ${msg.join(' ')}`;
    p2pLogger.error(entry);
}
/** Returns a linearly interpolated value between `amountToShrink` and the same
 * multiplied by a `scaleFactor`. The result depends on the
 * `scaleInfluenceForShrink`
 *
 * ITN3 example numbers  (128 / 5) * (640 / 100) = 25.6 * 6.4 = 163.84
 * config.p2p.amountToShrink  5
 * config.p2p.scaleInfluenceForShrink  0.2,
 *
 * Math.floor(lerp(163.84, 5, 0.2)) = 36!
 *
 * this is use as a max though onlty to clamp but not raise our amount to shrink
 * this is for the scaled down remove case
 *
 *
 */
function getScaledAmountToShrink() {
    const nonScaledAmount = Context_1.config.p2p.amountToShrink;
    const scaledAmount = Context_1.config.p2p.amountToShrink * CycleCreator.scaleFactor;
    const scaleInfluence = Context_1.config.p2p.scaleInfluenceForShrink;
    return Math.floor((0, utils_1.lerp)(nonScaledAmount, scaledAmount, scaleInfluence));
}
//# sourceMappingURL=Rotation.js.map