package net.mcreator.phayriosisreborn.meteor;

import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.ai.attributes.AttributeInstance;
import net.minecraft.world.entity.ai.attributes.Attributes;

/** Called once for EXTERIOR meteor defenders, after the existing meteor spawn path returns. */
public final class MeteorDefenderHealth {
    private MeteorDefenderHealth() {}

    public static void raiseIfBelow100(Entity entity) {
        if (!(entity instanceof LivingEntity living)) return;
        float originalMax = living.m_21233_();
        if (!(originalMax < 100.0f)) return;
        AttributeInstance health = living.m_21051_(Attributes.f_22276_);
        if (health == null) return;

        // Base-value adjustment preserves existing modifiers where possible and never
        // decreases a mob already at or above 100 effective maximum health.
        double initialBase = health.m_22115_();
        double delta = 100.0d - originalMax;
        health.m_22100_(initialBase + delta);
        double firstResult = living.m_21233_();
        double change = firstResult - originalMax;
        if (Double.isFinite(change) && change > 0.0001d) {
            double correctedBase = initialBase + delta * delta / change;
            if (Double.isFinite(correctedBase) && correctedBase >= 1.0d) {
                health.m_22100_(correctedBase);
            }
        }
        // Rare modded negative modifiers can leave the effective value below 100.
        // A small final correction maintains the requested floor without a tick loop.
        if (living.m_21233_() < 100.0f) {
            health.m_22100_(health.m_22115_() + 2.0d * (100.0d - living.m_21233_()));
        }
        living.m_21153_(Math.min(100.0f, living.m_21233_()));
    }
}
