import API

# =============================================================================
# SL_Combat.py  -  Shattered Legacy combat script, phase 1 (melee and the loot rater)
#
# Run this one. It fights what the rules allow, keeps you and your companions
# alive, and rates the magic loot you pick up. The modules beside it
# (SL_Combat_*.py) are not scripts to run on their own.
#
#   Assist mode   you move; the script targets, uses specials and heals.
#   AFK mode      the script also seeks targets around an anchor and returns to it.
#
# Targets: reds, criminals and oranges always; grays only when they attack you
# or a companion, or their name is on your hunt list; never blues, greens,
# invulnerables, your pets, companions or party. Hotkeys (Settings): CTRL+F9
# on/off, CTRL+F10 mode, CTRL+F11 pause, CTRL+F12 panic.
#
# Loot helper: TazUO autoloot takes the basics; this rates magic items against
# your profile (Keep, Upgrade, Unravel, Sell, Junk) and can sort them to bags.
# [artificerrank on the server tells it which essences you can use.
#
# Design and roadmap: shard-migration notes/design-combat-script.md (cc-P145).
# After editing a SL_Combat_* module, start this script with Legion's "Disable
# module cache" on, or restart the client, or the old module keeps running.
# =============================================================================

import SL_Combat_Settings as S
import SL_Combat_Core as C
import SL_Combat_Gump as G

S.load()
core = C.Core()
ui = G.UI(core)


def bind_hotkeys(old=None, new=None):
    if old:
        for key in old.values():
            if key:
                try:
                    API.OnHotKey(key)
                except Exception:
                    pass
    keys = new or S.SETTINGS.get("hotkeys", {})
    actions = {
        "toggle": core.toggle,
        "mode": core.toggle_mode,
        "pause": core.toggle_pause,
        "panic": core.panic,
    }
    for name, fn in actions.items():
        key = keys.get(name)
        if key:
            try:
                API.OnHotKey(key, fn)
            except Exception as e:
                API.SysMsg("[SL_Combat] hotkey %s for %s not accepted: %s" % (key, name, e), 33)


ui.on_hotkeys_changed = bind_hotkeys


def on_stop():
    try:
        core.shutdown()
    finally:
        ui.close_all()
        API.SysMsg("[SL_Combat] stopped.", 43)


API.OnStop(on_stop)
bind_hotkeys()
ui.open_main()

if core.rank is None:
    core.refresh_rank(silent=True)

API.SysMsg("[SL_Combat] ready: %s, %s mode. Click On or press %s." % (
    "ON" if core.enabled() else "off", S.SETTINGS.get("mode"), S.SETTINGS.get("hotkeys", {}).get("toggle")), 68)

errors = 0
while not API.StopRequested:
    API.ProcessCallbacks()
    try:
        core.tick()
        errors = 0
    except Exception as e:
        errors += 1
        API.SysMsg("[SL_Combat] error: %s" % e, 33)
        if errors >= 5:
            API.SysMsg("[SL_Combat] five errors in a row: switched off. Fix and click On.", 33)
            core.set_enabled(False)
            errors = 0
        API.Pause(1)
    ui.refresh()
    API.Pause(0.2)
