import { world, system, EntityComponentTypes } from '@minecraft/server';

const trackedEntities = new Map();
const tickInterval = 20;
const dummyType = "maca_evolvingmobs:crash_test_dummy";
const dimensions = ["minecraft:overworld", "minecraft:nether", "minecraft:the_end"];

// Function to reset crash test dummies
function resetCrashTestDummies() {
    for (const dimensionId of dimensions) {
        try {
            const dimension = world.getDimension(dimensionId);
            const dummies = dimension.getEntities({ type: dummyType });

            for (const dummy of dummies) {
                dummy.nameTag = "";
            }
        } catch (error) {}
    }
}

// Call reset function on script initialization
resetCrashTestDummies();

world.afterEvents.entityHurt.subscribe((event) => {
    const target = event.hurtEntity;
    if (target?.typeId !== dummyType) return;
    if (event.damageSource.damagingEntity?.typeId === "minecraft:player") return;

    if (event.damageSource.cause === "selfDestruct") {
        target.remove();
        return;
    }

    startTracking(target);

    // Accumulate damage history
    const data = trackedEntities.get(target.id);
    data.damageHistory.push({
        damage: event.damage,
        tick: system.currentTick
    });
    data.lastDamage = event.damage;
    if (data.firstAttackTick === null) {
        data.firstAttackTick = system.currentTick; // Record the first attack tick
    }

    // Reset health
    const healthComponent = target.getComponent(EntityComponentTypes.Health);
    if (healthComponent) {
        healthComponent.resetToMaxValue();
    }

    updateDPS(target);
});

// Helper function to start tracking a mob
function startTracking(entity) {
    const entityId = entity.id;
    if (!trackedEntities.has(entityId)) {
        trackedEntities.set(entityId, {
            damageHistory: [],
            lastDamage: 0,
            lastUpdate: system.currentTick,
            firstAttackTick: null
        });
    }
}

// Function to calculate and update DPS
function updateDPS(entity) {
    const entityId = entity.id;
    const data = trackedEntities.get(entityId);
    const now = system.currentTick;
    const num = data.damageHistory.length;

    let totalDamage = 0;
    for (const item of data.damageHistory) {
        totalDamage += item.damage;
    }

    if (data.firstAttackTick !== null) {
        const timeSinceFirstAttack = (now - data.firstAttackTick) / tickInterval; 
        const dps = (totalDamage / timeSinceFirstAttack).toFixed(2);
        const lastDamage = data.lastDamage.toFixed(2);
        entity.nameTag = `DPS: ${dps}\nLast Damage: ${lastDamage}\nTotal Damage: ${totalDamage}\nNumber of Hits: ${num}\nElapsed Time: ${timeSinceFirstAttack}`;
        data.lastUpdate = now;
    }
}