const MODULE_ID = "augur-nexus";

export class RegionChronicleIndex {
    static #dirty = true;
    static #byEntityId = new Map();

    static invalidate() {
        this.#dirty = true;
    }

    static getEvents(entityId) {
        const id = String(entityId || "").trim();
        if (!id) return [];
        this.#ensureCurrent();
        return foundry.utils.deepClone(this.#byEntityId.get(id) || []);
    }

    static hasEvents(entityId) {
        const id = String(entityId || "").trim();
        if (!id) return false;
        this.#ensureCurrent();
        return (this.#byEntityId.get(id) || []).length > 0;
    }

    static #ensureCurrent() {
        if (!this.#dirty) return;
        const byEntityId = new Map();
        for (const entry of game.journal?.contents || []) {
            if (entry.flags?.[MODULE_ID]?.regionChronicle !== true) continue;
            const chronicle = entry.flags?.[MODULE_ID]?.chronicle;
            if (!chronicle || !Array.isArray(chronicle.events)) continue;
            for (const event of chronicle.events) {
                const seen = new Set();
                for (const participant of event?.participants || []) {
                    const entityId = String(participant?.id || participant?.entityId || "").trim();
                    if (!entityId || seen.has(entityId)) continue;
                    seen.add(entityId);
                    if (!byEntityId.has(entityId)) byEntityId.set(entityId, []);
                    byEntityId.get(entityId).push({
                        entryId: entry.id,
                        sceneId: String(chronicle.sceneId || entry.flags?.[MODULE_ID]?.sceneId || ""),
                        sceneName: String(chronicle.sceneName || entry.flags?.[MODULE_ID]?.sceneName || "Unnamed Region"),
                        runId: String(chronicle.runId || entry.flags?.[MODULE_ID]?.runId || ""),
                        event: foundry.utils.deepClone(event)
                    });
                }
            }
        }
        this.#byEntityId = byEntityId;
        this.#dirty = false;
    }
}