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


export function initAnimalPack() {

    
    const forebodingCheck = fo.scoreChapter3; 
    const chance = 1 / 24; 
    const checkInterval = 6000; 

    
    let eventFlag = false; 

    
    function getDistance(pos1, pos2) {
        return Math.sqrt(
            Math.pow(pos1.x - pos2.x, 2) +
            Math.pow(pos1.z - pos2.z, 2) 
        );
    }

    
    function isCowFarFromAllPlayers(cow) {
        const players = cow.dimension.getPlayers({
            location: cow.location,
            maxDistance: 42,
        });

        
        return players.length === 0;
    }

    
    function spawnCowsAtLocation(location) {
        const cowCount = 15 + Math.floor(Math.random() * 11); 

        for (let i = 0; i < cowCount; i++) {
            fo.overworld.runCommand(
                `summon minecraft:cow ${location.x} ${location.y} ${location.z}`
            );
        }

        
    }

    
    world.afterEvents.entitySpawn.subscribe((event) => {
        const entity = event.entity;

        system.runTimeout(() => {

            if (eventFlag && entity.typeId === "minecraft:cow" && isCowFarFromAllPlayers(entity)) {
                spawnCowsAtLocation(entity.location);
                eventFlag = false; 
            }
        }, 1) 
    });

    
    system.runInterval(() => {
        const probabilityModifier = fo.netProbabilityModifier;

        if (!eventFlag && Math.random() < (chance * probabilityModifier) && fo.forebodingScore >= forebodingCheck) {
            eventFlag = true;
            
        }
    }, checkInterval);

}