import API
import re
import time

# =============================================================================
# SL_Combat_Rater.py  -  Shattered Legacy combat script: the item rater
# A module of SL_Combat.py (run that one).
#
# Reads a magic item's properties from its tooltip, scores them against a
# weighted profile (properties the character already has at or near cap count
# for less), compares with the equipped piece in the same slot, puts the item
# in a tier (Upgrade, Keep, Unravel, Sell, Junk) and says why. Unravel means
# "a property on it is one your account can imbue", which the server tells us
# through [artificerrank. Design section 8 and 9.
#
# Everything that decides is a pure function of plain values, so the tests in
# tests\test_rater.py run it in CPython with a fake API.
# =============================================================================

# -- the property table ----------------------------------------------------------------------
# (display name, tooltip regex (lowercase line), item cap, API.Player attribute with the character's total or None,
#  character-wide cap or None, knowledge keys the Artificers' table uses for it)
# The item cap is the Artificers' catalogue Full value. Add a shard property: one more line.
_RES = ("Physical", "Fire", "Cold", "Poison", "Energy")
_HIT = ("Life Leech", "Stamina Leech", "Mana Leech", "Lower Attack", "Lower Defense", "Magic Arrow", "Harm", "Fireball",
        "Lightning", "Dispel", "Cold Area", "Fire Area", "Energy Area", "Poison Area", "Physical Area")
_CUSTOM = (("Bountiful", 15), ("Mastercraft", 5), ("Prospector", 10), ("Butcher's Eye", 20), ("Fortune's Favor", 5),
           ("Echo of the Loop", 10), ("Time Slip", 5), ("Shatter", 10), ("Bond", 10), ("Spell Leech", 5), ("Renowned", 10))

PROPERTIES = [
    ("Swing Speed Increase", r"^swing speed increase (\d+)%", 60, "SwingSpeedIncrease", 60, None),
    ("Damage Increase", r"^damage increase (\d+)%", 50, "DamageIncrease", 100, None),
    ("Hit Chance Increase", r"^hit chance increase (\d+)%", 45, "HitChanceIncrease", 45, None),
    ("Defense Chance Increase", r"^defense chance increase (\d+)%", 45, "DefenseChanceIncrease", 45, None),
    ("Lower Mana Cost", r"^lower mana cost (\d+)%", 40, "LowerManaCost", 40, None),
    ("Lower Reagent Cost", r"^lower reagent cost (\d+)%", 100, "LowerReagentCost", 100, None),
    ("Spell Damage Increase", r"^spell damage increase (\d+)%", 12, "SpellDamageIncrease", None, None),
    ("Faster Cast Recovery", r"^faster cast recovery (\d+)", 3, "FasterCastRecovery", 6, None),
    ("Faster Casting", r"^faster casting (\d+)", 1, "FasterCasting", 2, None),
    ("Spell Channeling", r"^spell channeling$", 1, None, None, None),
    ("Night Sight", r"^night sight$", 1, None, None, None),
    ("Luck", r"^luck (\d+)", 100, "Luck", None, None),
    ("Enhance Potions", r"^enhance potions (\d+)%", 25, "EnhancePotions", 50, None),
    ("Reflect Physical Damage", r"^reflect physical damage (\d+)%", 15, "ReflectPhysicalDamage", None, None),
    ("Bonus Strength", r"^strength bonus (\d+)", 8, "StrengthIncrease", None, None),
    ("Bonus Dexterity", r"^dexterity bonus (\d+)", 8, "DexterityIncrease", None, None),
    ("Bonus Intelligence", r"^intelligence bonus (\d+)", 8, "IntelligenceIncrease", None, None),
    ("Hit Points Regen", r"^hit point regeneration (\d+)", 5, "HitPointsRegeneration", 18, None),
    ("Stamina Regen", r"^stamina regeneration (\d+)", 5, "StaminaRegeneration", 24, None),
    ("Mana Regen", r"^mana regeneration (\d+)", 5, "ManaRegeneration", 30, None),
    ("Hit Point Increase", r"^hit point increase (\d+)", 5, "HitPointsIncrease", None, None),
    ("Stamina Increase", r"^stamina increase (\d+)", 8, "StaminaIncrease", None, None),
    ("Mana Increase", r"^mana increase (\d+)", 8, "ManaIncrease", None, None),
    ("Mage Weapon", r"^mage weapon -(\d+) skill", 30, None, None, None),
    ("Mage Armor", r"^mage armor$", 1, None, None, None),
    ("Balanced", r"^balanced$", 1, None, None, None),
    ("Velocity", r"^velocity (\d+)%", 50, None, None, None),
    ("Self Repair", r"^self repair (\d+)", 5, None, None, ("Self Repair", "Self Repair (Armor)")),
    ("Durability", r"^durability (\d+)%", 100, None, None, ("Durability (Weapon)", "Durability (Armor)")),
    ("Lower Requirements", r"^lower requirements (\d+)%", 100, None, None, ("Lower Stat Req (Weapon)", "Lower Stat Req (Armor)")),
    ("Elemental Damage", r"^(fire|cold|poison|energy|chaos) damage (\d+)%", 100, None, None, ("Elemental Damage",)),
    ("Skill Bonus", r"^([a-z][a-z ]+?) \+(\d+)$", 15, None, None, ("Jewelry Skill Bonus", "Crafter Skill Bonus")),
    ("Slayer", None, 1, None, None, ("Slayer",)),
    ("Super Slayer", None, 1, None, None, ("Super Slayer",)),
]
for _r in _RES:
    _attr = "PhysicResistance" if _r == "Physical" else _r + "Resistance"
    PROPERTIES.append(("%s Resist Bonus" % _r, r"^%s resist (\d+)%%" % _r.lower(), 20,
                       "PhysicalResistance" if _r == "Physical" else _attr, "Max" + _attr, None))
for _h in _HIT:
    PROPERTIES.append(("Hit " + _h, r"^hit %s (\d+)%%" % _h.lower(), 50, None, None, None))
for _name, _cap in _CUSTOM:
    PROPERTIES.append((_name, r"^%s (\d+)%%" % re.escape(_name.lower()), _cap, None, None, None))

SUPER_SLAYERS = ("repond", "undead", "silver", "arachnid", "reptile", "demon", "elemental", "fey", "exorcism")

MIN_HEADROOM = 0.15
TIER_COLORS = {"Upgrade": "#55FF55", "Keep": "#88DDFF", "Unravel": "#DDAAFF", "Sell": "#FFD966", "Junk": "#999999"}

SHORT = {
    "Swing Speed Increase": "SSI", "Damage Increase": "DI", "Hit Chance Increase": "HCI",
    "Defense Chance Increase": "DCI", "Lower Mana Cost": "LMC", "Lower Reagent Cost": "LRC",
    "Spell Damage Increase": "SDI", "Faster Cast Recovery": "FCR", "Faster Casting": "FC",
    "Hit Life Leech": "HLL", "Hit Stamina Leech": "HSL", "Hit Mana Leech": "HML", "Hit Lower Attack": "HLA",
    "Hit Lower Defense": "HLD", "Hit Point Increase": "HPI", "Hit Points Regen": "HPR", "Stamina Regen": "SR",
    "Mana Regen": "MR", "Enhance Potions": "EP", "Reflect Physical Damage": "RPD",
    "Physical Resist Bonus": "Phys", "Fire Resist Bonus": "Fire", "Cold Resist Bonus": "Cold",
    "Poison Resist Bonus": "Poison", "Energy Resist Bonus": "Energy",
    "Bonus Strength": "Str", "Bonus Dexterity": "Dex", "Bonus Intelligence": "Int",
}

# tiledata layer -> the name FindLayer takes (TazUO Utility.GetItemLayer) and a label
LAYERS = {
    1: ("onehanded", "right hand"), 2: ("twohanded", "left hand"), 3: ("shoes", "feet"), 4: ("pants", "legs"),
    5: ("shirt", "shirt"), 6: ("helmet", "head"), 7: ("gloves", "hands"), 8: ("ring", "ring"),
    9: ("talisman", "talisman"), 10: ("neck", "neck"), 12: ("waist", "waist"), 13: ("torso", "chest"),
    14: ("bracelet", "bracelet"), 17: ("tunic", "tunic"), 18: ("earrings", "earrings"), 19: ("arms", "arms"),
    20: ("cloak", "cloak"), 22: ("robe", "robe"), 23: ("skirt", "skirt"), 24: ("legs", "legs"),
}

_COMPILED = [(p[0], re.compile(p[1]) if p[1] else None, p[2], p[3], p[4], p[5]) for p in PROPERTIES]
BY_NAME = dict((p[0], p) for p in _COMPILED)


def property_names():
    return [p[0] for p in PROPERTIES]


def knowledge_keys(name):
    p = BY_NAME.get(name)
    if p is None:
        return ()
    return p[5] or (name,)


# -- parsing ------------------------------------------------------------------------------------

def parse_props(text):
    """Tooltip text (name first, one property per line) -> list of (property name, value, detail).
    detail is the skill or slayer or damage kind when there is one, else ''."""
    out = []
    lines = [l.strip() for l in (text or "").replace("\r", "").split("\n")]
    for raw in lines[1:]:
        line = raw.lower()
        if not line:
            continue
        if line.endswith(" slayer") or line == "silver":
            kind = line[:-7].strip() if line != "silver" else "undead"
            tier = "Super Slayer" if kind in SUPER_SLAYERS else "Slayer"
            out.append((tier, 1, kind))
            continue
        for name, rx, cap, attr, pcap, keys in _COMPILED:
            if rx is None:
                continue
            m = rx.match(line)
            if not m:
                continue
            groups = m.groups()
            detail = ""
            if name == "Elemental Damage":
                detail, value = groups[0], int(groups[1])
            elif name == "Skill Bonus":
                detail, value = groups[0], int(groups[1])
            elif groups:
                value = int(groups[0])
            else:
                value = 1
            out.append((name, value, detail))
            break
    return out


def item_name(text):
    lines = [l.strip() for l in (text or "").replace("\r", "").split("\n") if l.strip()]
    return lines[0] if lines else "an item"


# -- the character ----------------------------------------------------------------------------

def player_snapshot():
    """The API.Player totals the headroom rule reads, as a plain dict (so tests can hand one in)."""
    snap = {}
    for name, rx, cap, attr, pcap, keys in _COMPILED:
        for a in (attr, pcap):
            if isinstance(a, str) and a not in snap:
                try:
                    snap[a] = int(getattr(API.Player, a) or 0)
                except Exception:
                    snap[a] = 0
    try:
        snap["MaxDefenseChanceIncrease"] = int(API.Player.MaxDefenseChanceIncrease or 0)
    except Exception:
        snap["MaxDefenseChanceIncrease"] = 0
    return snap


def player_cap(name, player):
    p = BY_NAME.get(name)
    if p is None:
        return None
    pcap = p[4]
    if pcap is None:
        return None
    if isinstance(pcap, str):
        v = int(player.get(pcap, 0) or 0)
        return v if v > 0 else 70
    if name == "Defense Chance Increase":
        v = int(player.get("MaxDefenseChanceIncrease", 0) or 0)
        return v if v > 0 else pcap
    return pcap


# -- scoring -------------------------------------------------------------------------------------

def score_props(props, profile, player, caps=None, add_back=None):
    """Score a parsed property list. Returns (score, contributions) where contributions is a list of
    (property name, value, points, detail) sorted by points, highest first.
    add_back: {property: value} the equipped piece in the same slot provides, given back to the headroom when
    scoring a candidate for that slot (compare mode)."""
    caps = caps or {}
    add_back = add_back or {}
    contributions = []
    total = 0.0
    for name, value, detail in props:
        p = BY_NAME.get(name)
        if p is None:
            continue
        w = float(profile.get(name, 0) or 0)
        if w == 0:
            continue
        item_cap = float(caps.get(name) or p[2] or 1)
        share = min(float(value), item_cap) / item_cap
        headroom = 1.0
        attr = p[3]
        pc = player_cap(name, player)
        if attr and pc:
            have = float(player.get(attr, 0) or 0) - float(add_back.get(name, 0) or 0)
            room = pc - have
            headroom = max(MIN_HEADROOM, min(1.0, room / item_cap))
        points = w * share * headroom
        total += points
        contributions.append((name, value, points, detail))
    contributions.sort(key=lambda c: -abs(c[2]))
    return round(total, 2), contributions


def reason_text(contributions, n=3):
    parts = []
    for name, value, points, detail in contributions[:n]:
        label = SHORT.get(name, name)
        if detail:
            label = "%s %s" % (detail, label) if name in ("Slayer", "Super Slayer", "Elemental Damage") else "%s +" % detail
        if name in ("Slayer", "Super Slayer", "Spell Channeling", "Night Sight", "Mage Armor", "Balanced"):
            parts.append("%s (%+.1f)" % (label, points))
        else:
            parts.append("%s %d (%+.1f)" % (label, value, points))
    return ", ".join(parts) if parts else "nothing the profile weighs"


def usable_essences(props, known):
    """The properties on this item whose essence the account could use: known at Basic or better."""
    out = []
    for name, value, detail in props:
        for key in knowledge_keys(name):
            if key.lower() in known:
                if name not in out:
                    out.append(name)
                break
    return out


def tier_for(score, props, keep_at, upgrade_margin, equipped_score=None, known=None, compare=False):
    """The first rule that matches: Upgrade, Keep, Unravel, Sell, Junk."""
    if not props:
        return "Junk", "no properties the table knows"
    if compare and equipped_score is not None and score - equipped_score >= float(upgrade_margin):
        return "Upgrade", "beats the equipped piece by %.1f" % (score - equipped_score)
    if score >= float(keep_at):
        return "Keep", "score %.1f is at or over %.1f" % (score, float(keep_at))
    usable = usable_essences(props, known or set())
    if usable:
        return "Unravel", "essence you can use: " + ", ".join(SHORT.get(u, u) for u in usable[:3])
    return "Sell", "magic, but nothing you can use or want"


def rate(text, profile, player, keep_at, upgrade_margin, caps=None, known=None, equipped_text=None, compare=False):
    """The whole decision for one item's tooltip text, as a dict."""
    props = parse_props(text)
    equipped_props = parse_props(equipped_text) if equipped_text else []
    add_back = {}
    for name, value, detail in equipped_props:
        add_back[name] = add_back.get(name, 0) + value
    score, contributions = score_props(props, profile, player, caps, add_back if compare else None)
    equipped_score = None
    if compare and equipped_text:
        equipped_score, _ = score_props(equipped_props, profile, player, caps, add_back)
    tier, why = tier_for(score, props, keep_at, upgrade_margin, equipped_score, known, compare and bool(equipped_text))
    return {
        "name": item_name(text), "props": props, "score": score, "contributions": contributions,
        "reason": reason_text(contributions), "tier": tier, "why": why,
        "equippedScore": equipped_score,
        "delta": None if equipped_score is None else round(score - equipped_score, 2),
    }


# -- the Artificers' rank (server command [artificerrank) ------------------------------------------

RANK_PREFIX = "[Artificer]"
_RANK_RE = re.compile(r"rank (\d+) of (\d+) \((.+?)\), standing ([\d,]+), (\d+) propert")


def parse_rank_lines(texts):
    """Journal lines from [artificerrank -> {"rank": n, "rankName": .., "standing": n, "known": {name lower: tier}}
    or None when the 'end' line has not arrived."""
    info = {"rank": 0, "rankName": "", "standing": 0, "known": {}, "member": True}
    seen_end = False
    for t in texts:
        t = (t or "").strip()
        if not t.startswith(RANK_PREFIX):
            continue
        body = t[len(RANK_PREFIX):].strip()
        if body == "end":
            seen_end = True
            continue
        m = _RANK_RE.search(body)
        if m:
            info["rank"] = int(m.group(1))
            info["rankName"] = m.group(3)
            info["standing"] = int(m.group(4).replace(",", ""))
            info["member"] = "not a member" not in body
            continue
        if body.startswith("not a member"):
            info["member"] = False
            continue
        for tier in ("Overcharged", "Full", "Refined", "Basic"):
            if body.startswith(tier + ":"):
                for name in body[len(tier) + 1:].split(","):
                    name = name.strip().lower()
                    if name:
                        info["known"][name] = tier
                break
    return info if seen_end else None


def request_rank(wait_seconds=4.0):
    """Ask the server and read the answer from the journal. Returns the parsed info or None."""
    try:
        API.ClearJournal()
    except Exception:
        pass
    API.Msg("[artificerrank")
    deadline = time.time() + wait_seconds
    while time.time() < deadline:
        API.Pause(0.3)
        try:
            entries = API.GetJournalEntries(wait_seconds + 1, RANK_PREFIX) or []
        except Exception:
            entries = []
        info = parse_rank_lines([e.Text for e in entries])
        if info is not None:
            return info
    return None


# -- Suggest -----------------------------------------------------------------------------------------

COMBAT_SKILLS = ("Swordsmanship", "Mace Fighting", "Fencing", "Wrestling", "Archery", "Throwing")
CASTER_SKILLS = ("Magery", "Necromancy", "Chivalry", "Spellweaving", "Mysticism", "Bushido", "Ninjitsu")


def suggest(player, skills, base_profile):
    """A profile for this character, with one plain line per decision.
    player: player_snapshot(); skills: {skill name: value}; base_profile: the weights to start from."""
    w = dict(base_profile)
    notes = []

    def sk(name):
        return float(skills.get(name, 0) or 0)

    def have(attr):
        return int(player.get(attr, 0) or 0)

    def set_w(name, value, line):
        if w.get(name) != value:
            w[name] = value
            notes.append(line)

    melee = max(sk(s) for s in COMBAT_SKILLS[:4]) if skills else 0
    ranged = max(sk("Archery"), sk("Throwing"))
    caster = max(sk(s) for s in ("Magery", "Necromancy", "Mysticism", "Spellweaving"))
    chiv = sk("Chivalry")
    necro = sk("Necromancy")
    healing = sk("Healing")

    hci = have("HitChanceIncrease")
    if hci >= 45:
        set_w("Hit Chance Increase", 1, "Hit Chance is at cap (45): weight dropped to 1.")
    elif hci < 30:
        set_w("Hit Chance Increase", 14, "Hit Chance is %d of 45: Hit Chance weight raised to 14." % hci)
    dci = have("DefenseChanceIncrease")
    if dci >= 45:
        set_w("Defense Chance Increase", 1, "Defense Chance is at cap (45): weight dropped to 1.")
    elif dci < 30:
        set_w("Defense Chance Increase", 10, "Defense Chance is %d of 45: weight raised to 10." % dci)
    ssi = have("SwingSpeedIncrease")
    if ssi >= 60:
        set_w("Swing Speed Increase", 1, "Swing Speed is at cap (60): weight dropped to 1.")
    elif melee >= 50 or ranged >= 50:
        set_w("Swing Speed Increase", 10, "Swing Speed is %d of 60: weight raised to 10." % ssi)
    di = have("DamageIncrease")
    if di >= 100:
        set_w("Damage Increase", 1, "Damage Increase is at cap (100): weight dropped to 1.")
    for res, attr, mx in (("Physical", "PhysicalResistance", "MaxPhysicResistance"), ("Fire", "FireResistance", "MaxFireResistance"),
                          ("Cold", "ColdResistance", "MaxColdResistance"), ("Poison", "PoisonResistance", "MaxPoisonResistance"),
                          ("Energy", "EnergyResistance", "MaxEnergyResistance")):
        cap = have(mx) or 70
        cur = have(attr)
        if cur >= cap:
            set_w("%s Resist Bonus" % res, 1, "%s resist %d of %d: weight dropped to 1." % (res, cur, cap))
        elif cur < cap - 20:
            set_w("%s Resist Bonus" % res, 5, "%s resist %d of %d: weight raised to 5." % (res, cur, cap))
    if chiv >= 50 or caster >= 50:
        set_w("Lower Mana Cost", 6, "%s %d: Lower Mana Cost weight raised to 6." % ("Chivalry" if chiv >= caster else "Magery", int(max(chiv, caster))))
        fc_cap = 4 if necro >= 50 else 2
        if have("FasterCasting") < fc_cap:
            set_w("Faster Casting", 5, "Faster Casting %d of %d (%s): weight raised to 5." % (have("FasterCasting"), fc_cap, "4 with Necromancy" if fc_cap == 4 else "2"))
        if caster >= 50 and have("FasterCastRecovery") < 6:
            set_w("Faster Cast Recovery", 5, "Faster Cast Recovery %d of 6: weight raised to 5." % have("FasterCastRecovery"))
        if caster >= 50:
            set_w("Spell Damage Increase", 6, "A caster skill of %d: Spell Damage weight raised to 6." % int(caster))
            if have("LowerReagentCost") < 100:
                set_w("Lower Reagent Cost", 4, "Lower Reagent Cost %d of 100: weight raised to 4." % have("LowerReagentCost"))
    else:
        for name in ("Spell Damage Increase", "Faster Cast Recovery", "Lower Reagent Cost"):
            set_w(name, 0, "No casting skill over 50: %s set to 0." % name)
    if melee < 50 and ranged < 50:
        for name in ("Hit Life Leech", "Hit Stamina Leech", "Hit Mana Leech", "Hit Lower Defense", "Hit Lower Attack"):
            set_w(name, 0, "No weapon skill over 50: %s set to 0." % name)
    if healing >= 50:
        set_w("Bonus Dexterity", 5, "Healing %d: Dexterity weight raised to 5 (faster bandages)." % int(healing))
        set_w("Hit Points Regen", 3, "Healing %d: Hit Points Regen kept at 3; Enhance Potions stays low." % int(healing))
    else:
        set_w("Enhance Potions", 5, "No Healing: Enhance Potions weight raised to 5 (potions carry you).")
    if sk("Lumberjacking") >= 50 or sk("Mining") >= 50:
        set_w("Bountiful", 3, "A gathering skill over 50: Bountiful weight raised to 3.")
        set_w("Prospector", 3, "A gathering skill over 50: Prospector weight raised to 3.")
    if not notes:
        notes.append("Nothing stood out: the starter weights fit this character as it is.")
    return w, notes


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