import { world, system } from "@minecraft/server";
import { fo } from "./utilities/fo_constants";


export function initMobKiller() {

    
    const chance = 1 / 24; 
    const forebodingCheckMin = fo.scoreChapter3 + (fo.durationChapter3 * 0.3);
    const forebodingCheckMax = fo.scoreChapter4 + (fo.durationChapter4 * 0.95);
    const checkInterval = 6000; 


    const validMobs = ["minecraft:chicken", "minecraft:cow", "minecraft:pig", "minecraft:llama", "minecraft:sheep", "minecraft:rabbit", "minecraft:fox", "minecraft:ocelot"];

    
    let isEventActive = false;

    
    function shouldStartEvent() {
        const forebodingScore = fo.forebodingScore;

        
        if (forebodingScore >= forebodingCheckMin && forebodingScore <= forebodingCheckMax) {
            
            if (!isEventActive) {
                const probabilityModifier = Math.min(fo.netProbabilityModifier, 2);

                
                if (Math.random() < (chance * probabilityModifier)) {
                    isEventActive = true;
                    system.runTimeout(() => { 
                        isEventActive = false;
                        
                    }, 144000)
                    
                }
            }
        }
    }

    
    system.runInterval(() => {
        shouldStartEvent();
    }, checkInterval);

    
    world.afterEvents.entitySpawn.subscribe(({ entity }) => {

        if (!isEventActive) return; 

        system.runTimeout(() => {
            try {
                if (!validMobs.includes(entity.typeId)) return;
                if (!entity.isValid) return;
                if (!entity.dimension || entity.dimension.id === null) return;
                if (entity.dimension.id !== "minecraft:overworld") return;

                const players = entity.dimension.getPlayers({
                    location: entity.location,
                    minDistance: 42,
                })

                if (players.length === 0) entity.kill();

            } catch (e) { }
        }, 1) 
    });

}