// import { Subscription } from 'rxjs/index.js';
// import { filter } from 'rxjs/operators';
import { delay, extractErrorMsg, getSaferSubstring, pretty, } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs';
import { getIbGibAddr } from '@ibgib/ts-gib/dist/helper.mjs';
import { rel8 } from '@ibgib/ts-gib/dist/V1/transforms/rel8.mjs';
import { getGibInfo } from '@ibgib/ts-gib/dist/V1/index.mjs';
import { validateIbGibIntrinsically } from '@ibgib/ts-gib/dist/V1/validate-helper.mjs';
import { GLOBAL_LOG_A_LOT } from '../../core-constants.mjs';
import { WitnessBase_V1, } from '../witness-base-v1.mjs';
import { createCommentIbGib, } from '../../common/comment/comment-helper.mjs';
import { getLatestAddrs } from '../space/space-helper.mjs';
import { getTjpAddr } from '../../common/other/ibgib-helper.mjs';
import { extractObsErrMsg, fnObs } from '../../common/pubsub/observer/observer-helper.mjs';
const logalot = GLOBAL_LOG_A_LOT;
/**
 * ## distinguishing characteristics of robbots
 *
 * With any witness ibgib, we are concerned with interpreting an incoming
 * arg ibgib and producing at least one result ibgib. Most often, there will
 * be additional ibgibs created, either creating "new" ibgibs via `fork`
 * transforms, or changing existing ibgibs through `mut8` and `rel8`
 * transforms. And almost always these will be persisted in at least
 * one space.
 *
 * But Robbots in particular are meant to be increasingly adaptable over time.
 *
 * This results in a couple of notes:
 *
 * 1. They should be able to handle any incoming ibgib, including primitives.
 * 2. If they are learning robbots, then they will mutate internally at some rate.
 * 3. Often robbots' output ibgib(s) will be intended for others'
 *    consumption, in service of others - be they humans or other
 *    biologically living organisms, other robbots or even later versions of
 *    themselves.
 *
 * So for example, one of the simplest robbots is one which simply echos the
 * incoming ibgib arg.

 * ## architecture
 *
 * At the base, any robbot should be able to handle any incoming ibgib.  This is
 * in contrast to, e.g., a Space, which is more rigid in design.
 *
 * Certainly there are robbot's who will be more rigid, but this will be an
 * abstract class on top of this one, and all robbots should be able to react to
 * all incoming ibgibs.
 *
 * Output will default to a simple ok^gib or (ROOT) ib^gib primitive...perhaps
 * we'll go with ack^gib, but whatever it is, it's just an acknowledgement of
 * input received.  (I'll put it in the constants file).
 *
 * Side effects should occur in a parallel execution thread, which ideally would
 * work in a completely parallel execution context (like a service worker). But
 * then we have to deal with race conditions and the real solution there is to
 * abstract to the robbot having its own space and the synchronization happening
 * exactly like any other sync space.
 *
 * For now, we'll spin off a promise with some intermittent `await delay`
 * calls if they end up called for, effectively the equivalent of the
 * old-fashioned "ProcessMessages/DoEvents" hack.
 */
export class WitnessWithContextBase_V1 extends WitnessBase_V1 {
    /**
     * Log context for convenience with logging. (Ignore if you don't want to use this.)
     *
     * Often used in conjunction with `logalot`.
     */
    lc = `[${WitnessWithContextBase_V1.name}]`;
    /**
     * Reference to the local ibgibs service, which is one way at getting at the
     * local user space.
     *
     * todo: refactor this to `metaspace` after we have completed majority of refactor/breakout from mvp
     */
    metaspace;
    _contextChangesSubscription;
    _currentWorkingContextIbGib;
    /**
     * when we get an update to the context, we want to know what the _new_
     * children are in order to interpret comments from the user that may be
     * directed at us.
     *
     * So we will get an initial snapshot of children that we will diff against.
     * We could go via the dna, but ultimately a diff is what is needed.
     */
    _currentWorkingContextIbGib_PriorChildrenAddrs = [];
    _updatingContext = false;
    constructor(initialData, initialRel8ns) {
        super(initialData, initialRel8ns);
        this.initialized = this.initialize();
    }
    async initialize() {
        const lc = `${this.lc}[${this.initialize.name}]`;
        try {
            if (logalot) {
                console.log(`${lc} starting... (I: f0e65ab0f80046a59668ddfbf9f47a4a5)`);
            }
            await super.initialize();
            // await this.initialize_semanticHandlers();
            // await this.initialize_lex();
        }
        catch (error) {
            console.error(`${lc} ${extractErrorMsg(error)}`);
        }
        finally {
            if (logalot) {
                console.log(`${lc} complete.`);
            }
        }
    }
    async loadNewerSelfIfAvailable() {
        const lc = `${this.lc}[${this.loadNewerSelfIfAvailable.name}]`;
        try {
            if (logalot) {
                console.log(`${lc} starting... (I: 94755c3131f4dfa12d20fa38e2926522)`);
            }
            if (this.metaspace) {
                // check for newer version of self locally before executing
                const thisAddr = getIbGibAddr({ ibGib: this });
                const latestAddr = await this.metaspace.getLatestAddr({ ibGib: this });
                if (latestAddr && latestAddr !== thisAddr) {
                    // this has a newer ibgib in its timeline
                    let resGet = await this.metaspace.get({ addr: latestAddr });
                    if (!resGet || !resGet?.success || (resGet?.ibGibs ?? []).length === 0) {
                        throw new Error(`could not get newer ibgib in timeline (E: 15fa346c8ac17edb96e4b0870104c122)`);
                    }
                    await this.loadIbGibDto(resGet.ibGibs[0]);
                    const validationErrors = await this.validateThis();
                    if (validationErrors?.length > 0) {
                        throw new Error(`validationErrors when loading newer version: ${pretty(validationErrors)} (E: 0d9f0684a1ff6af44e20a57130e3ac22)`);
                    }
                }
            }
            else {
                console.warn(`${lc} this.metaspace undefined (W: 44cc5bf1b14b4695b8de4c589787be06)`);
            }
        }
        catch (error) {
            console.error(`${lc} ${extractErrorMsg(error)}`);
            throw error;
        }
        finally {
            if (logalot) {
                console.log(`${lc} complete.`);
            }
        }
    }
    /**
     * By default, this...
     *
     * * performs the raw {@link rel8} transform to the given `ibGib`.
     * * persists the new ibgib's transform result in the given space.
     * * registers the newer version of this robbot ibgib with the ibgibs svc.
     *
     * @see {@link ibGibs}
     * @see {@link rel8nName}
     * @see {@link metaspace}
     * @see {@link space}
     *
     * ## notes
     *
     * * If there is no given `space`, then we will use the `metaspace` to get
     *   the local user space. If none, then we skip persistence.
     * * If there is no `metaspace`, we won't register the new ibgibs locally.
     */
    async rel8To({ ibGibs, rel8nName, linked, metaspace,
    // space,
     }) {
        const lc = `${this.lc}[${this.rel8To.name}]`;
        try {
            if (logalot) {
                console.log(`${lc} starting...`);
            }
            // #region initialize, validate args and this
            if ((ibGibs ?? []).length === 0) {
                throw new Error(`ibGibs required (E: 2fd13de0f025b170885bede4d7a50922)`);
            }
            rel8nName = rel8nName || this.data?.defaultRel8nName;
            if (!rel8nName) {
                throw new Error(`rel8nName required either as an arg or in this.data.defaultRel8nName (E: 43ab8ae63694a2a82cd8a70ed6b6b522)`);
            }
            const thisValidationErrors = await this.validateThis();
            if (thisValidationErrors?.length > 0) {
                throw new Error(`this is an invalid ibGib. thisValidationErrors: ${thisValidationErrors.join('|')} (E: 8f08716866cd13bf254222ee9e6a6722)`);
            }
            metaspace = metaspace ?? this.metaspace;
            if (!metaspace) {
                // if (this.metaspace) {
                //     if (logalot) { console.log(`${lc} metaspace arg falsy, but we have a reference on this object, which we will use. (I: ee0d39a47ee8aee8ffd797721fea4322)`); }
                //     metaspace = this.metaspace;
                // }
                throw new Error(`either metaspace or this.metaspace required (E: b5f9453ddb394a2b76dec74c7304df22)`);
            }
            // if (!space) {
            //     if (metaspace) {
            //         if (logalot) { console.log(`${lc} space arg falsy, but metaspace truthy, so we'll use metaspace's local user space for persistence. (I: 37a4b4c1406556cb23831671755b0d22)`); }
            //         space = await metaspace.getLocalUserSpace({ lock: true });
            //     }
            // }
            // if (!space) { throw new Error(`(UNEXPECTED) space required and metaspace couldn't get it? (E: a3b9f9b72f6f6f18883199a19d38c622)`); }
            // #endregion initialize, validate args and this
            // we want to rel8 only to the ibGibs whose timelines we're not
            // already related to. So we look to see if we already have the tjpGib
            // per our rel8nName.
            // if (!this.rel8ns) { this.rel8ns = {} as any };
            const alreadyRel8dAddrs = this.rel8ns ? this.rel8ns[rel8nName] ?? [] : [];
            const alreadyRel8dTjpGibs = alreadyRel8dAddrs.map(x => getGibInfo({ ibGibAddr: x }).tjpGib);
            const ibGibsNotYetRel8dByTjp = ibGibs.filter(x => {
                const tjpGib = getGibInfo({ ibGibAddr: getIbGibAddr({ ibGib: x }) }).tjpGib;
                return !alreadyRel8dTjpGibs.includes(tjpGib);
            });
            if (ibGibsNotYetRel8dByTjp.length === 0) {
                if (logalot) {
                    console.log(`${lc} already rel8d to all incoming ibGib(s) via tjp. (I: 5e9d94a98ba262f146c0c0b765157922)`);
                }
                return; /* <<<< returns early */
            }
            // perform the raw ibgib rel8 transform
            const addrs = ibGibsNotYetRel8dByTjp.map(x => getIbGibAddr({ ibGib: x }));
            const resNewThis = await rel8({
                src: this.toIbGibDto(),
                rel8nsToAddByAddr: { [rel8nName]: addrs },
                linkedRel8ns: linked ? ["past", "ancestor", rel8nName] : ["past", "ancestor"],
                dna: true,
                nCounter: true,
            });
            const newThisIbGib = resNewThis.newIbGib;
            const newThisValidationErrors = await validateIbGibIntrinsically({ ibGib: newThisIbGib });
            if (newThisValidationErrors?.length ?? 0 > 0) {
                throw new Error(`new this ibgib would have validation errors. aborting. newThisValidationErrors: ${newThisValidationErrors.join('|')} (E: eb816a27156c246c121ef55e37d59322)`);
            }
            // if space is given, perform the persistence
            // if (space) {
            await metaspace.persistTransformResult({ resTransform: resNewThis });
            // } else {
            //     if (logalot) { console.log(`${lc} space falsy, skipping persistence (I: 90aa3553e92ad1d02bce61f83648ea22)`); }
            // }
            // update this witness' primary ibGib properties (ib, gib, data, rel8ns).
            //   override `loadIbGibDto` to update secondary/derivative properties
            await this.loadIbGibDto(newThisIbGib);
            // (in the future, need to revisit the ibgibs service to the idea of locality/ies).
            await metaspace.registerNewIbGib({ ibGib: newThisIbGib });
        }
        catch (error) {
            console.error(`${lc} ${extractErrorMsg(error)}`);
            throw error;
        }
        finally {
            if (logalot) {
                console.log(`${lc} complete.`);
            }
        }
    }
    async rel8ToContextIbGib({ ibGibToRel8, ibGibAddrToRel8, contextIbGib, rel8nNames,
    // space,
     }) {
        const lc = `${this.lc}[${this.rel8ToContextIbGib.name}]`;
        try {
            if (!ibGibToRel8 && !ibGibAddrToRel8) {
                throw new Error(`ibGibToRel8 or ibGibAddrToRel8 required (E: 3ee14659fd22355a5ba0e537a477be22)`);
            }
            if (!contextIbGib) {
                throw new Error(`contextIbGib required (E: 85f27c7cbf713704c21084c141cd8822)`);
            }
            if (!this.metaspace) {
                throw new Error(`this.metaspace required (E: 6a38c4274bdefc8d44cafd2d6faaa222)`);
            }
            // space = space ?? await this.metaspace.getLocalUserSpace({ lock: true });
            // if (!space) { throw new Error(`space required (E: 267ad87c148942cda641349df0bbbd22)`); }
            if ((rel8nNames ?? []).length === 0) {
                if (!this.data?.defaultRel8nName) {
                    throw new Error(`either rel8nNames or this.data.defaultRel8nName required (E: a14ab4b3e479d9274c61bc5a30bc2222)`);
                }
                rel8nNames = [this.data.defaultRel8nName];
            }
            // set up the rel8ns to add
            const rel8nsToAddByAddr = {};
            ibGibAddrToRel8 = ibGibAddrToRel8 || getIbGibAddr({ ibGib: ibGibToRel8 });
            rel8nNames.forEach((rel8nName) => { rel8nsToAddByAddr[rel8nName] = [ibGibAddrToRel8]; });
            // perform the rel8 transform and...
            const resRel8ToContext = await rel8({
                src: contextIbGib,
                rel8nsToAddByAddr,
                dna: true,
                nCounter: true
            });
            // ...persist it...
            await this.metaspace.persistTransformResult({ resTransform: resRel8ToContext });
            // ...register the context.
            const { newIbGib: newContext } = resRel8ToContext;
            await this.metaspace.registerNewIbGib({ ibGib: newContext });
        }
        catch (error) {
            console.error(`${lc} ${extractErrorMsg(error)}`);
            throw error;
        }
    }
    async createCommentAndRel8ToContextIbGib({ text, contextIbGib, rel8nName, }) {
        const lc = `${this.lc}[${this.createCommentAndRel8ToContextIbGib.name}]`;
        try {
            if (logalot) {
                console.log(`${lc} starting... (I: c3a005f7d323468a5b4e1b2710901d22)`);
            }
            if (!this.metaspace) {
                throw new Error(`this.metaspace required (E: 5dbb1a7f0ff5469b8ce3cb1be175e521)`);
            }
            // space = space ?? await this.metaspace.getLocalUserSpace({ lock: true });
            // if (!space) { throw new Error(`(UNEXPECTED) space required and wasn't able to get it from metaspace? (E: 7159f9893a66c28a7e09b61384545622)`); }
            let space = await this.metaspace.getLocalUserSpace({ lock: true });
            /** tag this comment with metadata to show it came from this witness */
            let resComment = await createCommentIbGib({ text, addlMetadataText: this.getAddlMetadata(), saveInSpace: true, space });
            // get again to be sure it's the latest space.
            space = await this.metaspace.getLocalUserSpace({ lock: true });
            const commentIbGib = resComment.newIbGib;
            if (!commentIbGib) {
                throw new Error(`(UNEXPECTED) failed to create comment? (E: 6d668f4e55198e654324622eabaac922)`);
            }
            await this.metaspace.registerNewIbGib({ ibGib: commentIbGib });
            await this.rel8ToContextIbGib({ ibGibToRel8: commentIbGib, contextIbGib, rel8nNames: ['comment'] });
            await this.rel8To({
                ibGibs: [commentIbGib],
                rel8nName,
            });
        }
        catch (error) {
            console.error(`${lc} ${extractErrorMsg(error)}`);
            throw error;
        }
        finally {
            if (logalot) {
                console.log(`${lc} complete.`);
            }
        }
    }
    /**
     * I'm abstracting getAddlMetadata and for a robbot witness the first part
     * is atow  "robbot", e.g., * `robbot_classname_id_etc`. So "ThisAtom" is
     * "robbot" for a robbot.
     *
     * override this in descending classes per use case.
     *
     * by default, this returns a safe substring of this.data.classname or "this".
     */
    getThisAtom() {
        return getSaferSubstring({ text: this.data?.classname ?? 'this', length: 16 });
    }
    /**
     * used to help identify when comments are made by descending witnesses.
     *
     * override this with your particular use case's addl metadata.
     *
     * @example atow robbot is: `robbot_${this.data.classname}_${this.data.name}_${this.data.uuid.slice(0, 8)}`;
     *
     * @returns addlmetadata string to be used in comment ib's
     */
    getAddlMetadata() {
        const lc = `${this.lc}[${this.getAddlMetadata.name}]`;
        try {
            if (logalot) {
                console.log(`${lc} starting... (I: 7800732facf3783943fdf1b2423b0c22)`);
            }
            if (!this.data) {
                throw new Error(`(UNEXPECTED) this.data falsy? (E: 7cb044b39b2b8e31f363f3b82f256323)`);
            }
            const atom = this.getThisAtom();
            if (!atom) {
                throw new Error(`(UNEXPECTED) atom couldn't be gotten? (E: b260de391356e04abd334e0cd8b09123)`);
            }
            if (atom.includes(' ')) {
                throw new Error(`(UNEXPECTED) atom contains space? (E: 574d088eea13d3afe5fcd2999ab6b423)`);
            }
            const classnameIsh = this.data.classname?.replace(/[_]/mg, '') || undefined;
            const nameIsh = this.data.name?.slice(0, 8).replace(/[__]/mg, '') || undefined;
            const idIsh = this.data.uuid?.slice(0, 8) || undefined;
            const addlMetadataText = `${atom}_${classnameIsh}_${nameIsh}_${idIsh}`;
            if (logalot) {
                console.log(`${lc} addlMetadataText: ${addlMetadataText} (I: 53c0044671dc99fb75635367d2e63c22)`);
            }
            return addlMetadataText;
        }
        catch (error) {
            console.error(`${lc} ${extractErrorMsg(error)}`);
            throw error;
        }
        finally {
            if (logalot) {
                console.log(`${lc} complete.`);
            }
        }
    }
    /**
     * I originally created this just to extract the context from the arg, but
     * I'm reusing it to get the latest context from the addr alone.
     */
    async getContextIbGibFromArgOrAddr({ arg, addr, latest, }) {
        const lc = `${this.lc}[${this.getContextIbGibFromArgOrAddr.name}]`;
        try {
            if (logalot) {
                console.log(`${lc} starting... (I: c13f7cb92133984048f606075efb8a22)`);
            }
            let contextIbGib;
            if (!arg && !addr) {
                throw new Error(`either arg or addr required. (E: 3f647b65742242fd9ba878521acf7c22)`);
            }
            if (!this.metaspace) {
                throw new Error(`(UNEXPECTED) this.metaspace required (E: f0046290b0d66d28c4bbbf83d9d9f523)`);
            }
            if (arg) {
                if ((arg.ibGibs ?? []).length === 0) {
                    throw new Error(`(UNEXPECTED) invalid arg? no context ibgib on arg (E: 89997eb4bdeb3885bee9de5d33ee0f22)`);
                }
                if ((arg.ibGibs ?? []).length !== 1) {
                    throw new Error(`(UNEXPECTED) invalid arg? only expected one ibgib on arg.ibGibs (E: 1a1498af668740fe9439f4953a74ea8a)`);
                }
                contextIbGib = arg.ibGibs[0];
            }
            else {
                // addr provided
                const resGet = await this.metaspace.get({ addr });
                if (!resGet.success || resGet.ibGibs?.length !== 1) {
                    throw new Error(`could not get context addr (${addr}) (E: 834492313512a45b23a7bebacdc48122)`);
                }
                contextIbGib = resGet.ibGibs[0];
            }
            if (latest) {
                const resLatestAddr = await this.metaspace.getLatestAddr({ ibGib: contextIbGib });
                if (resLatestAddr !== getIbGibAddr({ ibGib: contextIbGib })) {
                    const resGet = await this.metaspace.get({ addr: resLatestAddr });
                    if (resGet.success && resGet.ibGibs?.length === 1) {
                        contextIbGib = resGet.ibGibs[0];
                    }
                    else {
                        throw new Error(`unable to get resLatestAddr (${resLatestAddr}) (E: ce1e1297743e9a16c8f082321e52a122)`);
                    }
                }
            }
            return contextIbGib;
        }
        catch (error) {
            console.error(`${lc} ${extractErrorMsg(error)}`);
            throw error;
        }
        finally {
            if (logalot) {
                console.log(`${lc} complete.`);
            }
        }
    }
    /**
     * The context is the ibgib where we are interacting with the user(s).
     *
     * When we initialize, we are setting state on this witness as well as
     * subscribing to the context ibgib's updates in `this.metaspace`.
     *
     * if we already have a context, then this will check the new incoming
     * context against it.  If it's the same timeline, then this won't do
     * anything. Otherwise, it will finalize the previous context.
     */
    async initializeContext({ arg, contextIbGib, rel8nName, }) {
        const lc = `${this.lc}[${this.initializeContext.name}]`;
        try {
            if (logalot) {
                console.log(`${lc} starting... (I: d93429c85b0a494388f66fba3eece922)`);
            }
            if (!this.metaspace) {
                throw new Error(`this.metaspace (metaspace) required. set this before using this witness. (E: 67db388a0223bf813b40accd9941ad23)`);
            }
            if (arg && contextIbGib) {
                console.warn(`${lc} both arg and contextIbGib provided. using raw contextIbGib (W: d6d723ad7fb942079833c40647aecd22)`);
            }
            // get context from arg just to compare the tjp's so we don't need
            // the latest at this point
            const incomingContext_NotLatest = contextIbGib ?? await this.getContextIbGibFromArgOrAddr({ arg, latest: false });
            if (this._currentWorkingContextIbGib) {
                let currentTjpAddr = getTjpAddr({ ibGib: this._currentWorkingContextIbGib });
                const incomingTjpAddr = getTjpAddr({ ibGib: incomingContext_NotLatest });
                if (currentTjpAddr === incomingTjpAddr) {
                    if (logalot) {
                        console.warn(`${lc} initializing context but it's the same timeline (${currentTjpAddr}). (W: 7609f8f51172443183e0c93ad52bfe56)`);
                    }
                    return;
                }
                else {
                    await this.finalizeContext({ arg });
                }
            }
            /** used both now and when context ibgib is updated via observable */
            const updatePriorChildren = () => {
                this._currentWorkingContextIbGib_PriorChildrenAddrs = [
                    ...this._currentWorkingContextIbGib?.rel8ns?.comment ?? [],
                    ...this._currentWorkingContextIbGib?.rel8ns?.pic ?? [],
                    ...this._currentWorkingContextIbGib?.rel8ns?.link ?? [],
                ];
            };
            // set the props
            this._currentWorkingContextIbGib = contextIbGib ?
                await this.getContextIbGibFromArgOrAddr({
                    addr: getIbGibAddr({ ibGib: contextIbGib }),
                    latest: true
                }) :
                await this.getContextIbGibFromArgOrAddr({ arg, latest: true });
            updatePriorChildren();
            // subscribe to context ibgib updates
            const contextTjpAddr = getTjpAddr({ ibGib: this._currentWorkingContextIbGib });
            if (!this.metaspace) {
                throw new Error(`(UNEXPECTED) this.metaspace falsy...not initialized? (E: 6e38bfdc5c2eb5fef884f0183889e823)`);
            }
            if (!this.metaspace.latestObs) {
                throw new Error(`(UNEXPECTED) this.metaspace.latestObs falsy? (E: 831936570c14ed526f9c9ab511929923)`);
            }
            this._contextChangesSubscription =
                await this.metaspace.latestObs
                    // .pipe(
                    //     filter(x => x.tjpAddr === contextTjpAddr)
                    // ).subscribe(async (update: any) => {
                    .subscribe(fnObs({
                    next: async (update) => {
                        const lcNext = `${lc}[latestObs.next]`;
                        // acts like a poor man's `filter` operator on this observerable
                        if (update.tjpAddr !== contextTjpAddr) {
                            return; /* <<<< returns early */
                        }
                        const currentAddr = getIbGibAddr({ ibGib: this._currentWorkingContextIbGib });
                        if (update.latestAddr !== currentAddr) {
                            if (logalot) {
                                console.warn(`${lcNext} checking if new context is actually new...damn getLatestAddr maybe not working in ionic space... argh (W: 3d1a12154dfafb9c96d07e6f75f7a322)`);
                            }
                            if (update.latestIbGib) {
                                let latestN_Supposedly = update.latestIbGib.data?.n ?? -1;
                                let currentN = this._currentWorkingContextIbGib?.data?.n ?? -2;
                                if (latestN_Supposedly <= currentN) {
                                    console.warn(`${lcNext} latestN is not really the latest. latestN_Supposedly: ${latestN_Supposedly}, currentN: ${currentN}. (tjpGib: ${update.tjpAddr}) (W: 6792c9a596c44c03b262614ae79a715e)`);
                                    return; /* <<<< returns early */
                                }
                            }
                            if (logalot) {
                                console.log(`${lcNext} update to context.\ncurrentAddr: ${currentAddr}\nlatestAddr: ${update.latestAddr} (I: d0adcc392e6e974c9917730ebad51322)`);
                            }
                            this._currentWorkingContextIbGib =
                                update.latestIbGib ??
                                    await this.getContextIbGibFromArgOrAddr({ addr: update.latestAddr, latest: false }); // already latest
                            if (!this._updatingContext) {
                                await this.handleContextUpdate({ update });
                                updatePriorChildren();
                            }
                            else {
                                if (logalot) {
                                    console.log(`${lcNext} already updating context (I: f856f9414627ab00418dccd285b55822)`);
                                }
                            }
                        }
                    },
                    error: async (err) => {
                        const lcErr = `${lc}[latestObs.error]`;
                        console.error(`${lcErr} this.metaspace.latestObs error: ${extractObsErrMsg({ err })}. (E: 99df4c42195d46d0a9dbfb06ac45ae00)`);
                    },
                }));
            // rel8 to the context (conversation)
            if (rel8nName) {
                await this.rel8To({
                    ibGibs: [this._currentWorkingContextIbGib],
                    rel8nName,
                });
            }
            // subscribe to receive updates to the context so we can participate
            // in the conversation (i.e. interpret incoming ibgibs like commands
            // if needed)
            // let gibInfo = getGibInfo({ gib: this._currentWorkingContextIbGib.gib });
            // if (gibInfo.tjpGib) {
            //     this.metaspace.latestObs
            //         .subscribe(update => {
            //             if (!update.tjpAddr) { return; /* <<<< returns early */ }
            //             if (getIbAndGib({ ibGibAddr: update.tjpAddr }).gib !== gibInfo.tjpGib) { return; /* <<<< returns early */ }
            //             if (update.latestAddr === getIbGibAddr({ ibGib: this._currentWorkingContextIbGib })) {
            //                 if (logalot) { console.log(`${lc} already have that context... (I: a6e17ec40d620f0bd5b231db39eaa522)`); }
            //                 return; /* <<<< returns early */
            //             }
            //             if (this._updatingContext) {
            //                 if (logalot) { console.log(`${lc} already updating context (I: f856f9414627ab00418dccd285b55822)`); }
            //                 return; /* <<<< returns early */
            //             }
            //             this.handleContextUpdate({ update });
            //         });
            // }
        }
        catch (error) {
            console.error(`${lc} ${extractErrorMsg(error)}`);
            throw error;
        }
        finally {
            if (logalot) {
                console.log(`${lc} complete.`);
            }
        }
    }
    async finalizeContext({ arg, }) {
        const lc = `${this.lc}[${this.finalizeContext.name}]`;
        try {
            if (logalot) {
                console.log(`${lc} starting... (I: dd53dfc745864dd19fde5f209ceb82c8)`);
            }
            let tries = 0;
            const maxTries = 100;
            while (this._updatingContext && tries < maxTries) {
                await delay(100);
                tries++;
                if (tries % 10 === 0) {
                    console.log(`${lc} already updating context and taking a litle while... waiting still. tries: ${tries}/${maxTries} (I: d45ab59af9ea43518432e34ddad95c19)`);
                }
            }
            if (this._updatingContext) {
                console.error(`${lc} previous call to updatingContext took too long. Ignoring flag and finalizing context. (E: 9a2dc4e1923442fa90fbeae72f358acd)`);
            }
            this._updatingContext = true;
            if (this._contextChangesSubscription) {
                await this._contextChangesSubscription.unsubscribe();
                delete this._contextChangesSubscription;
            }
            delete this._currentWorkingContextIbGib;
            throw new Error(`not refactored yet. the proceeding code needs to be introduced in the robbot descending class. (E: 066aa414693672d868dbf953617aab23)`);
            // if (this._currentWorkingContextIbGib) {
            //     await this.createCommentAndRel8ToContextIbGib({
            //         text: await this.getOutputText({ text: 'end of line' }),
            //         contextIbGib: this._currentWorkingContextIbGib,
            //     });
            //     delete this._currentWorkingContextIbGib;
            // }
        }
        catch (error) {
            console.error(`${lc} ${extractErrorMsg(error)}`);
            throw error;
        }
        finally {
            this._updatingContext = false;
            if (logalot) {
                console.log(`${lc} complete.`);
            }
        }
    }
    /**
     * Handles a new ibgib in the current working context.
     *
     * If it originated from the witness itself, then we will ignore it.
     * Otherwise, for robbot witnesses, this is interpreted either as a
     * "command" or something to remember.
     *
     * ## notes
     *
     * If the user says something and we're listening (this is triggered), then
     * it should be either interpreted as a "command" or ignored. I put
     * "command" in quotes because the word is a very short-sighted
     * understanding of the conversational aspect. Or perhaps I speak to the
     * connotations to current belief's regarding robbots and commands.
     *
     * This is complicated by the possibility in the future of multiple robbots
     * being engaged in a conversation within the same context.
     */
    async handleContextUpdate({ update }) {
        const lc = `${this.lc}[${this.handleContextUpdate.name}]`;
        // I don't see this as really being very likely in the near future,
        // but putting in a wait delay in case there are multiple updates
        while (this._updatingContext) {
            console.warn(`${lc} already updating context? delaying... (W: 19d2ebeaaf2340fb91a7d6c717e9cb41)`);
            await delay(1000);
        }
        this._updatingContext = true;
        try {
            if (logalot) {
                console.log(`${lc} starting... (I: 3eeaa40cad49094f125f9f5cd6ff6e22)`);
            }
            // if it's caused by this robbot speaking, then we don't really need
            // it. but if it's from the user, then we want to respond.
            if (logalot) {
                console.log(`${lc} update: (I: ad0abae7de472e3b4d3891ea0b937322)`);
                console.table(update);
            }
            if (!update.latestIbGib) {
                debugger; // before error
                throw new Error(`(UNEXPECTED) update.latestIbGib falsy? (E: e18a048d7e95757238396ddd84748f22)`);
            }
            const newContext = update.latestIbGib;
            const newChildrenIbGibs = await this.getNewChildrenIbGibs({ newContext });
            // should normally be just one (would be very edge casey if not atow)
            // 05/2025 - making it iterate through each new child because this is happening downstream in blank-gib app when dealing with talking with agents within an ibgib context. So the ibgib is added to the context, then the agent hears this and immediately responds within the broadcast handler. now there are two new children by the time we get to this point in code. So this could be brittle, I dunno. Probably need a better pubsub service, but hey, what are ya gonna do when only one fing person is working on something that could be worth so much fing money. but i'm not bitter... ^-^/
            if (newChildrenIbGibs.length === 1) {
                const newChild = newChildrenIbGibs[0];
                // we have a single new child in the context.
                await this.handleNewContextChild({ newChild, });
            }
            else if (newChildrenIbGibs.length > 1) {
                // we multiple new children. iterate
                console.warn(`${lc} (UNEXPECTED) multiple new children in context update. iterating through each one. (W: 02d82a8f755f418d95fa30f0f52ad58e)`);
                for (const newChild of newChildrenIbGibs) {
                    await this.handleNewContextChild({ newChild, });
                }
            }
            else {
                // no new children, so maybe the user deleted something or who knows.
                if (logalot) {
                    console.log(`${lc} no new children in context update. returning early... (I: 31397b04965351ab29bb3f78cb709122)`);
                }
                return; /* <<<< returns early */
            }
        }
        catch (error) {
            console.error(`${lc} ${extractErrorMsg(error)}`);
            throw error;
        }
        finally {
            this._updatingContext = false;
            if (logalot) {
                console.log(`${lc} complete.`);
            }
        }
    }
    async getNewChildrenIbGibs({ newContext }) {
        const lc = `${this.lc}[${this.getNewChildrenIbGibs.name}]`;
        try {
            if (logalot) {
                console.log(`${lc} starting... (I: 1b3d1cf908489087fa3b281f55b9a522)`);
            }
            // get a diff of the new addrs vs. the old addrs.
            /** all of the children addrs of the new context */
            const newContextChildrenAddrs = [
                ...newContext.rel8ns?.comment ?? [],
                ...newContext.rel8ns?.pic ?? [],
                ...newContext.rel8ns?.link ?? [],
            ];
            /** just the new addrs from the context  */
            const newChildrenAddrs = newContextChildrenAddrs.filter(x => !this._currentWorkingContextIbGib_PriorChildrenAddrs.includes(x));
            if (newChildrenAddrs.length === 0) {
                // no new children
                if (logalot) {
                    console.log(`${lc} no new children addrs in newContext. returning early... (I: 8f9c3658c194c472cb1e2bc19d847b22)`);
                }
                return []; /* <<<< returns early */
            }
            // get the latest addrs for those children
            if (!this.metaspace) {
                throw new Error(`this.metaspace falsy. not initialized? (E: 1cc26ca7de7fadcdbaecbd6613350e23)`);
            }
            const space = await this.metaspace.getLocalUserSpace({});
            if (!space) {
                throw new Error(`couldn't get local user space? (E: f118f75e5852fc22bba3a6495beec723)`);
            }
            const resLatestAddrs = await getLatestAddrs({ addrs: newChildrenAddrs, space, });
            const latestAddrs = Object.values(resLatestAddrs?.data?.latestAddrsMap ?? {});
            if (!resLatestAddrs?.data?.success || latestAddrs.length !== newChildrenAddrs.length) {
                throw new Error(`could not get latest addrs. (E: 2e1619e7e2e166696fe8ff78cb02cc22)`);
            }
            // get the addrs' corresponding ibgibs
            if (latestAddrs.some(x => x === null)) {
                // some of the addrs were not found in the space
                throw new Error(`some addrs were not found in the space. (E: 2216d8e5ad7fb600ceb025ed7c90f323)`);
            }
            const resGet = await this.metaspace.get({ addrs: latestAddrs });
            if (!resGet.success || resGet.ibGibs?.length !== newChildrenAddrs.length) {
                throw new Error(`failed to get newChildren with addrs: ${newChildrenAddrs.join('|')}. Error: ${resGet.errorMsg ?? 'unknown error 5737bd0996d5445b8bd80975bedc0d57'} (E: 05722e11350ec6ffffdb5c7d0caa2922)`);
            }
            return resGet.ibGibs;
        }
        catch (error) {
            console.error(`${lc} ${extractErrorMsg(error)}`);
            throw error;
        }
        finally {
            if (logalot) {
                console.log(`${lc} complete.`);
            }
        }
    }
    async handleNewContextChild({ newChild, }) {
        const lc = `${this.lc}[${this.handleNewContextChild.name}]`;
        try {
            throw new Error(`not implemented in base class (E: ea6b2b13d9504d93b33b70191d106084)`);
        }
        catch (error) {
            console.error(`${lc} ${extractErrorMsg(error)}`);
            throw error;
        }
    }
}
// export interface IbGibRobbotAny
//     extends RobbotBase_V1<any, any, any, any, any, any, any, any> {
// }
//# sourceMappingURL=witness-with-context-base-v1.mjs.map