import { clone, extractErrorMsg, getUUID } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';
import { getIbAndGib, getIbGibAddr, } from '@ibgib/ts-gib/dist/helper.mjs';
import { validateIbGibIntrinsically } from '@ibgib/ts-gib/dist/V1/validate-helper.mjs';
import { GLOBAL_LOG_A_LOT } from '../../../core-constants.mjs';
import { getSpaceIb, } from '../space-helper.mjs';
import { getTjpAddr } from '../../../common/other/ibgib-helper.mjs';
import { ReconciliationSpaceBase, } from '../reconciliation-space/reconciliation-space-base.mjs';
import { DEFAULT_INNER_SPACE_DATA_V1 } from './inner-space-types.mjs';
import { getGib } from '@ibgib/ts-gib/dist/V1/transforms/transform-helper.mjs';
import { isMetaStone, parseMetaStoneIb } from '../../../common/meta-stone/meta-stone-helper.mjs';
import { META_STONE_TARGET_REL8N_NAME } from '../../../common/meta-stone/meta-stone-constants.mjs';
const logalot = GLOBAL_LOG_A_LOT;
/**
 * Base class convenience for a "local" space
 * (i.e. analogous to residing on the same computer as the app).
 *
 * Base implementation defaults to a naive in-memory internal object that
 * tracks ibgibs with a simple map.
 */
export class InnerSpace_V1 extends ReconciliationSpaceBase {
    /**
     * Log context for convenience with logging. (Ignore if you don't want to use this.)
     */
    lc = `[${InnerSpace_V1.name}]`;
    /**
     * In-memory store of ibgibs stored in this inner space object.
     *
     * @see {@link rel8ns} in {@link WitnessBase_V1} base class.
     */
    ibGibs = {};
    /**
     * Each tjp/timeline has its own map of metastones.
     *
     * NOTE: This is a map of maps.
     */
    ibGibMetastones = {};
    /**
     * all known metastone addrs for this innerspace
     */
    get metastoneAddrs() {
        const resMetastones = [];
        Object.values(this.ibGibMetastones).forEach(map => {
            Object.keys(map)
                .forEach(metastone => resMetastones.push(metastone));
        });
        return resMetastones;
    }
    /**
     * all known metastone ibgibs for this innerspace
     */
    get metastoneIbGibs() {
        const resMetastones = [];
        Object.values(this.ibGibMetastones).forEach(map => {
            Object.values(map)
                .forEach(metastone => resMetastones.push(metastone));
        });
        return resMetastones;
    }
    constructor(initialData, initialRel8ns) {
        super(initialData, initialRel8ns);
    }
    /**
     * Initializes to default space values.
     */
    async initialize() {
        const lc = `${this.lc}[${this.initialize.name}]`;
        try {
            // if (logalot) { console.log(`${lc} starting...`); }
            // await super.initialize();
            // if (!this.data) { throw new Error(`(UNEXPECTED) this.data is falsy? (E: 6461b2e4c9877053689dbc8bb375a623)`); }
            // if (!this.data?.classname) { this.data!.classname = InnerSpace_V1.name }
            // this.ib = getSpaceIb({ space: this });
            // this.gib = await getGib({ ibGib: this });
            if (logalot) {
                console.log(`${lc} starting...`);
            }
            if (!this.data) {
                this.data = clone(DEFAULT_INNER_SPACE_DATA_V1);
                this.data = this.data; // why does ts compiler need this?
            }
            if (this.data.classname !== InnerSpace_V1.name) {
                if (this.data.classname) {
                    // only warn if the consumer has explicitly set a different classname
                    console.warn(`${lc} this.data.classname (${this.data.classname}) !== ${InnerSpace_V1.name}. overriding this. (W: 4cac18140e58f0bd2890010a3639d225)`);
                }
                this.data.classname = InnerSpace_V1.name; // always set?
            }
            // if (!this.data.uuid) { throw new Error(`this.data.uuid is falsy. right now i'm assuming data.uuid is truthy. this is what i'm using atow (12/2024) (E: e531e3c812c22324e856cf219e337825)`); }
            this.data.uuid ??= await getUUID();
            this.ib = getSpaceIb({ space: this, classname: this.data.classname });
            this.gib = await getGib({ ibGib: this });
        }
        catch (error) {
            console.error(`${lc} ${error.message}`);
            throw error;
        }
        finally {
            if (logalot) {
                console.log(`${lc} complete.`);
            }
        }
    }
    async _getLatestAddrsInStore(ibGibs) {
        const lc = `${this.lc}[_getLatestAddrsInStore]`;
        try {
            if (logalot) {
                console.log(`${lc} starting...`);
            }
            const ibGibAddrs = ibGibs.map(x => getIbGibAddr({ ibGib: x }));
            const arg = { data: { ibGibAddrs } };
            const resGet = await this.getLatestAddrsImpl(arg);
            return resGet.data.latestAddrsMap;
        }
        catch (error) {
            console.error(`${lc} ${extractErrorMsg(error)}`);
            throw error;
        }
    }
    async _getIbGibsFromStore(addrs) {
        const lc = `${this.lc}[_getIbGibsFromStore]`;
        try {
            if (logalot) {
                console.log(`${lc} starting...`);
            }
            const res = {};
            for (const addr of addrs) {
                if (this.ibGibs[addr]) {
                    res[addr] = this.ibGibs[addr];
                }
            }
            return res;
        }
        catch (error) {
            console.error(`${lc} ${extractErrorMsg(error)}`);
            throw error;
        }
    }
    async _putIbGibsToStore(ibGibs) {
        const lc = `${this.lc}[_putIbGibsToStore]`;
        try {
            if (logalot) {
                console.log(`${lc} starting...`);
            }
            await this.putIbGibsImpl({ ibGibs, addrsAlreadyHave: [] });
        }
        catch (error) {
            console.error(`${lc} ${extractErrorMsg(error)}`);
            throw error;
        }
    }
    async _deleteIbGibsFromStore(addrs) {
        const lc = `${this.lc}[_deleteIbGibsFromStore]`;
        try {
            if (logalot) {
                console.log(`${lc} starting...`);
            }
            for (const addr of addrs) {
                delete this.ibGibs[addr];
            }
        }
        catch (error) {
            console.error(`${lc} ${extractErrorMsg(error)}`);
            throw error;
        }
    }
    async getImpl(arg) {
        const lc = `${this.lc}[${this.getImpl.name}]`;
        const resultData = { optsAddr: getIbGibAddr({ ibGib: arg }), };
        const resultIbGibs = [];
        try {
            if (logalot) {
                console.log(`${lc} starting... (I: 2a2dd19a00f1f892e3b6d1372ab72c23)`);
            }
            const { ibGibAddrs } = arg.data;
            if (!ibGibAddrs) {
                throw new Error(`(UNEXPECTED) arg.data.ibGibAddrs falsy? (E: 33dcc212788221c601bf2258eb1cd523)`);
            }
            let notFoundIbGibAddrs = undefined;
            for (let i = 0; i < ibGibAddrs.length; i++) {
                const addr = ibGibAddrs[i];
                if (Object.keys(this.ibGibs).includes(addr)) {
                    resultIbGibs.push(this.ibGibs[addr]);
                }
                else {
                    if (!notFoundIbGibAddrs) {
                        notFoundIbGibAddrs = [];
                    }
                    notFoundIbGibAddrs.push(addr);
                }
            }
            if (notFoundIbGibAddrs && notFoundIbGibAddrs.length > 0) {
                resultData.addrsNotFound = notFoundIbGibAddrs;
                resultData.success = false;
            }
            else {
                resultData.success = true;
            }
        }
        catch (error) {
            console.error(`${lc} error: ${error.message}`);
            resultData.errors = [error.message];
        }
        finally {
            if (logalot) {
                console.log(`${lc} complete. (I: 2c3aeda2fcd6338b9ab89261b9237a23)`);
            }
        }
        const result = await this.resulty({ resultData, ibGibs: resultIbGibs });
        return result;
    }
    async putImpl(arg) {
        const lc = `${this.lc}[${this.putImpl.name}]`;
        const resultData = { optsAddr: getIbGibAddr({ ibGib: arg }), };
        try {
            const ibGibs = arg.ibGibs || [];
            const addrsAlreadyHave = [];
            await this.putIbGibsImpl({ ibGibs, addrsAlreadyHave });
            if (addrsAlreadyHave.length > 0) {
                resultData.addrsAlreadyHave = addrsAlreadyHave;
                resultData.warnings = (resultData.warnings || []).concat([
                    `${lc} space (${this.ib}) already had addr(s): ${addrsAlreadyHave.join('|')}`,
                    '(W: 7120c8267c2aaf8cad5d2f3850666826)'
                ]);
            }
            resultData.success = true;
        }
        catch (error) {
            console.error(`${lc} error: ${error.message}`);
            resultData.errors = [error.message];
            resultData.success = false;
        }
        const result = await this.resulty({ resultData });
        return result;
    }
    async putIbGibsImpl({ ibGibs, addrsAlreadyHave, }) {
        const lc = `${this.lc}[${this.putIbGibsImpl.name}]`;
        try {
            if (logalot) {
                console.log(`${lc} starting...`);
            }
            if (!ibGibs) {
                throw new Error(`ibGibs required. (E: cd479b15097d45a5bf0c8ca13c9f3487)`);
            }
            if (!addrsAlreadyHave) {
                throw new Error(`addrsAlreadyHave required. (E: 18b2c8eef27bc267c55755e272367e22)`);
            }
            for (let i = 0; i < ibGibs?.length; i++) {
                const ibGib = ibGibs[i];
                const addr = getIbGibAddr({ ibGib });
                if (isMetaStone({ ibGib })) {
                    const metastone = ibGib;
                    if (!metastone.data) {
                        throw new Error(`(UNEXPECTED) ibGib is a metastone, but metastone.data falsy? (E: f3a05815c68821d564cb101821b91326)`);
                    }
                    const { tjpGib } = metastone.data.targetData;
                    if (this.ibGibMetastones[tjpGib]) {
                        // has existing metastones for this timeline/stone
                        if (!Object.keys(this.ibGibMetastones[tjpGib]).includes(addr)) {
                            this.ibGibMetastones[tjpGib][addr] = metastone;
                        }
                        else {
                            addrsAlreadyHave.push(addr);
                        }
                    }
                    else {
                        // no existing metastones for this timeline/stone
                        this.ibGibMetastones[tjpGib] = {
                            [addr]: metastone,
                        };
                    }
                }
                else {
                    if (!Object.keys(this.ibGibs).includes(addr)) {
                        this.ibGibs[addr] = ibGib;
                    }
                    else {
                        addrsAlreadyHave.push(addr);
                    }
                }
            }
        }
        catch (error) {
            console.error(`${lc} ${error.message}`);
            throw error;
        }
        finally {
            if (logalot) {
                console.log(`${lc} complete.`);
            }
        }
    }
    async deleteImpl(arg) {
        const lc = `${this.lc}[${this.deleteImpl.name}]`;
        const resultData = { optsAddr: getIbGibAddr({ ibGib: arg }), };
        try {
            const addrsNotFound = [];
            const addrsDeleted = [];
            const ibGibAddrs = arg.data.ibGibAddrs || [];
            for (let i = 0; i < ibGibAddrs.length; i++) {
                const addr = ibGibAddrs[i];
                if (Object.keys(this.ibGibs).includes(addr)) {
                    delete this.ibGibs[addr];
                    addrsDeleted.push(addr);
                }
                else {
                    addrsNotFound.push(addr);
                }
            }
            if (addrsNotFound.length > 0) {
                resultData.addrsNotFound = addrsNotFound.concat();
                const warningMsg = `${lc} some addrs (${addrsNotFound.length}) not found: ${addrsNotFound}`;
                resultData.warnings = (resultData.warnings || []).concat([warningMsg]);
            }
            resultData.success = true;
            resultData.addrs = addrsDeleted.concat();
        }
        catch (error) {
            console.error(`${lc} error: ${error.message}`);
            resultData.errors = [error.message];
            resultData.success = false;
        }
        try {
            const result = await this.resulty({ resultData });
            return result;
        }
        catch (error) {
            console.error(`${lc} error forming result ibGib. error: ${error.message}`);
            throw error;
        }
    }
    async getAddrsImpl(arg) {
        const lc = `${this.lc}[${this.getAddrs.name}]`;
        const resultData = { optsAddr: getIbGibAddr({ ibGib: arg }), };
        try {
            resultData.addrs = Object.keys(this.ibGibs).concat();
            resultData.success = true;
        }
        catch (error) {
            console.error(`${lc} error: ${error.message}`);
            resultData.errors = [error.message];
            resultData.success = false;
        }
        const result = await this.resulty({ resultData });
        return result;
    }
    async getLatestAddrsImpl(arg) {
        const lc = `${this.lc}[${this.getLatestAddrsImpl.name}]`;
        if (logalot) {
            console.log(`${lc} starting... (I: 913548fe045270432ea96f2a59ca6625)`);
        }
        const resultData = { optsAddr: getIbGibAddr({ ibGib: arg }), };
        try {
            if (!arg.data) {
                throw new Error(`(UNEXPECTED) !arg.data? (E: 60869288f3deeff5d1dd93be5f4b8624)`);
            }
            if (!arg.data.ibGibAddrs) {
                throw new Error(`(UNEXPECTED) !arg.data.ibGibAddrs? (E: d62cfac462daacc5b2f50c7c3ae45d24)`);
            }
            const latestAddrsMap = {};
            // #region new impl with metastones
            for (const localAddr of arg.data.ibGibAddrs) {
                if (isMetaStone({ addr: localAddr })) {
                    if (logalot) {
                        console.log(`${lc} localAddr not found: ${localAddr} (I: 12c7668bbdb8e4a86ceb5f455eb00826)`);
                    }
                    if (this.metastoneAddrs.includes(localAddr)) {
                        latestAddrsMap[localAddr] = localAddr;
                    }
                    else {
                        if (logalot) {
                            console.log(`${lc} metastone addr NOT found...what are we getting latest on metastone anyway? (I: 0e71b8a9234fcc93b8259578eb491626)`);
                        }
                        latestAddrsMap[localAddr] = null;
                    }
                    continue;
                }
                const localIbGib = this.ibGibs[localAddr];
                if (!localIbGib) {
                    if (logalot) {
                        console.log(`${lc} localAddr not found: ${localAddr} (I: 12c7668bbdb8e4a86ceb5f455eb00826)`);
                    }
                    latestAddrsMap[localAddr] = null; // or handle as error/not found
                    continue;
                }
                // we have the ibgib, now see if we have any metastones for it.
                const tjpAddr = getTjpAddr({ ibGib: localIbGib, defaultIfNone: 'incomingAddr' }) ??
                    getIbGibAddr({ ibGib: localIbGib });
                const { gib: tjpGib } = getIbAndGib({ ibGibAddr: tjpAddr });
                // examine metastones
                const metastoneMap = this.ibGibMetastones[tjpGib];
                if (!metastoneMap) {
                    // no metastones for this, so there is no latest
                    latestAddrsMap[localAddr] = localAddr;
                    continue;
                }
                // we DO have metastone(s) for this timeline/stone, so analyze
                // these metastones and get the latest according to them
                const metaStoneAddrs = Object.keys(metastoneMap);
                if (metaStoneAddrs.length === 0) {
                    throw new Error(`(UNEXPECTED) we have a metastoneMap but no addrs? (E: 82a448407c08585f685a9b2543923826)`);
                }
                const metaStoneAddrsAndIbInfos = metaStoneAddrs
                    .map(xAddr => [xAddr, getIbAndGib({ ibGibAddr: xAddr }).ib])
                    .map(([xAddr, metaStoneIb]) => [xAddr, parseMetaStoneIb({ ib: metaStoneIb })]);
                /**
                 * sort mutates the actual array (shuffle sort I think), but
                 * we're storing it in a different variable name to be more
                 * explicit.
                 */
                const metaStoneAddrsAndIbInfos_descending = metaStoneAddrsAndIbInfos.sort((a, b) => {
                    const [_aAddr, aInfo] = a;
                    const [_bAddr, bInfo] = b;
                    // we want the highest n, with tiebreaker going to
                    // timestampInTicks. if that's the same also, then what are we
                    // quibbling about?
                    if (aInfo.n > bInfo.n) {
                        return -1;
                    }
                    else if (aInfo.n < bInfo.n) {
                        return 1;
                    }
                    else if (aInfo.timestampInTicks > bInfo.timestampInTicks) {
                        return -1;
                    }
                    else if (aInfo.timestampInTicks < bInfo.timestampInTicks) {
                        return 1;
                    }
                    else {
                        // neither discriminator is different.
                        return 0;
                    }
                });
                if (logalot) {
                    console.log(`${lc} console.dir(metaStoneAddrsAndIbInfos_descending)... (I: 5ce425f199283e2185a2cc0801264826)`);
                    console.dir(metaStoneAddrsAndIbInfos_descending);
                }
                // since we sorted into a descending order, the latest is the very
                // first item.  and we have already guaranteed that there is at
                // least 1 in the array.
                if (metaStoneAddrsAndIbInfos_descending.length === 0) {
                    throw new Error(`(UNEXPECTED) metaStoneAddrsAndIbInfos_descending is empty? earlier in the function there should have been a check. did getMetaStoneAddrs return a populated list but no stones were found? (E: 63c035ebed77741f2330c7a625823f23)`);
                }
                const [latestMetaStoneAddr, latestMetaStoneInfo] = metaStoneAddrsAndIbInfos_descending[0];
                if (logalot) {
                    console.log(`${lc} [latestMetaStoneAddr, latestMetaStoneInfo]: ${[latestMetaStoneAddr, latestMetaStoneInfo]}  (I: 1307ca46b4abd62c7a30fe87c08fa923)`);
                }
                let latestMetaStoneIbGib;
                latestMetaStoneIbGib = metastoneMap[latestMetaStoneAddr];
                // latestMetaStoneIbGib.rel8ns ensured via validation at this point
                const latestMetaStoneRel8ns = latestMetaStoneIbGib.rel8ns;
                /**
                 * this is accurate as the punctiliar address that corresponds to
                 * the metastone.
                 *
                 * atow (11/2023) interface of rel8ns
                 * [META_STONE_TARGET_REL8N_NAME]: IbGibAddr[];
                 * [META_STONE_TARGET_TJP_REL8N_NAME]?: IbGibAddr[];
                 */
                const latestAddr = latestMetaStoneRel8ns[META_STONE_TARGET_REL8N_NAME].at(0);
                if (!latestAddr) {
                    throw new Error(`metastone passed validation but latestMetaStoneRel8ns[META_STONE_TARGET_REL8N_NAME].at(0) is empty? (E: c188ec0089ad86efe4d925c118599d23)`);
                }
                latestAddrsMap[localAddr] = latestAddr;
            }
            // #region new impl with metastones
            // #region old inefficient no metastones
            // // wildly inefficient with a decent number of ibgibs
            // // get all ibgibs in the space and group them by their tjp address
            // const ibGibsInSpace = Object.values(this.ibGibs);
            // const ibGibsInSpaceByTjp = groupBy({ items: ibGibsInSpace, keyFn: x => getTjpAddr({ ibGib: x })! });
            // if (logalot) { console.log(`${lc} ibGibsInSpaceByTjp: ${pretty(ibGibsInSpaceByTjp)} (I: af9f88985b96822b68ad4928eb6f6a25)`); }
            // // iterate over each address we're looking for
            // for (const localAddr of arg.data.ibGibAddrs) {
            //     const localIbGib = this.ibGibs[localAddr];
            //     if (!localIbGib) {
            //         latestAddrsMap[localAddr] = null; // or handle as error/not found
            //         continue;
            //     }
            //     const tjpAddr = getTjpAddr({ ibGib: localIbGib });
            //     if (tjpAddr && ibGibsInSpaceByTjp[tjpAddr]) {
            //         // if we have a timeline for this tjp, find the latest
            //         const timeline = ibGibsInSpaceByTjp[tjpAddr];
            //         if (timeline.some(ibGib => ibGib.data?.n === undefined)) {
            //             const filtered = timeline.filter(ibGib => ibGib.data?.n === undefined);
            //             console.warn(`${lc} timeline includes ibgibs with ibGib.data?.n === undefined.\nfiltered:\n${filtered.map(x => pretty(x)).join('\n')}}(W: 7360a8e81b05accf244fb4b86e796325)`);
            //         }
            //         // sort mutates array in place
            //         timeline.sort((a, b) => (a.data?.n ?? -1) > (b.data?.n ?? -1) ? 1 : -1); // sorts ascending, e.g., 0,1,2...[Highest]
            //         // last one is the latest
            //         let latestInTimeline = timeline.at(-1);
            //         if (latestInTimeline) {
            //             latestAddrsMap[localAddr] = getIbGibAddr({ ibGib: latestInTimeline });
            //         } else {
            //             latestAddrsMap[localAddr] = null;
            //         }
            //     } else {
            //         // if it has no tjp, it is its own latest if it exists
            //         latestAddrsMap[localAddr] = this.ibGibs[localAddr] ? localAddr : null;
            //     }
            // }
            // #endregion old inefficient no metastones
            resultData.latestAddrsMap = latestAddrsMap;
            resultData.success = true;
        }
        catch (error) {
            const emsg = `${lc} ${extractErrorMsg(error)}`;
            console.error(emsg);
            resultData.errors = [emsg];
        }
        try {
            let result = await this.resulty({ resultData });
            return result;
        }
        catch (error) {
            console.error(`${lc}[resulty] ${extractErrorMsg(error)}`);
            throw error;
        }
        finally {
            if (logalot) {
                console.log(`${lc} complete. (I: 913548fe045270432ea96f2a59ca6625)`);
            }
        }
    }
    /**
     * Performs a naive `exists: boolean` or `includes: boolean` analog.
     *
     * If all of the addresses are found, will result in `success` and `can` being `true`.
     *
     * Else, `can` will be falsy, and `addrsNotFound` will be populated with all/some of
     * the queried addresses.
     *
     * ## notes
     *
     * This does not take authorization into account in any way. it's a simple, naive in-memory
     * storage ibGib witness.
     *
     * @returns result ibGib whose primary value is `can`
     */
    async canGetImpl(arg) {
        const lc = `${this.lc}[${this.canGetImpl.name}]`;
        const resultData = { optsAddr: getIbGibAddr({ ibGib: arg }), };
        try {
            const { ibGibAddrs } = arg.data;
            if (!ibGibAddrs) {
                throw new Error(`(UNEXPECTED) arg.data.ibGibAddrs falsy? (E: d94c64744037ca443589fca71e121123)`);
            }
            let notFoundIbGibAddrs = undefined;
            for (let i = 0; i < ibGibAddrs.length; i++) {
                const addr = ibGibAddrs[i];
                if (!Object.keys(this.ibGibs).includes(addr)) {
                    if (!notFoundIbGibAddrs) {
                        notFoundIbGibAddrs = [];
                    }
                    notFoundIbGibAddrs.push(addr);
                }
            }
            resultData.success = true;
            if (notFoundIbGibAddrs && notFoundIbGibAddrs.length > 0) {
                resultData.addrsNotFound = notFoundIbGibAddrs;
                resultData.can = false;
            }
            else {
                resultData.can = true;
            }
        }
        catch (error) {
            console.error(`${lc} error: ${error.message}`);
            resultData.errors = [error.message];
        }
        const result = await this.resulty({ resultData });
        return result;
    }
    async canPutImpl(arg) {
        const lc = `${this.lc}[${this.canPutImpl.name}]`;
        const resultData = { optsAddr: getIbGibAddr({ ibGib: arg }), };
        try {
            const ibGibs = arg.ibGibs || [];
            const addrsAlreadyHave = [];
            for (let i = 0; i < ibGibs?.length; i++) {
                const ibGib = ibGibs[i];
                const addr = getIbGibAddr({ ibGib });
                if (Object.keys(this.ibGibs).includes(addr)) {
                    addrsAlreadyHave.push(addr);
                }
            }
            resultData.success = true;
            if (addrsAlreadyHave.length > 0) {
                resultData.addrsAlreadyHave = addrsAlreadyHave;
                resultData.warnings = (resultData.warnings || []).concat([`${lc} already have addr(s).`]);
            }
            resultData.can = ibGibs.length > addrsAlreadyHave.length;
        }
        catch (error) {
            console.error(`${lc} error: ${error.message}`);
            resultData.errors = [error.message];
        }
        const result = await this.resulty({ resultData });
        return result;
    }
    async canDeleteImpl(arg) {
        const lc = `${this.lc}[${this.canDeleteImpl.name}]`;
        const resultData = { optsAddr: getIbGibAddr({ ibGib: arg }), };
        try {
            throw new Error('not implemented');
        }
        catch (error) {
            console.error(`${lc} error: ${error.message}`);
            resultData.errors = [error.message];
            resultData.success = false;
        }
        try {
            const result = await this.resulty({ resultData });
            return result;
        }
        catch (error) {
            console.error(`${lc} error forming result ibGib. error: ${error.message}`);
            throw error;
        }
    }
    async persistOptsAndResultIbGibs({ arg, result }) {
        const lc = `${this.lc}[${this.persistOptsAndResultIbGibs.name}]`;
        try {
            if (logalot || this.data?.trace) {
                console.log(`${lc} starting...`);
            }
            if (logalot || this.data?.trace) {
                console.log(`${lc} doing arg?.data?.cmd: ${arg?.data?.cmd}, result?.data?.success: ${result?.data?.success}`);
            }
            let argValidationErrors = await validateIbGibIntrinsically({ ibGib: arg });
            if (argValidationErrors && argValidationErrors.length > 0) {
                throw new Error(`invalid arg. cannot persist. (E: 015d38de71a3407f9d77fc4ed3404bf0)`);
            }
            let resultValidationErrors = result ?
                await validateIbGibIntrinsically({ ibGib: result }) :
                null;
            if (resultValidationErrors && resultValidationErrors.length > 0) {
                throw new Error(`invalid arg. cannot persist. (E: 015d38de71a3407f9d77fc4ed3404bf0)`);
            }
            const ibGibs = result ? [arg, result] : [arg];
            await this.putIbGibsImpl({ ibGibs: ibGibs, addrsAlreadyHave: [] });
        }
        catch (error) {
            console.error(`${lc} ${error.message}`);
            // this is a best effort storage, so we do not rethrow
            // throw error;
        }
        finally {
            if (logalot || this.data?.trace) {
                console.log(`${lc} complete.`);
            }
        }
    }
}
//# sourceMappingURL=inner-space-v1.mjs.map