/**
 * @module sync-innerspace-constants.withid.respec
 *
 * Verifies syncing "Constants" (ibGibs without timelines/TJPs) with Identity.
 * Also verifies Smart Diff behavior (Constants shouldn't be re-sent).
 */
import { respecfully, iReckon, ifWe } from '@ibgib/helper-gib/dist/respec-gib/respec-gib.mjs';
const maam = `[${import.meta.url}]`, sir = maam;
import { clone, delay } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';
import { getIbGibAddr } from '@ibgib/ts-gib/dist/helper.mjs';
import { Factory_V1 } from '@ibgib/ts-gib/dist/V1/index.mjs';
import { GLOBAL_LOG_A_LOT } from '../core-constants.mjs';
import { SyncSagaCoordinator } from './sync-saga-coordinator.mjs';
import { putInSpace, getFromSpace } from '../witness/space/space-helper.mjs';
import { Metaspace_Innerspace } from '../witness/space/metaspace/metaspace-innerspace/metaspace-innerspace.mjs';
import { InnerSpace_V1 } from '../witness/space/inner-space/inner-space-v1.mjs';
import { DEFAULT_INNER_SPACE_DATA_V1 } from '../witness/space/inner-space/inner-space-types.mjs';
import { SyncPeerInnerspace_V1 } from './sync-peer/sync-peer-innerspace/sync-peer-innerspace-v1.mjs';
import { SYNC_PEER_INNERSPACE_DEFAULT_DATA_V1 } from './sync-peer/sync-peer-innerspace/sync-peer-innerspace-constants.mjs';
import { getDependencyGraph } from '../common/other/graph-helper.mjs';
import { KeystoneService_V1 } from '../keystone/keystone-service-v1.mjs';
import { KEYSTONE_VERB_SYNC, POOL_ID_SYNC, } from '../keystone/keystone-constants.mjs';
import { createStandardPoolConfig } from '../keystone/keystone-config-builder.mjs';
import { KeystoneReplenishStrategy } from '../keystone/keystone-types.mjs';
const logalot = GLOBAL_LOG_A_LOT;
const lc = `[sync-innerspace-constants.withid.respec]`;
const SENDER_SECRET = 'test-sender-secret-constants-withid';
const SENDER_IDENTITY_SYNC_POOL_CONFIG = createStandardPoolConfig({
    id: POOL_ID_SYNC,
    salt: 'senderidentitysyncsaltconstantswithid',
    verbs: [KEYSTONE_VERB_SYNC],
    size: 200,
    sequential: 1,
    random: 1,
    targetBinding: 2,
    replenishStrategy: KeystoneReplenishStrategy.topUp,
});
await respecfully(sir, `Sync Constants (No TJP) with Identity`, async () => {
    let metaspace;
    let sourceSpace;
    let destSpace;
    // #region Round 1 - Sync Constants
    await respecfully(sir, `Syncing Constants (No TJP) (Source -> Dest)`, async () => {
        // 1. Setup Spaces
        metaspace = new Metaspace_Innerspace(undefined);
        await metaspace.initialize({
            getFnAlert: () => async ({ title, msg }) => { },
            getFnPrompt: () => async ({ title, msg }) => { return ''; },
            getFnPromptPassword: () => async (title, msg) => { return null; },
        });
        while (!metaspace.initialized) {
            await delay(10);
        }
        sourceSpace = new InnerSpace_V1({
            ...DEFAULT_INNER_SPACE_DATA_V1,
            name: 'source',
            uuid: 'source_uuid',
            description: 'source test space',
        });
        await sourceSpace.initialized;
        destSpace = new InnerSpace_V1({
            ...DEFAULT_INNER_SPACE_DATA_V1,
            name: 'dest',
            uuid: 'dest_uuid',
            description: 'dest test space',
        });
        await destSpace.initialized;
        const keystoneSvc = new KeystoneService_V1();
        const r1_senderIdentity_v0_source = await keystoneSvc.genesis({
            masterSecret: SENDER_SECRET,
            configs: [SENDER_IDENTITY_SYNC_POOL_CONFIG],
            metaspace,
            space: sourceSpace,
        });
        // post the senderIdentity to receiver
        await metaspace.put({ ibGib: r1_senderIdentity_v0_source, space: destSpace });
        await metaspace.registerNewIbGib({ ibGib: r1_senderIdentity_v0_source, space: destSpace });
        // #region r1 setup
        // 2. Create Constant (C1) in Source
        const r1_c1_v0_source = await Factory_V1.constant({
            parentPrimitiveIb: 'root',
            ib: 'constant_c1',
            data: { some: 'data' },
        });
        const r1_c1_v0_source_addr = getIbGibAddr({ ibGib: r1_c1_v0_source });
        await putInSpace({ space: sourceSpace, ibGibs: [r1_c1_v0_source] });
        // #endregion r1 setup
        // #region r1 verify pre
        await respecfully(sir, `r1 verify pre`, async () => {
            await ifWe(sir, `C1 is not initially in Dest`, async () => {
                const checkDest1 = await getFromSpace({ space: destSpace, addr: r1_c1_v0_source_addr });
                iReckon(sir, checkDest1.success).asTo('Dest initially does not have C1').isGonnaBeFalse();
            });
        });
        // #endregion r1 verify pre
        // 3. Setup Coordinator and Peer
        const senderCoordinator = new SyncSagaCoordinator();
        const receiverCoordinator = new SyncSagaCoordinator();
        const peer = new SyncPeerInnerspace_V1(clone(SYNC_PEER_INNERSPACE_DEFAULT_DATA_V1));
        await peer.initialized;
        await peer.initializeOpts({
            sagaId: '',
            localMetaspace: metaspace,
            localSpace: sourceSpace, // "Client"
            receiverSpace: destSpace, // "Server"
            receiverCoordinator,
            receiverMetaspace: metaspace,
        });
        // #region r1 syncs
        // 4. Sync C1 (First Pass)
        let resSync = await senderCoordinator.sync({
            peer,
            localSpace: sourceSpace,
            metaspace: metaspace,
            domainIbGibs: [r1_c1_v0_source],
            senderIdentity: r1_senderIdentity_v0_source,
            fnSenderSecret: async () => SENDER_SECRET,
        });
        await resSync.done;
        // Get the latest sender identity frame after Sync 1
        const latestSenderAddr1 = await metaspace.getLatestAddr({
            addr: getIbGibAddr({ ibGib: r1_senderIdentity_v0_source }),
            space: sourceSpace,
        });
        const resGetLatestI1 = await getFromSpace({ space: sourceSpace, addr: latestSenderAddr1 });
        const r1_senderIdentity_v1_source_postSync1 = resGetLatestI1.ibGibs[0];
        // 5. Sync C1 (Second Pass - Idempotency / Smart Diff)
        resSync = await senderCoordinator.sync({
            peer: peer,
            localSpace: sourceSpace,
            metaspace: metaspace,
            domainIbGibs: [r1_c1_v0_source],
            senderIdentity: r1_senderIdentity_v1_source_postSync1,
            fnSenderSecret: async () => SENDER_SECRET,
        });
        await resSync.done;
        // Get the latest sender identity frame after Sync 2
        const latestSenderAddr2 = await metaspace.getLatestAddr({
            addr: getIbGibAddr({ ibGib: r1_senderIdentity_v0_source }),
            space: sourceSpace,
        });
        const resGetLatestI2 = await getFromSpace({ space: sourceSpace, addr: latestSenderAddr2 });
        const r1_senderIdentity_v2_source_postSync2 = resGetLatestI2.ibGibs[0];
        // 6. Create "Constant with Dependency" (C2 -> C1)
        const r1_c2_v0_source_rel8C1 = await Factory_V1.constant({
            ib: 'constant_c2',
            parentPrimitiveIb: 'root',
            rel8ns: {
                link: [r1_c1_v0_source_addr],
            },
        });
        const r1_c2_v0_source_addr = getIbGibAddr({ ibGib: r1_c2_v0_source_rel8C1 });
        await putInSpace({ space: sourceSpace, ibGibs: [r1_c2_v0_source_rel8C1] });
        // Sync C2
        resSync = await senderCoordinator.sync({
            peer: peer,
            localSpace: sourceSpace,
            metaspace: metaspace,
            domainIbGibs: [r1_c2_v0_source_rel8C1],
            senderIdentity: r1_senderIdentity_v2_source_postSync2,
            fnSenderSecret: async () => SENDER_SECRET,
        });
        await resSync.done;
        // #endregion r1 syncs
        // #region r1 verify post
        await respecfully(sir, `r1 verify post`, async () => {
            await ifWe(sir, `Dest has C1 and C2 after sync`, async () => {
                const getC1Dest = await getFromSpace({ space: destSpace, addr: r1_c1_v0_source_addr });
                const getC2Dest = await getFromSpace({ space: destSpace, addr: r1_c2_v0_source_addr });
                iReckon(sir, getC1Dest.success && !!getC1Dest.ibGibs[0]).asTo('Dest has C1').isGonnaBeTrue();
                iReckon(sir, getC2Dest.success && !!getC2Dest.ibGibs[0]).asTo('Dest has C2').isGonnaBeTrue();
            });
            await ifWe(sir, 'sessionIdentity evolved the expected number of times', async () => {
                const latestS = peer.currentSessionIdentity;
                iReckon(sir, latestS).asTo('latest session identity exists on peer').isGonnaBeTruthy();
                if (latestS) {
                    iReckon(sir, latestS.data?.n).asTo('session identity data.n').isGonnaBe(2);
                }
            });
            await ifWe(sir, 'sender durable space has I (evolved frame)', async () => {
                const latestSenderIdentityAddr = await metaspace.getLatestAddr({
                    addr: getIbGibAddr({ ibGib: r1_senderIdentity_v0_source }),
                    space: sourceSpace,
                });
                iReckon(sir, latestSenderIdentityAddr).asTo('latestSenderIdentityAddr exists').isGonnaBeTruthy();
                if (latestSenderIdentityAddr) {
                    const resGetSourceI = await getFromSpace({ space: sourceSpace, addr: latestSenderIdentityAddr });
                    iReckon(sir, resGetSourceI.success && resGetSourceI.ibGibs?.length === 1).asTo('evolved I exists in sourceSpace').isGonnaBeTrue();
                    if (resGetSourceI.success && resGetSourceI.ibGibs?.[0]) {
                        const evolvedI = resGetSourceI.ibGibs[0];
                        iReckon(sir, evolvedI.data?.n).asTo('evolved I data.n').isGonnaBe(3);
                    }
                }
            });
            await ifWe(sir, 'receiver durable space has I (evolved frame)', async () => {
                const latestSenderIdentityAddr = await metaspace.getLatestAddr({
                    addr: getIbGibAddr({ ibGib: r1_senderIdentity_v0_source }),
                    space: sourceSpace,
                });
                iReckon(sir, latestSenderIdentityAddr).asTo('latestSenderIdentityAddr exists').isGonnaBeTruthy();
                if (latestSenderIdentityAddr) {
                    const resGetDestI = await getFromSpace({ space: destSpace, addr: latestSenderIdentityAddr });
                    iReckon(sir, resGetDestI.success && resGetDestI.ibGibs?.length === 1).asTo('evolved I exists in destSpace').isGonnaBeTrue();
                    if (resGetDestI.success && resGetDestI.ibGibs?.[0]) {
                        const evolvedI = resGetDestI.ibGibs[0];
                        iReckon(sir, evolvedI.data?.n).asTo('evolved I data.n').isGonnaBe(3);
                    }
                }
            });
            await ifWe(sir, 'sender durable space has full S dep graph', async () => {
                const latestS = peer.currentSessionIdentity;
                iReckon(sir, latestS).asTo('latestS exists').isGonnaBeTruthy();
                if (latestS) {
                    const depGraphS = await getDependencyGraph({ ibGib: latestS, space: sourceSpace });
                    const addrs = Object.keys(depGraphS);
                    iReckon(sir, addrs.length > 2).asTo('number of nodes in S graph > 2').isGonnaBeTrue();
                }
            });
            await ifWe(sir, 'receiver durable space has full S dep graph', async () => {
                const latestS = peer.currentSessionIdentity;
                iReckon(sir, latestS).asTo('latestS exists').isGonnaBeTruthy();
                if (latestS) {
                    const depGraphS = await getDependencyGraph({ ibGib: latestS, space: destSpace });
                    const addrs = Object.keys(depGraphS);
                    iReckon(sir, addrs.length > 2).asTo('number of nodes in S graph in destSpace > 2').isGonnaBeTrue();
                }
            });
        });
        // #endregion r1 verify post
    });
    // #endregion Round 1 - Sync Constants
});
//# sourceMappingURL=sync-innerspace-constants.withid.respec.mjs.map