import API
import time

# =============================================================================
# SL_Combat_Melee.py  -  Shattered Legacy combat script: the melee module
# A module of SL_Combat.py (run that one).
#
# A combat module is any object with these methods (all optional):
#   name                       "melee"
#   wants(target) -> bool      could this module fight this target now
#   on_engage(target)          once, when a target is chosen
#   on_tick(target, ctx)       every tick while engaged
#   on_disengage()             the target died or was dropped
#   on_low_hp()                hits crossed the heal threshold while engaged
# ctx is a dict: now, hp (%), mana, stam, distance, settings, mode, anchor.
#
# A STANCE layers on top (Bushido, Chivalry, Necromancy later): the same
# methods, called after the module's each tick. Phase 1 ships none; the
# example at the bottom shows the shape. Design section 7.
# =============================================================================


class MeleeModule:
    name = "melee"

    def __init__(self, settings):
        self.s = settings
        self.last_special = 0.0
        self.alternate = False
        self.engaged = 0

    def wants(self, target):
        return True

    def on_engage(self, target):
        self.engaged = target.Serial
        API.SetWarMode(True)
        API.Attack(target.Serial)

    def on_disengage(self):
        self.engaged = 0

    def on_low_hp(self):
        pass

    def _special_name(self):
        which = self.s.get("special", "primary")
        if which == "none":
            return None
        if which == "alternate":
            self.alternate = not self.alternate
            return "secondary" if self.alternate else "primary"
        return which

    def _special_active(self, which):
        try:
            if which == "primary":
                return API.PrimaryAbilityActive()
            return API.SecondaryAbilityActive()
        except Exception:
            return False

    def specials(self, ctx):
        """Toggle the chosen weapon special when mana and the cooldown allow. Returns True when toggled."""
        now = ctx["now"]
        if now - self.last_special < float(self.s.get("specialCooldown", 3.0)):
            return False
        if ctx["mana"] < int(self.s.get("specialMana", 30)):
            return False
        which = self._special_name()
        if which is None:
            return False
        if self._special_active(which):
            return False
        try:
            API.ToggleAbility(which)
        except Exception:
            return False
        self.last_special = now
        return True

    def on_tick(self, target, ctx):
        if ctx["mode"] == "afk" and target.Distance > 1:
            try:
                API.PathfindEntity(target.Serial, 1, False, 3)
            except Exception:
                pass
        if target.Distance <= 1 or ctx["mode"] == "assist":
            API.Attack(target.Serial)         # re-assert in case war mode or the target dropped
        self.specials(ctx)


# -- the stance hook, by example (not registered) --------------------------------------------
#
# class ChivalryStance:
#     name = "chivalry"
#     def on_engage(self, target):
#         if not API.IsSpellActive("Consecrate Weapon"):
#             API.CastSpell("Consecrate Weapon")
#     def on_tick(self, target, ctx):
#         if ctx["stam"] < 30 and ctx["mana"] >= 15:
#             API.CastSpell("Divine Fury")
#     def on_low_hp(self):
#         API.CastSpell("Close Wounds"); API.WaitForTarget(); API.TargetSelf()
#
# Register one in SL_Combat_Core.STANCES (a later phase adds settings and a gump page per stance).


if __name__ == "__main__":
    API.SysMsg("SL_Combat_Melee is a module of SL_Combat: run SL_Combat.py instead.", 43)
