// =====================================================
// BLAZE RELEASE BOSS AI (CustomNPCs 1.12.2)
// Uses ShinobiNPCScriptAPI for all Blaze Release abilities.
// Flame Wrapping Fire used at mid-range to keep pressure.
// Blaze Porcupine deployed as an area-denial spike field.
// Blaze Flame Slice is the phase-2 signature move.
// =====================================================

// ================= CONFIG =================
var BASE_COOLDOWN       = 22;
var WINDUP_TICKS        = 14;
var AGGRESSIVE_HP_RATIO = 0.45;

var SLICE_CD_TICKS     = 20 * 30;  // Blaze Flame Slice on a 30 s internal cooldown
var PORCUPINE_COMBO_CD = 10;       // ticks between each combo hit after porcupine spike

var AIM_EVERY_CAST = true;
var AIM_PITCH      = true;

// ---- Normal phase weights ----
var WEIGHTS_BASE = {
    WRAP  : 50,
    PORCU : 30,
    SLICE : 20
};

// ---- Aggressive phase (below 45% HP) ----
var WEIGHTS_AGGRO = {
    WRAP  : 35,
    PORCU : 35,
    SLICE : 30
};

var POWERS = {
    WRAP  : 5.0,
    PORCU : 5.0,
    SLICE : 8.0
};

// ================= STATE =================
var lastPhase = -1;

// ================= IMPORTS =================
var Shinobi = Java.type("com.leolifeless.shinobiaddon.compat.customnpcs.ShinobiNPCScriptAPI");
var Math    = Java.type("java.lang.Math");

// ================= HELPERS =================
function getStored(npc, key, defVal) {
    var d = npc.getStoreddata();
    if (!d.has(key)) { if (defVal !== undefined) d.put(key, defVal); return defVal; }
    return d.get(key);
}
function setStored(npc, key, val) { npc.getStoreddata().put(key, val); }

function clamp(v, a, b) { return v < a ? a : (v > b ? b : v); }

function copyWeights(obj) {
    var out = {};
    for (var k in obj) out[k] = obj[k];
    return out;
}

function weightedPick(weights) {
    var keys = [], sum = 0;
    for (var k in weights) { keys.push(k); sum += weights[k]; }
    if (!keys.length || sum <= 0) return null;
    var r = Math.random() * sum, acc = 0;
    for (var i = 0; i < keys.length; i++) {
        acc += weights[keys[i]];
        if (r <= acc) return keys[i];
    }
    return keys[keys.length - 1];
}

function getHp(mc) {
    try { if (mc && mc.getHealth) return mc.getHealth(); } catch(e) {}
    try { if (mc && mc.health != null) return mc.health; } catch(e) {}
    return 1;
}
function getMaxHp(mc) {
    try { if (mc && mc.getMaxHealth) return mc.getMaxHealth(); } catch(e) {}
    return 20;
}

function distToTarget(npc, t) {
    if (!t) return 9999;
    var me = npc.getMCEntity();
    var dx = me.posX - t.posX, dy = me.posY - t.posY, dz = me.posZ - t.posZ;
    return Math.sqrt(dx*dx + dy*dy + dz*dz);
}

function faceTarget(me, t) {
    try {
        var dx = t.posX - me.posX, dz = t.posZ - me.posZ;
        var dy = (t.posY + t.height * 0.6) - (me.posY + me.getEyeHeight());
        me.rotationYaw = Math.atan2(dz, dx) * 180 / Math.PI - 90;
        me.rotationYawHead = me.rotationYaw;
        me.renderYawOffset = me.rotationYaw;
        if (AIM_PITCH)
            me.rotationPitch = -(Math.atan2(dy, Math.sqrt(dx*dx + dz*dz)) * 180 / Math.PI);
    } catch(e) {}
}

function castPick(pick, npc) {
    if (pick === "WRAP")  return Shinobi.cast(npc, "blaze_flame_wrapping_fire", POWERS.WRAP,  true);
    if (pick === "PORCU") return Shinobi.cast(npc, "blaze_blaze_porcupine",     POWERS.PORCU, true);
    if (pick === "SLICE") return Shinobi.cast(npc, "blaze_blaze_flame_slice",   POWERS.SLICE, true);
    return false;
}

var NEEDS_WINDUP = { SLICE: true, WRAP: true };
var WINDUP_OVERRIDE = { WRAP: 8 };

// ================= MAIN TICK =================
function tick(event) {
    var npc = event.npc;
    if (!npc) return;

    var me;
    try { me = npc.getMCEntity(); } catch(e) { return; }

    var tgt = npc.getAttackTarget();
    if (!tgt) return;
    var t = tgt.getMCEntity ? tgt.getMCEntity() : tgt;
    if (!t) return;

    if (!npc.getStoreddata().has("bl_cd"))       setStored(npc, "bl_cd",       0);
    if (!npc.getStoreddata().has("bl_wind"))     setStored(npc, "bl_wind",     0);
    if (!npc.getStoreddata().has("bl_casting"))  setStored(npc, "bl_casting",  "");
    if (!npc.getStoreddata().has("bl_combo"))    setStored(npc, "bl_combo",    "");
    if (!npc.getStoreddata().has("bl_combo_cd")) setStored(npc, "bl_combo_cd", 0);
    if (!npc.getStoreddata().has("bl_slicecd"))  setStored(npc, "bl_slicecd",  0);

    // Tick Flame Slice cooldown
    var scd = getStored(npc, "bl_slicecd", 0);
    if (scd > 0) setStored(npc, "bl_slicecd", scd - 1);

    // Phase update
    var phase = 0;
    try {
        var ratio = clamp(getHp(me) / getMaxHp(me), 0.0, 1.0);
        phase = ratio <= AGGRESSIVE_HP_RATIO ? 1 : 0;
    } catch(e) {}

    if (phase !== lastPhase) {
        announcePhase(npc, phase);
        lastPhase = phase;
    }

    // ---- COMBO MODE (follow-up after Porcupine) ----
    var combo   = getStored(npc, "bl_combo",    "");
    var comboCd = getStored(npc, "bl_combo_cd", 0);
    if (combo && combo.length > 0) {
        if (comboCd > 0) { setStored(npc, "bl_combo_cd", comboCd - 1); return; }
        var parts = combo.split(",");
        var next  = parts[0];
        var rest  = parts.slice(1).join(",");
        if (AIM_EVERY_CAST) faceTarget(me, t);
        castPick(next, npc);
        setStored(npc, "bl_combo",    rest);
        setStored(npc, "bl_combo_cd", PORCUPINE_COMBO_CD);
        return;
    }

    // ---- WINDUP ----
    var wind    = getStored(npc, "bl_wind",    0);
    var casting = getStored(npc, "bl_casting", "");

    if (wind > 0) {
        if (wind % 3 === 0) {
            try { npc.spawnParticle("FLAME", npc.getX(), npc.getY() + 1, npc.getZ(), 0.3, 0.5, 0.3, 8, 0); } catch(e) {}
        }
        wind--;
        setStored(npc, "bl_wind", wind);
        if (wind === 0 && casting) {
            if (AIM_EVERY_CAST) faceTarget(me, t);
            var used = castPick(casting, npc);
            if (used && casting === "SLICE")
                setStored(npc, "bl_slicecd", SLICE_CD_TICKS);
            setStored(npc, "bl_casting", "");
            setStored(npc, "bl_cd", used ? BASE_COOLDOWN : 8);
        }
        return;
    }

    // ---- COOLDOWN ----
    var cd = getStored(npc, "bl_cd", 0);
    if (cd > 0) { setStored(npc, "bl_cd", cd - 1); return; }

    // ---- PICK ATTACK ----
    var weights = copyWeights(phase === 1 ? WEIGHTS_AGGRO : WEIGHTS_BASE);
    var d = distToTarget(npc, t);

    // Flame Slice off cooldown in phase 2: force it
    if (phase === 1 && getStored(npc, "bl_slicecd", 0) <= 0) {
        weights.SLICE += 60;
    }
    // Block Flame Slice if still on cooldown
    if (getStored(npc, "bl_slicecd", 0) > 0) {
        weights.SLICE = 0;
    }

    if (d > 14) {
        weights.WRAP += 20;
    } else if (d < 6) {
        weights.PORCU += 25;
    }

    var pick = weightedPick(weights);
    if (!pick) return;

    // Porcupine: fire it then queue a Wrap follow-up
    if (pick === "PORCU") {
        if (AIM_EVERY_CAST) faceTarget(me, t);
        var pOk = castPick("PORCU", npc);
        if (pOk) {
            setStored(npc, "bl_combo",    "WRAP,WRAP");
            setStored(npc, "bl_combo_cd", 12);
        }
        setStored(npc, "bl_cd", BASE_COOLDOWN);
        return;
    }

    if (NEEDS_WINDUP[pick]) {
        var windTicks = WINDUP_OVERRIDE[pick] !== undefined ? WINDUP_OVERRIDE[pick] : WINDUP_TICKS;
        setStored(npc, "bl_wind",    windTicks);
        setStored(npc, "bl_casting", pick);
        return;
    }

    if (AIM_EVERY_CAST) faceTarget(me, t);
    var used2 = castPick(pick, npc);
    setStored(npc, "bl_cd", used2 ? BASE_COOLDOWN : 8);
}

// ================= EVENTS =================
function target(event) {
    var npc = event.npc;
    if (!npc) return;
    setStored(npc, "bl_cd",      20);
    setStored(npc, "bl_wind",    0);
    setStored(npc, "bl_casting", "");
    setStored(npc, "bl_combo",   "");
    setStored(npc, "bl_slicecd", 0);
    npc.say("§6§lAmaterasu never dies. Neither do I.");
}

function damaged(event) {
    var npc = event.npc;
    if (!npc) return;
    try {
        if (event.damage > 5 && Math.random() < 0.35) {
            var cd = getStored(npc, "bl_cd", 0);
            setStored(npc, "bl_cd", Math.max(0, cd - 10));
        }
    } catch(e) {}
}

function announcePhase(npc, phase) {
    if (phase === 0) {
        npc.say("§6§oBlack flames that never go out...");
    } else {
        npc.say("§c§l§oI WILL BURN EVERYTHING — BLAZE FLAME SLICE!");
    }
}
