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






export function initCaveCow() {

    
    const
        summonCowChance = 1 / 155, 
        FOREBODINGCHECK = fo.scoreChapter4, 
        INTERVAL = 1411, 

        IssolationCheck = 52, 

        overworld = fo.overworld;

    let cowEventFlag = false; 

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

    
    function getRandomPlayerBelowY20() {
        const players = [...overworld.getPlayers()].filter(player => player.location.y < 20);

        if (players.length === 0) return null; 

        
        return players[Math.floor(Math.random() * players.length)];
    }

    
    function isPlayerIsolated(player) {
        const players = [...overworld.getPlayers()].filter(
            p => p !== player && getDistance(p.location, player.location) <= IssolationCheck
        );

        return players.length === 0; 
    }

    
    function findValidBlockBehindPlayer(player) {
        let attempts = 7;

        for (let i = 0; i < attempts; i++) {
            
            const distance = 10 - i; 
            const direction = { x: -player.getViewDirection().x, z: -player.getViewDirection().z }; 
            const spawnPos = {
                x: player.location.x + direction.x * distance,
                y: player.location.y + 2,
                z: player.location.z + direction.z * distance
            };

            
            const block = overworld.getBlock({ x: Math.floor(spawnPos.x), y: Math.floor(spawnPos.y), z: Math.floor(spawnPos.z) });
            if (block && block.typeId === "minecraft:air") {
                return spawnPos; 
            }
        }

        return null; 
    }

    
    function summonCowBehindPlayer() {
        const player = getRandomPlayerBelowY20();

        if (!player) {
            
            return;
        }

        if (!isPlayerIsolated(player)) {
            
            return;
        }

        const spawnPos = findValidBlockBehindPlayer(player);

        if (!spawnPos) {
            
            return;
        }

        
        overworld.spawnEntity("minecraft:cow", spawnPos);
        
        cowEventFlag = false 
    }

    
    system.runInterval(() => {
        const forebodingScore = fo.forebodingScore;

        if (!cowEventFlag && forebodingScore >= FOREBODINGCHECK) {

            if (Math.random() <= (summonCowChance * fo.netProbabilityModifier)) {
                cowEventFlag = true; 

                
            }
        } else if (cowEventFlag) { 

            summonCowBehindPlayer();

        }

    }, INTERVAL);

}
