import { EntityComponentTypes, ItemStack, system, world, } from "@minecraft/server";
export const processingNests = new Set();
import { feedMount } from "../C/Feeding";
import { healMount } from "../C/Healing";
import { incubatorClick } from "../C/Incubator";
import { eggClick, spawnBabyMountFromEggWithDelay } from "../C/Egg";
import { nestClick, spawnEggItemAtFromIndex } from "../C/Nest";
import { removeWardLocation } from "../C/Warding";
import { checkIsDay, isSleeping, setWake, setSleep, canSleep } from "../C/Sleeping";
import { mountIDs, mythicMaterialDropMap, nestMountDropMap, spawnEggStatTypes, stickDropMap, } from "../DATA/Config";
import { logNearbyEntityHealth } from "./EntityHitEvent";
import { itemLoreConfig } from "../DATA/LoreConfig";
import { flyingPropId, mountsFlying, mountsFlyingStopped, mountsSpeed } from "../C/Flying";
import { allMountIDs } from "../DATA/Config";
function startMountDebugReport(runs) {
    const mountFlyHistory = new Map();
    const mountAnimHistory = new Map();
    const mountsState = {
        wasJumping: {},
        flying: {},
    };
    function getOrCreate(map, key) {
        let arr = map.get(key);
        if (!arr) {
            arr = [];
            map.set(key, arr);
        }
        return arr;
    }
    function evaluateState(mount, player) {
        const isSleep = mount.getProperty("kicu_mmad:sleep") === 1;
        const rawFlying = mount.getProperty(flyingPropId) || 0;
        const isAmbient = mount.getProperty("kicu_mmad:ambient") === 1;
        const attackType = mount.getProperty("kicu_mmad:attack_type") || 0;
        const onGround = mount.isOnGround;
        const isJump = player.isJumping;
        const vel = mount.getVelocity();
        const groundSpeed = Math.hypot(vel.x, vel.z);
        const isMove = groundSpeed > 0.05;
        const hasRider = Boolean(player.getComponent(EntityComponentTypes.Riding));
        if (isSleep && onGround && attackType === 0)
            return "sleep";
        if ((isMove && !(rawFlying > 0 && hasRider && !isSleep)) || isJump)
            return "walk";
        if (rawFlying > 0 && hasRider && !isSleep && !isJump) {
            switch (rawFlying) {
                case 1:
                    return "fly1";
                case 2:
                    return "fly2";
                case 3:
                    return "fly3";
                case 4:
                    return "fly4";
            }
            return "set_fly";
        }
        if (isAmbient && onGround && !isMove && !isSleep && rawFlying < 1 && attackType === 0) {
            return "ambient";
        }
        return "default";
    }
    let count = 0;
    const intervalId = system.runInterval(() => {
        for (const player of world.getAllPlayers()) {
            const riding = player.getComponent(EntityComponentTypes.Riding);
            if (!riding?.entityRidingOn?.isValid())
                continue;
            const mount = riding.entityRidingOn;
            if (!allMountIDs.includes(mount.typeId))
                continue;
            const prevJump = mountsState.wasJumping[player.id] || false;
            const isJump = player.isJumping;
            let currentFlying = mountsState.flying[mount.id] || 0;
            if (isJump && !prevJump) {
                const angle = player.getRotation().x;
                currentFlying = currentFlying === 0 ? (angle < -30 ? 2 : angle < 10 ? 1 : 4) : 0;
                mount.setProperty(flyingPropId, currentFlying);
            }
            mountsState.wasJumping[player.id] = isJump;
            mountsState.flying[mount.id] = currentFlying;
            const rawFlyingProp = mount.getProperty(flyingPropId) || 0;
            const trackedFlying = mountsFlying[mount.id] ?? 0;
            const stoppedState = mountsFlyingStopped[mount.id] ?? false;
            const trackedSpeed = mountsSpeed[mount.id] ?? 0;
            const animState = evaluateState(mount, player);
            const flyHist = getOrCreate(mountFlyHistory, mount.id);
            if (flyHist[flyHist.length - 1] !== rawFlyingProp) {
                flyHist.push(rawFlyingProp);
            }
            const animHist = getOrCreate(mountAnimHistory, mount.id);
            if (animHist[animHist.length - 1] !== animState) {
                animHist.push(animState);
            }
            const previousState = animHist.length > 1 ? animHist[animHist.length - 2] : null;
            const velocity = mount.getVelocity();
            const computedSpeed = Math.hypot(velocity.x, velocity.z);
            const viewDirection = player.getViewDirection();
            const location = mount.location;
            const report = {
                player: player.name,
                mountId: mount.id,
                typeId: mount.typeId,
                animationState: animState,
                previousAnimationState: previousState,
                animationStateHistory: animHist,
                rawFlyingProp,
                trackedFlying,
                flyStateHistory: flyHist,
                stoppedState,
                computedSpeed: computedSpeed.toFixed(3),
                trackedSpeed: trackedSpeed.toFixed(3),
                onGround: mount.isOnGround,
                viewDirection,
                velocity,
                location,
            };
            console.warn(JSON.stringify(report, null, 2));
        }
        count++;
        if (count >= runs) {
            system.clearRun(intervalId);
            console.warn("==== Mount Debug Report Complete ====");
        }
    }, 40);
}
export function runScriptEventAfterEvent(log) {
    system.afterEvents.scriptEventReceive.subscribe((event) => {
        const { sourceEntity, id, message } = event;
        if (!sourceEntity)
            return;
        const entityLocation = sourceEntity?.location;
        const entityId = sourceEntity?.typeId;
        const eventHandlers = {
            "kicu_mmad:spawn_baby_mount": (entity) => {
                spawnBabyMountFromEggWithDelay(entity);
            },
            "kicu_mmad:mount_death": (entity) => {
                const statName = entity.typeId.replace("kicu_mmad:", "kicu_mmad_") + "_died_stat";
                entity.runCommand(`execute as @s[type=${entity.typeId}] at @p run scoreboard players add "${statName}" "kicu_mmad:jig_computer.addon_stats" 1`);
                entity.triggerEvent("kicu_mmad:set_death");
            },
            "kicu_mmad:debug_mount_tool": (entity) => {
                startMountDebugReport(extractNumber(message));
            },
            "kicu_mmad:debug_health": () => {
                logNearbyEntityHealth(sourceEntity, 5);
            },
            "kicu_mmad:nest_deaths": (entity) => {
                if (!entity.isValid() || processingNests.has(entity.id))
                    return;
                processingNests.add(entity.id);
                try {
                    entity.runCommand("playsound sound.kicu_mmad_destroy_nest @a[r=8] ~ ~ ~ 1 1 1");
                    const f1 = Math.floor(Math.random() * 4) + 1;
                    entity.playAnimation(`animation.kicu_mmad_nest.break${f1}`);
                }
                catch { }
                system.runTimeout(() => {
                    if (!entity.isValid())
                        return;
                    try {
                        entity.runCommand("playsound sound.kicu_mmad_destroy_nest_break @a[r=8] ~ ~ ~ 1 1 1");
                    }
                    catch { }
                    let hasEgg = 0;
                    try {
                        hasEgg = world.scoreboard.getObjective("kicu_mmad_NestHasEgg").getScore(entity);
                    }
                    catch { }
                    if (hasEgg > 0) {
                        spawnEggItemAtFromIndex(hasEgg, entity);
                        entity.triggerEvent("kicu_mmad:set_egg_false");
                        world.scoreboard.getObjective("kicu_mmad_NestHasEgg")?.setScore(entity, 0);
                        return;
                    }
                    const { x, y, z } = entity.location;
                    const dim = world.getDimension(entity.dimension.id);
                    const matCfg = nestMountDropMap[entity.typeId];
                    const stickCfg = stickDropMap[entity.typeId];
                    const mythicCfg = mythicMaterialDropMap[entity.typeId];
                    const hadEggBeforeBreak = entity.getDynamicProperty("kicu_mmad:hadEggBeforeBreak") === true;
                    if (hadEggBeforeBreak) {
                        entity.setDynamicProperty("kicu_mmad:hadEggBeforeBreak", false);
                    }
                    const mythicChance = hadEggBeforeBreak ? 100.0 : mythicCfg.chance;
                    const spawnItems = [];
                    if (Math.random() * 100 <= matCfg.chance) {
                        const cnt = Math.floor(Math.random() * (matCfg.max - matCfg.min + 1)) + matCfg.min;
                        if (cnt > 0) {
                            const it = new ItemStack(matCfg.id, cnt);
                            it.setLore(itemLoreConfig[matCfg.id]);
                            spawnItems.push(it);
                        }
                    }
                    if (stickCfg && Math.random() * 100 <= stickCfg.chance) {
                        const cnt = Math.floor(Math.random() * (stickCfg.max - stickCfg.min + 1)) + stickCfg.min;
                        if (cnt > 0) {
                            spawnItems.push(new ItemStack(stickCfg.id, cnt));
                        }
                    }
                    if (mythicChance === 100.0 || (mythicCfg && Math.random() * 100 <= mythicChance)) {
                        const cnt = Math.floor(Math.random() * (mythicCfg.max - mythicCfg.min + 1)) + mythicCfg.min;
                        if (cnt > 0) {
                            const it = new ItemStack(mythicCfg.id, cnt);
                            it.setLore(itemLoreConfig[mythicCfg.id]);
                            spawnItems.push(it);
                        }
                    }
                    system.runTimeout(() => {
                        if (!entity.isValid())
                            return;
                        const f2 = Math.floor(Math.random() * 4) + 1;
                        try {
                            entity.runCommand(`playanimation @s animation.kicu_mmad_nest.break${f2}`);
                        }
                        catch { }
                        entity.triggerEvent("kicu_mmad:set_death");
                    }, 5);
                    system.runTimeout(() => {
                        if (!entity.isValid())
                            return;
                        for (let i = 0; i < 3; i++) {
                            dim.spawnParticle("kicu_mmad:nest_snatch", { x, y, z });
                        }
                        for (const it of spawnItems) {
                            dim.spawnItem(it, { x, y, z });
                        }
                        dim.playSound("sound.kicu_mmad_destroy_nest_break", { x, y, z }, { pitch: Math.random() * 3 + 1, volume: 0.5 });
                        entity.triggerEvent("kicu_mmad:despawns");
                    }, 12);
                }, 6);
            },
            "kicu_mmad:feeding": (entity) => feedMount(entity, entityLocation, entityId, log),
            "kicu_mmad:egg_incubator_interact": (entity) => incubatorClick(log, entity),
            "kicu_mmad:set_wild_fly": (entity) => {
                if (!isSleeping(entity)) {
                    entity.addEffect("levitation", 60, { amplifier: 2, showParticles: false });
                    entity.setProperty("kicu_mmad:wild_fly", false);
                    system.runTimeout(() => {
                        if (entity.isValid()) {
                            const sourceLookDirection = entity.getViewDirection();
                            entity.applyKnockback(sourceLookDirection.x * 3, sourceLookDirection.z * 2, 2, 0);
                        }
                    }, 70);
                }
            },
            "kicu_mmad:set_wild_sleep": (entity) => {
                const dayTime = checkIsDay();
                const isSleep = isSleeping(entity);
                if (dayTime && isSleep) {
                    setWake(entity);
                }
                else if (!dayTime && !isSleep && canSleep(entity)) {
                    setSleep(entity);
                }
            },
            "kicu_mmad:drop_egg": (entity) => {
                const { typeId } = entity;
                let eggTypeIndex;
                if (typeId.endsWith("_egg_placeholder")) {
                    eggTypeIndex = mountIDs.indexOf(typeId.replace("_egg_placeholder", "")) + 1;
                }
                else if (typeId.endsWith("egg_incubator")) {
                    const baseMountId = entity.getProperty("kicu_mmad:egg_type");
                    eggTypeIndex = baseMountId > 0 ? baseMountId : undefined;
                }
                if (eggTypeIndex !== undefined && spawnEggStatTypes[eggTypeIndex]) {
                    spawnEggItemAtFromIndex(eggTypeIndex, entity);
                    entity.triggerEvent("kicu_mmad:despawns");
                }
            },
            "kicu_mmad:egg_interact": (entity) => eggClick(log, entity),
            "kicu_mmad:nest_interacts": (entity) => nestClick(log, entity),
            "kicu_mmad:lantern_of_warding_die": (entity) => {
                entity.runCommand("playanimation @s animation.kicu_mmad_damaged.generic");
                removeWardLocation(log, entity);
                entity.runCommand("playsound random.glass @a[r=16] ~ ~ ~ 1 1.0 1");
                entity.dimension.spawnParticle("kicu_mmad:lantern_of_warding_break", entity.location);
                system.runTimeout(() => {
                    const itemId = "kicu_mmad:lantern_of_warding_spawn_egg";
                    const lantern_of_warding_spawn_egg = new ItemStack(itemId, 1);
                    lantern_of_warding_spawn_egg.setLore(itemLoreConfig[itemId]);
                    entity.dimension.spawnItem(lantern_of_warding_spawn_egg, entity.location);
                    entity.runCommand("event entity @s kicu_mmad:despawns");
                }, 5);
            },
            "kicu_mmad:set_healing": (entity) => healMount(entity),
        };
        if (id in eventHandlers) {
            eventHandlers[id](sourceEntity);
        }
    });
}
function extractNumber(str) {
    const match = str.match(/-?\d+(\.\d+)?/);
    return match ? +match[0] : 0;
}

//# sourceMappingURL=../../../../../_KiCuMountsBPDebug/kicu/mmad/ESS/ScriptEvent.js.map
