import API
import json

# =============================================================================
# SL_Combat_Settings.py  -  Shattered Legacy combat script: settings and profiles
# A module of SL_Combat.py (run that one). Holds the defaults, loads and saves
# the per-character settings (API persistent vars, scope Char, as JSON), the
# rating profiles, and the names of the shared vars other scripts can read.
# Design: shard-migration notes/design-combat-script.md (cc-P145).
# =============================================================================

VAR_SETTINGS = "SLC_Settings"       # per-character JSON of everything below
VAR_RANK = "SLC_ArtificerRank"      # cached [artificerrank answer: JSON {"at": epoch, "rank": .., "known": {..}}

# Shared vars (API.SetSharedVar) the core publishes every tick, for a looter or pet manager.
SHARED = {
    "enabled": "SLC_Enabled",         # 1 or 0
    "paused": "SLC_Paused",           # 1 or 0
    "mode": "SLC_Mode",               # "assist" or "afk"
    "state": "SLC_State",             # Idle, Engage, Heal, Recover, Loot
    "target": "SLC_Target",           # serial or 0
    "anchor": "SLC_Anchor",           # "x,y,z,map" or ""
    "companions": "SLC_Companions",   # comma-separated serials
    "hunt": "SLC_HuntList",           # semicolon-separated names
    "danger": "SLC_InDanger",         # 1 while under the heal threshold or poisoned
    "last_rated": "SLC_LastRated",    # serial of the last item the rater scored
}

# The shipped profile: a swordsman with Healing. Weights per property display name (SL_Combat_Rater.PROPERTIES).
MELEE_STARTER = {
    "Hit Chance Increase": 10, "Defense Chance Increase": 8, "Swing Speed Increase": 8, "Damage Increase": 8,
    "Hit Life Leech": 6, "Hit Stamina Leech": 4, "Hit Mana Leech": 3, "Hit Lower Defense": 4, "Hit Lower Attack": 3,
    "Physical Resist Bonus": 3, "Fire Resist Bonus": 3, "Cold Resist Bonus": 3, "Poison Resist Bonus": 3, "Energy Resist Bonus": 3,
    "Bonus Strength": 3, "Bonus Dexterity": 3, "Bonus Intelligence": 0,
    "Hit Point Increase": 3, "Stamina Increase": 2, "Mana Increase": 1,
    "Hit Points Regen": 2, "Stamina Regen": 3, "Mana Regen": 1,
    "Luck": 2, "Enhance Potions": 2, "Lower Mana Cost": 2, "Lower Reagent Cost": 0,
    "Faster Casting": 1, "Faster Cast Recovery": 0, "Spell Damage Increase": 0, "Spell Channeling": 0,
    "Mage Weapon": -5, "Mage Armor": 0, "Night Sight": 1, "Reflect Physical Damage": 2,
    "Hit Magic Arrow": 2, "Hit Harm": 2, "Hit Fireball": 2, "Hit Lightning": 2, "Hit Dispel": 1,
    "Hit Cold Area": 1, "Hit Fire Area": 1, "Hit Energy Area": 1, "Hit Poison Area": 1, "Hit Physical Area": 1,
    "Slayer": 4, "Super Slayer": 6, "Skill Bonus": 2,
    "Self Repair": 1, "Durability": 1, "Lower Requirements": 0, "Balanced": 0, "Velocity": 0,
    "Bountiful": 0, "Mastercraft": 0, "Prospector": 0, "Butcher's Eye": 1, "Fortune's Favor": 2,
    "Echo of the Loop": 2, "Time Slip": 4, "Shatter": 4, "Bond": 3, "Spell Leech": 0, "Renowned": 1,
}

DEFAULTS = {
    "version": 1,
    "enabled": False,
    "mode": "assist",                 # assist | afk
    "engageRange": 8,                 # fight what the rules allow this close (both modes)
    "seekRange": 12,                  # AFK: look this far from the anchor for targets
    "leashRange": 20,                 # AFK: never go further than this from the anchor
    "pickBy": "nearest",              # nearest | lowesthp, when something else attacks mid-fight
    "huntList": [],                   # names (or words of names) of grays to fight
    "companions": [],                 # serials added with Add companion
    "anchor": None,                   # [x, y, z, map] or None
    "hotkeys": {"toggle": "CTRL+F9", "mode": "CTRL+F10", "pause": "CTRL+F11", "panic": "CTRL+F12"},
    # survival
    "bandageAt": 70,                  # % hits
    "bandageDelayOverride": 0,        # seconds; 0 = the stock formula from Dex
    "healPotionAt": 45,
    "curePotionAt": 90,               # poisoned and under this: cure potion
    "refreshAt": 0,                   # % stamina; 0 = off
    "potionCooldown": 10,
    "companionHealAt": 60,
    "guardAt": 50,                    # "all guard me" under this
    "panicAt": 0,                     # % hits, automatic panic; 0 = hotkey only
    "panicAction": "heal",            # heal | recall | run
    "recallRune": 0,                  # serial of a rune or runebook entry item for recall
    "recallSpell": "Recall",          # Recall | Sacred Journey
    # melee
    "special": "primary",             # primary | secondary | alternate | none
    "specialMana": 30,
    "specialCooldown": 3.0,
    "recoverHp": 80,                  # AFK: wait for these before the next target
    "recoverStam": 60,
    # rater
    "lootHelper": True,
    "compareMode": True,
    "autoSort": False,
    "bags": {"Keep": 0, "Unravel": 0, "Sell": 0},
    "keepAt": 12.0,
    "upgradeMargin": 2.0,
    "activeProfile": "Melee starter",
    "profiles": {"Melee starter": dict(MELEE_STARTER)},
    "profileCaps": {},                # per profile: {property: cap override}
}

SETTINGS = {}


def _merge(base, over):
    out = {}
    for k, v in base.items():
        if isinstance(v, dict) and isinstance(over.get(k), dict):
            out[k] = _merge(v, over[k])
        elif k in over:
            out[k] = over[k]
        else:
            out[k] = json.loads(json.dumps(v))
    for k, v in over.items():
        if k not in out:
            out[k] = v
    return out


def load():
    """Fill SETTINGS from the character's persistent var, defaults for anything missing."""
    raw = ""
    try:
        raw = API.GetPersistentVar(VAR_SETTINGS, "", API.PersistentVar.Char) or ""
    except Exception:
        raw = ""
    saved = {}
    if raw:
        try:
            saved = json.loads(raw)
        except Exception as e:
            API.SysMsg("[SL_Combat] settings unreadable, using defaults (%s)" % e, 33)
            saved = {}
    SETTINGS.clear()
    SETTINGS.update(_merge(DEFAULTS, saved if isinstance(saved, dict) else {}))
    if "Melee starter" not in SETTINGS["profiles"]:
        SETTINGS["profiles"]["Melee starter"] = dict(MELEE_STARTER)
    if SETTINGS["activeProfile"] not in SETTINGS["profiles"]:
        SETTINGS["activeProfile"] = "Melee starter"
    return SETTINGS


def save():
    try:
        API.SavePersistentVar(VAR_SETTINGS, json.dumps(SETTINGS), API.PersistentVar.Char)
    except Exception as e:
        API.SysMsg("[SL_Combat] could not save settings: %s" % e, 33)


def get(key, default=None):
    return SETTINGS.get(key, default)


def set(key, value, persist=True):
    SETTINGS[key] = value
    if persist:
        save()


def active_profile():
    name = SETTINGS.get("activeProfile", "Melee starter")
    return SETTINGS["profiles"].get(name) or SETTINGS["profiles"]["Melee starter"]


def profile_caps():
    return SETTINGS.get("profileCaps", {}).get(SETTINGS.get("activeProfile", ""), {})


def set_profile(name, weights, caps=None, select=True):
    SETTINGS["profiles"][name] = dict(weights)
    if caps is not None:
        SETTINGS.setdefault("profileCaps", {})[name] = dict(caps)
    if select:
        SETTINGS["activeProfile"] = name
    save()


def delete_profile(name):
    if name == "Melee starter":
        return False
    SETTINGS["profiles"].pop(name, None)
    SETTINGS.get("profileCaps", {}).pop(name, None)
    if SETTINGS["activeProfile"] == name:
        SETTINGS["activeProfile"] = "Melee starter"
    save()
    return True


def to_int(text, default):
    try:
        return int(str(text).strip())
    except Exception:
        return default


def to_float(text, default):
    try:
        return float(str(text).strip())
    except Exception:
        return default


def load_rank_cache():
    try:
        raw = API.GetPersistentVar(VAR_RANK, "", API.PersistentVar.Char) or ""
        return json.loads(raw) if raw else None
    except Exception:
        return None


def save_rank_cache(data):
    try:
        API.SavePersistentVar(VAR_RANK, json.dumps(data), API.PersistentVar.Char)
    except Exception:
        pass


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