import API
import time

# =============================================================================
# SL_Combat_Survival.py  -  Shattered Legacy combat script: staying alive
# A module of SL_Combat.py (run that one).
#
# Self bandage on a hits threshold or poison (one cooldown bar), heal and cure
# potions on their thresholds, companion care (bandage a hurt companion, "all
# guard me" when the player is hurt), and panic (stop, heal, recall or run).
# Design section 6.
# =============================================================================

BANDAGE = 0x0E21
HEAL_POTION = 0x0F0C
CURE_POTION = 0x0F07
REFRESH_POTION = 0x0F0B
COOLDOWN_NAME = "Bandaging"


def hits_pct(m=None):
    m = m or API.Player
    mx = m.HitsMax or 0
    if mx <= 0:
        return 100.0
    return (m.Hits * 100.0) / mx


def stam_pct():
    mx = API.Player.StaminaMax or 0
    if mx <= 0:
        return 100.0
    return (API.Player.Stamina * 100.0) / mx


def bandage_seconds(dex, override=0):
    """The stock self-bandage delay: 11 - Dex/20, never under 1 (the Healing resist can push it lower; one second
    is close enough for a timer bar)."""
    if override and override > 0:
        return float(override)
    return max(1.0, 11.0 - (dex // 20))


class Survival:
    def __init__(self, settings):
        self.s = settings
        self.bandage_until = 0.0
        self.potion_until = 0.0
        self.cure_until = 0.0
        self.refresh_until = 0.0
        self.companion_until = {}
        self.guard_said_at = 0.0
        self.missing_said = {}
        self.panic_active = False
        self.panic_started = 0.0
        self.last_action = ""

    # -- helpers --------------------------------------------------------------------

    def _say_missing(self, what):
        now = time.time()
        if now - self.missing_said.get(what, 0) > 60:
            API.SysMsg("[SL_Combat] no %s left in your pack" % what, 33)
            self.missing_said[what] = now

    def _has(self, graphic):
        try:
            return API.FindType(graphic, API.Backpack) is not None
        except Exception:
            return False

    def in_danger(self):
        return hits_pct() < self.s.get("bandageAt", 70) or API.Player.IsPoisoned

    def bandaging(self):
        return time.time() < self.bandage_until

    # -- self ---------------------------------------------------------------------------

    def bandage_self(self, now):
        if now < self.bandage_until:
            return False
        if not self._has(BANDAGE):
            self._say_missing("bandages")
            return False
        try:
            ok = API.BandageSelf()
        except Exception:
            ok = False
        if ok:
            secs = bandage_seconds(API.Player.Dexterity, self.s.get("bandageDelayOverride", 0))
            self.bandage_until = now + secs
            try:
                API.CreateCooldownBar(secs, COOLDOWN_NAME, 21)
            except Exception:
                pass
            self.last_action = "bandage"
            return True
        return False

    def heal_potion(self, now):
        if now < self.potion_until:
            return False
        if API.Player.IsPoisoned:
            return False          # a heal potion does nothing while poisoned
        if not self._has(HEAL_POTION):
            self._say_missing("heal potions")
            return False
        API.UseType(HEAL_POTION, container=API.Backpack)
        self.potion_until = now + self.s.get("potionCooldown", 10)
        self.last_action = "heal potion"
        return True

    def cure_potion(self, now):
        if now < self.cure_until:
            return False
        if not self._has(CURE_POTION):
            self._say_missing("cure potions")
            return False
        API.UseType(CURE_POTION, container=API.Backpack)
        self.cure_until = now + 1.5
        self.last_action = "cure potion"
        return True

    def refresh_potion(self, now):
        if now < self.refresh_until or not self._has(REFRESH_POTION):
            return False
        API.UseType(REFRESH_POTION, container=API.Backpack)
        self.refresh_until = now + 5
        self.last_action = "refresh potion"
        return True

    def tick_self(self, now):
        """Priority 1 each tick. Returns True when a heal action was started."""
        acted = False
        hp = hits_pct()
        poisoned = API.Player.IsPoisoned
        if poisoned and hp < self.s.get("curePotionAt", 90):
            acted = self.cure_potion(now) or acted
        if hp < self.s.get("bandageAt", 70) or poisoned:
            acted = self.bandage_self(now) or acted
        if hp < self.s.get("healPotionAt", 45):
            acted = self.heal_potion(now) or acted
        ra = self.s.get("refreshAt", 0)
        if ra and stam_pct() < ra:
            acted = self.refresh_potion(now) or acted
        return acted

    # -- companions ---------------------------------------------------------------------

    def tick_companions(self, now, companions):
        """Priority 2. Bandage a hurt companion (walking to it first); 'all guard me' when the player is hurt."""
        acted = False
        if hits_pct() < self.s.get("guardAt", 50) and companions and now - self.guard_said_at > 20:
            API.Msg("all guard me")
            self.guard_said_at = now
        if self.bandaging():
            return acted
        threshold = self.s.get("companionHealAt", 60)
        for m in companions:
            if m.IsDead or hits_pct(m) >= threshold:
                continue
            if now < self.companion_until.get(m.Serial, 0):
                continue
            if not self._has(BANDAGE):
                self._say_missing("bandages")
                return acted
            if m.Distance > 2:
                try:
                    API.PathfindEntity(m.Serial, 1, True, 3)
                except Exception:
                    pass
                if m.Distance > 2:
                    continue
            API.UseType(BANDAGE, container=API.Backpack)
            if API.WaitForTarget("any", 2):
                API.Target(m.Serial)
                secs = bandage_seconds(API.Player.Dexterity, self.s.get("bandageDelayOverride", 0))
                self.bandage_until = now + secs
                self.companion_until[m.Serial] = now + secs
                try:
                    API.CreateCooldownBar(secs, COOLDOWN_NAME, 68)
                except Exception:
                    pass
                self.last_action = "bandage companion"
                acted = True
                break
        return acted

    # -- panic ----------------------------------------------------------------------------

    def start_panic(self, now=None):
        now = now or time.time()
        self.panic_active = True
        self.panic_started = now
        try:
            API.CancelPathfinding()
        except Exception:
            pass
        API.SetWarMode(False)
        API.HeadMsg("PANIC", API.Player, 33)
        API.SysMsg("[SL_Combat] panic: healing, then %s" % self.s.get("panicAction", "heal"), 33)

    def tick_panic(self, now):
        """While panicking: heal first; once hits are back over the bandage threshold (or 15 s pass), do the
        configured escape. Returns False when the panic is over."""
        if not self.panic_active:
            return False
        self.tick_self(now)
        healed = hits_pct() >= self.s.get("bandageAt", 70) and not API.Player.IsPoisoned
        if not healed and now - self.panic_started < 15:
            return True
        action = self.s.get("panicAction", "heal")
        if action == "recall":
            rune = int(self.s.get("recallRune", 0) or 0)
            if rune:
                API.CastSpell(self.s.get("recallSpell", "Recall"))
                if API.WaitForTarget("any", 4):
                    API.Target(rune)
            else:
                API.SysMsg("[SL_Combat] panic: no recall rune set (Settings)", 33)
        elif action == "run":
            a = self.s.get("anchor")
            if a:
                try:
                    API.Pathfind(int(a[0]), int(a[1]), int(a[2]), 0, False, 20)
                except Exception:
                    pass
        self.panic_active = False
        return False


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