'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;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
// 5.1.0 — introduces system.hdb_deployment for deployment tracking.
//
// Fresh installs get the table automatically via utility/mount_hdb.ts (which iterates
// json/systemSchema.json on first boot). This directive handles the upgrade path: existing
// installs that already have a system schema need the new table added explicitly.
//
// IMPORTANT: this directive must be versioned to the first release that ships the
// deployment-recorder code depending on the table (5.1.0), NOT a later release. Directives
// only run when current_version < directive_version <= upgrade_version (see
// directivesController.getVersionsForUpgrade). Tagging it for a later release than the
// dependent code (it was previously mis-tagged 5.2.0) means it never fires on the
// 5.0.x -> 5.1.x upgrade path, leaving the table missing and replicated deploy_component
// failing on peer nodes.
const databases_ts_1 = require("../../resources/databases.js");
const systemSchema_json_1 = __importDefault(require("../../json/systemSchema.json"));
const terms = __importStar(require("../../utility/hdbTerms.js"));
const initPaths = __importStar(require("../../dataLayer/harperBridge/lmdbBridge/lmdbUtility/initializePaths.js"));
const harperBridge_ts_1 = __importDefault(require("../../dataLayer/harperBridge/harperBridge.js"));
const harper_logger_ts_1 = __importDefault(require("../../utility/logging/harper_logger.js"));
const DEPLOYMENT_TABLE = terms.SYSTEM_TABLE_NAMES.DEPLOYMENT_TABLE_NAME;
async function createHdbDeploymentIfMissing() {
    if (databases_ts_1.databases.system?.[DEPLOYMENT_TABLE]) {
        harper_logger_ts_1.default.info(`system.${DEPLOYMENT_TABLE} already exists; skipping create.`);
        // Still run the patch — installs that created hdb_deployment before the is_hash_attribute
        // fix was introduced have an __dbis__ entry without that field. harperdb@4.x uses
        // is_hash_attribute to determine LMDB DBI open flags; without it the DBI is opened with
        // wrong flags (DUPSORT set) and LMDB throws MDB_INCOMPATIBLE, breaking downgrade.
        await patchHdbDeploymentIsHashAttribute();
        return;
    }
    harper_logger_ts_1.default.info(`Creating system.${DEPLOYMENT_TABLE} table for deployment tracking.`);
    const CreateTableObject = require('../../dataLayer/CreateTableObject').default || require('../../dataLayer/CreateTableObject');
    const schema = systemSchema_json_1.default[DEPLOYMENT_TABLE];
    if (!schema) {
        throw new Error(`systemSchema.${DEPLOYMENT_TABLE} is missing; cannot run 5.1.0 directive.`);
    }
    initPaths.initSystemSchemaPaths(terms.SYSTEM_SCHEMA_NAME, DEPLOYMENT_TABLE);
    const createTable = new CreateTableObject(terms.SYSTEM_SCHEMA_NAME, DEPLOYMENT_TABLE, schema.hash_attribute);
    createTable.attributes = schema.attributes;
    const primaryKeyAttribute = createTable.attributes.find(({ attribute }) => attribute === schema.hash_attribute);
    if (primaryKeyAttribute)
        primaryKeyAttribute.isPrimaryKey = true;
    createTable.audit = true;
    await harperBridge_ts_1.default.createTable(DEPLOYMENT_TABLE, createTable);
}
/**
 * Patch the hdb_deployment __dbis__ primary-key entry to include is_hash_attribute: true.
 *
 * harperdb@4.x reads is_hash_attribute from __dbis__ to derive the LMDB DBI open flags
 * (DBIDefinition(dup_sort, is_hash_attribute)). If the field is absent it opens the DBI
 * with dup_sort=true / useVersions=false — the opposite of how harper@5 created it — which
 * causes LMDB to throw MDB_INCOMPATIBLE and prevents harperdb@4 from starting after a
 * 5.1.x downgrade.
 *
 * This is safe to call when the table already exists: it is a no-op if is_hash_attribute is
 * already set, and writing it back is idempotent (lmdb upsert).
 */
async function patchHdbDeploymentIsHashAttribute() {
    const systemTable = databases_ts_1.databases.system?.[DEPLOYMENT_TABLE];
    if (!systemTable?.dbisDB)
        return;
    const dbiName = `${DEPLOYMENT_TABLE}/`;
    const primaryAttr = systemTable.dbisDB.getSync(dbiName);
    if (!primaryAttr || primaryAttr.is_hash_attribute)
        return; // already correct
    primaryAttr.is_hash_attribute = true;
    await systemTable.dbisDB.put(dbiName, primaryAttr);
    harper_logger_ts_1.default.info(`Patched system.${DEPLOYMENT_TABLE} __dbis__ entry with is_hash_attribute=true for harperdb@4.x downgrade compatibility.`);
}
const directive510 = {
    version: '5.1.0',
    sync_functions: [],
    async_functions: [createHdbDeploymentIfMissing],
};
exports.default = [directive510];
//# sourceMappingURL=5-1-0.js.map