// =====================================================
// TYPHOON RELEASE BOSS AI (CustomNPCs 1.12.2)
// Uses ShinobiNPCScriptAPI for all Typhoon abilities.
// Activates Thunderhead Formation at fight start and
// again at low HP for an empowered second phase.
// =====================================================

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

var THUNDERHEAD_REFRESH = 20 * 55;   // re-cast storm every ~55 s (under its internal limit)
var STORM_ANNOUNCE_DONE = false;

var AIM_EVERY_CAST = true;
var AIM_PITCH      = true;

// ---- Normal phase weights ----
var WEIGHTS_BASE = {
    STRONG   : 65,
    THUNDER  : 20
};

// ---- Aggressive phase (below 50% HP) ----
var WEIGHTS_AGGRO = {
    STRONG   : 45,
    EXTREME  : 55,
    THUNDER  : 20
};

var POWERS = {
    STRONG  : 5.0,
    EXTREME : 6.0,
    THUNDER : 5.0
};

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

// ================= 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, me) {
    if (pick === "STRONG")   return Shinobi.cast(npc, "typhoon_strong_consecutive_winds",   POWERS.STRONG,   true);
    if (pick === "EXTREME")  return Shinobi.cast(npc, "typhoon_extreme_consecutive_winds",  POWERS.EXTREME,  true);
    if (pick === "THUNDER")  return Shinobi.cast(npc, "typhoon_thunderhead_formation",       POWERS.THUNDER,  true);
    return false;
}

var NEEDS_WINDUP = { EXTREME: true };

// ================= 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;

    // Init storeddata keys
    if (!npc.getStoreddata().has("ty_cd"))      setStored(npc, "ty_cd",      0);
    if (!npc.getStoreddata().has("ty_wind"))    setStored(npc, "ty_wind",    0);
    if (!npc.getStoreddata().has("ty_casting")) setStored(npc, "ty_casting", "");
    if (!npc.getStoreddata().has("ty_thcd"))    setStored(npc, "ty_thcd",    0);

    // ---- Periodic Thunderhead refresh ----
    var thcd = getStored(npc, "ty_thcd", 0);
    if (thcd <= 0) {
        Shinobi.cast(npc, "typhoon_thunderhead_formation", POWERS.THUNDER, true);
        setStored(npc, "ty_thcd", THUNDERHEAD_REFRESH);
        if (!STORM_ANNOUNCE_DONE) {
            npc.say("§9§lThe storm answers my call...");
            STORM_ANNOUNCE_DONE = true;
        }
    } else {
        setStored(npc, "ty_thcd", thcd - 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;
        // Force a Thunderhead re-cast on phase transition
        if (phase === 1) setStored(npc, "ty_thcd", 0);
    }

    // ---- WINDUP ----
    var wind    = getStored(npc, "ty_wind",    0);
    var casting = getStored(npc, "ty_casting", "");

    if (wind > 0) {
        if (wind % 3 === 0) {
            try { npc.spawnParticle("CLOUD", npc.getX(), npc.getY() + 1, npc.getZ(), 0.5, 0.5, 0.5, 6, 0); } catch(e) {}
        }
        wind--;
        setStored(npc, "ty_wind", wind);
        if (wind === 0 && casting) {
            if (AIM_EVERY_CAST) faceTarget(me, t);
            var used = castPick(casting, npc, me);
            setStored(npc, "ty_casting", "");
            setStored(npc, "ty_cd", used ? BASE_COOLDOWN : 8);
        }
        return;
    }

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

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

    if (d > 16) {
        weights.EXTREME  = (weights.EXTREME  || 0) + 30;   // ranged pressure from a distance
        weights.STRONG   = (weights.STRONG   || 0) + 15;
    } else if (d < 6) {
        weights.STRONG   += 20;
    }

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

    if (NEEDS_WINDUP[pick]) {
        setStored(npc, "ty_wind",    WINDUP_TICKS);
        setStored(npc, "ty_casting", pick);
        return;
    }

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

// ================= EVENTS =================
function target(event) {
    var npc = event.npc;
    if (!npc) return;
    STORM_ANNOUNCE_DONE = false;
    setStored(npc, "ty_thcd", 0);   // trigger Thunderhead immediately
    setStored(npc, "ty_cd",      20);
    setStored(npc, "ty_wind",    0);
    setStored(npc, "ty_casting", "");
    npc.say("§9You dare challenge the eye of the storm?");
}

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

function announcePhase(npc, phase) {
    if (phase === 0) {
        npc.say("§9§oThe winds obey me...");
    } else {
        npc.say("§b§l§oYOU WILL BE SWALLOWED BY THE GALE!");
    }
}
