import API
import time

# =============================================================================
# SL_Combat_Targeting.py  -  Shattered Legacy combat script: who to fight
# A module of SL_Combat.py (run that one).
#
# The rules (design section 5):
#   always    reds (Murderer), criminals, enemies (orange)
#   grays     only if the gray is attacking the player or a companion, or its
#             name is on the hunt list
#   never     blues (Innocent), greens (Ally), invulnerables, own pets,
#             companions (squire, evo pet), party members
# Stick to the current target until it is dead; if something else attacks the
# player, re-pick by the setting: nearest or lowest HP.
# =============================================================================

ATTACK_WINDOW = 3.0      # a hits drop this recent means "being attacked"
ATTACK_REACH = 2         # a gray in war mode this close to the hurt one counts as the attacker


def _noto():
    N = API.Notoriety
    return {
        "always": [N.Murderer, N.Criminal, N.Enemy],
        "gray": [N.Gray],
        "never": [N.Innocent, N.Ally, N.Invulnerable],
    }


def name_matches(name, hunt_list):
    """True when a hunt-list entry equals the name or one of its words (case-insensitive).
    'ettin' hits 'an ettin'; 'orc' hits 'an orc captain' but not 'an orcish lord'."""
    n = (name or "").strip().lower()
    if not n:
        return False
    words = n.split()
    for entry in hunt_list or []:
        e = (entry or "").strip().lower()
        if not e:
            continue
        if e == n or e in words:
            return True
        if " " in e and e in n:
            return True
    return False


class Targeting:
    def __init__(self, settings):
        self.s = settings
        self.player_hits = None
        self.player_hurt_at = 0.0
        self.companion_hits = {}       # serial -> hits
        self.companion_hurt_at = {}    # serial -> time
        self.consented = set()         # grays the player attacked themselves (Assist consent)
        self.out_of_reach = {}         # serial -> time ignored until

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

    def companion_serials(self):
        out = set()
        for s in self.s.get("companions", []) or []:
            try:
                out.add(int(s))
            except Exception:
                pass
        try:
            for s in API.GetAllFriends() or []:
                out.add(int(s))
        except Exception:
            pass
        try:
            for s in API.GetPartyMemberSerials() or []:
                out.add(int(s))
        except Exception:
            pass
        return out

    def is_companion(self, mob, serials=None):
        if mob is None:
            return False
        if serials is None:
            serials = self.companion_serials()
        if int(mob.Serial) in serials:
            return True
        try:
            if mob.IsRenamable:          # TazUO's own "own follower" test
                return True
        except Exception:
            pass
        return False

    def companions(self, max_distance=12):
        """The companions the client can see right now, alive, as ApiMobile objects."""
        out = []
        for s in self.companion_serials():
            try:
                m = API.FindMobile(s)
            except Exception:
                m = None
            if m is not None and not m.IsDead and m.Distance <= max_distance:
                out.append(m)
        try:
            for m in API.GetAllMobiles(distance=max_distance) or []:
                if m is not None and not m.IsDead and m.Serial != API.Player.Serial and m.IsRenamable:
                    if all(x.Serial != m.Serial for x in out):
                        out.append(m)
        except Exception:
            pass
        return out

    # -- damage tracking --------------------------------------------------------

    def note_damage(self, now=None):
        """Call every tick: remembers when the player or a companion last lost hits."""
        now = now or time.time()
        hits = API.Player.Hits
        if self.player_hits is not None and hits < self.player_hits:
            self.player_hurt_at = now
        self.player_hits = hits
        for m in self.companions():
            last = self.companion_hits.get(m.Serial)
            if last is not None and m.Hits < last:
                self.companion_hurt_at[m.Serial] = now
            self.companion_hits[m.Serial] = m.Hits

    def player_under_attack(self, now=None):
        now = now or time.time()
        return now - self.player_hurt_at <= ATTACK_WINDOW

    def _hurt_positions(self, now):
        pts = []
        if self.player_under_attack(now):
            pts.append((API.Player.X, API.Player.Y))
        for m in self.companions():
            if now - self.companion_hurt_at.get(m.Serial, 0) <= ATTACK_WINDOW:
                pts.append((m.X, m.Y))
        return pts

    def attacking_us(self, mob, now=None):
        """A gray counts as attacking when it is in war mode within reach of someone who just lost hits,
        or the player attacked it themselves."""
        now = now or time.time()
        if mob.Serial in self.consented:
            return True
        try:
            if API.LastTargetSerial == mob.Serial and API.Player.InWarMode:
                self.consented.add(mob.Serial)
                return True
        except Exception:
            pass
        if not mob.InWarMode:
            return False
        for (x, y) in self._hurt_positions(now):
            if max(abs(mob.X - x), abs(mob.Y - y)) <= ATTACK_REACH:
                return True
        return False

    # -- the rules ------------------------------------------------------------------

    def allowed(self, mob, now=None, companion_serials=None):
        """The whole rule set for one mobile."""
        if mob is None or mob.IsDead or mob.Serial == API.Player.Serial:
            return False
        if self.is_companion(mob, companion_serials):
            return False
        if self.out_of_reach.get(mob.Serial, 0) > (now or time.time()):
            return False
        noto = _noto()
        n = mob.Notoriety
        if n in noto["never"]:
            return False
        if n in noto["always"]:
            return True
        if n in noto["gray"]:
            if name_matches(mob.Name, self.s.get("huntList", [])):
                return True
            return self.attacking_us(mob, now)
        return False

    def give_up(self, serial, seconds=20):
        self.out_of_reach[serial] = time.time() + seconds

    # -- selection ------------------------------------------------------------------

    def candidates(self, rng, now=None, origin=None):
        now = now or time.time()
        noto = _noto()
        serials = self.companion_serials()
        out = []
        try:
            mobs = API.GetAllMobiles(distance=rng, notoriety=noto["always"] + noto["gray"]) or []
        except Exception:
            mobs = []
        for m in mobs:
            if origin is not None:
                if max(abs(m.X - origin[0]), abs(m.Y - origin[1])) > rng:
                    continue
            if self.allowed(m, now, serials):
                out.append(m)
        return out

    def pick(self, mobs):
        if not mobs:
            return None
        if self.s.get("pickBy", "nearest") == "lowesthp":
            def key(m):
                mx = m.HitsMax or 25
                return (float(m.Hits) / mx, m.Distance)
        else:
            def key(m):
                return (m.Distance, m.Hits)
        return sorted(mobs, key=key)[0]

    def choose(self, current_serial, rng, now=None, origin=None):
        """Keep the current target while it lives and is allowed, unless something new is attacking us;
        otherwise pick from the candidates."""
        now = now or time.time()
        current = None
        if current_serial:
            try:
                current = API.FindMobile(current_serial)
            except Exception:
                current = None
            if current is not None and (current.IsDead or not self.allowed(current, now)):
                current = None
        attackers = []
        if self._hurt_positions(now):
            for m in self.candidates(rng, now, origin):
                if current is not None and m.Serial == current.Serial:
                    continue
                if m.Notoriety in _noto()["always"] or self.attacking_us(m, now):
                    attackers.append(m)
        if current is not None and not attackers:
            return current
        if attackers:
            pool = attackers + ([current] if current is not None else [])
            return self.pick(pool)
        return self.pick(self.candidates(rng, now, origin))


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