Metadata-Version: 2.4
Name: wynntilsresolver
Version: 2.0.0
Summary: A simple resolver to analyze wynntils' encoded equipment in chat.
Keywords: wynntils,resolver,wynncraft
Author: FYWinds
Author-email: FYWinds <i@windis.cn>
License-Expression: MIT
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Requires-Dist: httpx==0.27.0
Requires-Dist: rich>=14.3.4 ; extra == 'cli'
Requires-Dist: typer>=0.20.1 ; extra == 'cli'
Requires-Python: >=3.11
Project-URL: Changelog, https://github.com/fywinds/WynntilsResolver
Project-URL: Documentation, https://github.com/fywinds/WynntilsResolver
Project-URL: Homepage, https://github.com/fywinds/WynntilsResolver
Project-URL: Repository, https://github.com/fywinds/WynntilsResolver
Provides-Extra: cli
Description-Content-Type: text/markdown

# Wynntils Resolver
A resolver to analyze Artemis' encoded items in chat: gear, tomes, charms, crafted gear, crafted consumables and mounts.

### Requires
[![Python >= 3.11](https://img.shields.io/badge/python>=3.11-3670A0?style=for-the-badge&logo=python&logoColor=ffdd54)](https://www.python.org/)

### Install
```bash
pip install wynntilsresolver -U
```


### Supported Encodings
Artemis encoding versions `0`–`3` (`ItemTransformingVersion` V1–V4) are accepted; any other version byte raises
`UnsupportedVersion`. Encoding defaults to the latest version, like Artemis.
Since V3 the identification block carries the stat value instead of the internal roll, so `Identification.roll` is
estimated from the value (the roll closest to `value / base` within the valid range) rather than read from the item.
V4 adds the in-game identification meter as a number (`Identification.meter`, 0–36), real powder tiers (`A7`) and the
powder special (`Gear.powder_special`). The format itself is specified in Wynntils'
[ENCODING_STANDARD.md](https://github.com/Wynntils/Wynntils/blob/main/docs/ENCODING_STANDARD.md).

Every item type Artemis encodes is supported:

| Type byte | Item                | Entity              | Resolver                    |
|-----------|---------------------|---------------------|-----------------------------|
| 0         | gear                | `Gear`              | `GearResolver`              |
| 1         | tome                | `Tome`              | `TomeResolver`              |
| 2         | charm               | `Charm`             | `CharmResolver`             |
| 3         | crafted gear        | `CraftedGear`       | `CraftedGearResolver`       |
| 4         | crafted consumable  | `CraftedConsumable` | `CraftedConsumableResolver` |
| 5         | mount               | `Mount`             | `MountResolver`             |

### CLI
```bash
pip install "wynntilsresolver[cli]"

wynntilsresolver "<encoded item>"                 # pretty table
echo "<encoded item>" | wynntilsresolver --json   # machine-readable, reads stdin
wynntilsresolver --help
```

### Usage
#### Decode any item
`decode` reads the type byte and hands the string to the matching resolver; `encode` picks the resolver from the
entity's class. Both are what the CLI uses.
```python
from wynntilsresolver import Gear, PowderSpecialTier, decode, encode
from wynntilsresolver.enums import PowderSpecial

weathered = "󰀃󰄀󰉗󶕡󷑨󶕲󶕤󰀃󰔀󲌨󱼀󴕀󲀀󱅋󱸀󰐴󲐀󵅂󲐁󰐃󰎎󳣀󰤇󰔄􏿮"
item = decode(weathered)
assert isinstance(item, Gear) and item.name == "Weathered"
assert item.powders == ("A7", "A7", "A7")
assert item.powder_special == PowderSpecialTier(PowderSpecial.WIND_PRISON, 7)
assert item.identifications[-1].meter == 36  # walkSpeed, a full meter
assert encode(item) == weathered  # V4 strings re-encode byte for byte
```

#### Decode a gear item
`GearResolver.decode` turns a chat string into a `Gear`: a frozen dataclass with what the item says about itself,
independent of the encoding version it came in.
```python
from wynntilsresolver import GearResolver, Identification, ShinyStat

shiny_warp = "󰀁󰄀󰉗󶅲󷀀󰌉󰄁󲤲󴖴󰅚󱅤󷼢󵥔󱢏󰍕󱦯󰥌󱜻󵘄󱹀󵇨󰉧󲛖󰑱󰐃󰏷󻰅󰈆󰄁󰃿"
gear = GearResolver.decode(shiny_warp)

assert gear.name == "Warp"
assert gear.identifications[0] == Identification(id="rawAgility", internal_id=41, base=25, roll=None, value=25)
assert gear.identifications[-1] == Identification(id="raw2ndSpellCost", internal_id=38, base=-299, roll=113, value=-338)
assert gear.powder_slots == 3
assert gear.powders == ("A6", "A6", "A6")
assert gear.shiny == ShinyStat(name="mobsKilled", internal_id=1, display_name="Mobs Killed", value=0, reroll=1)
assert gear.rerolls == 2
```
`roll is None` marks a pre-identified (fixed) stat; `Identification.perfect` tells whether the roll is the best
possible one. Since Artemis V3 the wire carries the stat value instead of the roll, so rolls decoded from V3/V4 strings
are derived from the value and flagged `estimated=True`; the in-game meter travels along as `meter` (a stage 0–36,
`None` when the item was shared without one). Spell costs keep the API's sign (negative) even though Artemis stores
them inverted.

The blocks behind an item stay reachable when the wire details matter:
```python
resolver = GearResolver.from_utf16(shiny_warp)
resolver.version                          # 1 -> Artemis' ItemTransformingVersion V2
resolver.identifications.extended         # True: every base is on the wire
resolver.to_item() == gear
```

#### Encode a gear item
`GearResolver.encode` produces Artemis' chat encoding. Blocks are only written when Artemis would write them
(no reroll block for 0 rerolls, no shiny block without a shiny, ...). `extended=True` puts every base on the wire so
readers without an up-to-date item database can still decode it; without it, readers fill in the pre-identified
stats from their own database.
```python
from wynntilsresolver import Gear, GearResolver, Identification

gear = Gear(
    name="Masterwork Cataclysm",
    identifications=(Identification("rawHealth", 56, -6000, 70, -4200),),
    powder_slots=3,
    powders=("A6", "A6", "A6"),
    rerolls=2,
)
chat_string = GearResolver.encode(gear, extended=True)  # latest encoding version (Artemis V4) by default
decoded = GearResolver.decode(chat_string)
assert (decoded.name, decoded.powders, decoded.rerolls) == (gear.name, gear.powders, gear.rerolls)
# V3 and V4 carry the value, not the roll: the roll comes back as an estimate derived from it
assert decoded.identifications == (Identification("rawHealth", 56, -6000, 70, -4200, estimated=True),)

assert GearResolver.decode(GearResolver.encode(gear, version=1, extended=True)) == gear  # V2 keeps the roll
```
Every real Artemis string in the test suite (V1–V4) re-encodes byte for byte: the meter and perfect flag stay on the
entity, and the perfect flag written is `Identification.perfect`. Encoding to an older version loses what it cannot
carry, as in Artemis: V3 drops the powder special and rejects tier 7 powders, V1/V2 carry neither value nor meter.

#### Tomes and charms
Same blocks as gear, minus powders and shiny. A charm's `base` section of the item database is treated as
identifications, like Artemis does.
```python
from wynntilsresolver import Charm, Identification, Tome, decode, encode

tome = Tome("Blooming Tome of Defensive Mastery III", (Identification("rawHealth", 56, 300, 121, 363, True),), rerolls=1)
assert decode(encode(tome)) == tome
charm = Charm("Charm of the Void", (Identification("damageFromMobs", 8, 12, 108, 13, True),))
assert decode(encode(charm)) == charm
```

#### Crafted items
Crafted gear and consumables carry their whole definition on the wire, so no item database lookup is needed. Their
name is not part of the encoding (it is the chat text around it); `name` is `None` unless a name block happens to be
present and `display_name` falls back to a generic one. Stat ids, damage types and the like come from
`wynntilsresolver.enums`, whose values are Artemis' wire ids.
```python
from wynntilsresolver import CraftedConsumable, CraftedGear, CraftedStat, DamageRange, GearRequirements, decode, encode
from wynntilsresolver.enums import AttackSpeed, ClassType, ConsumableEffect, ConsumableType, DamageType, Element, GearType, Skill

spear = CraftedGear(
    gear_type=GearType.SPEAR,
    durability=200,
    max_durability=250,
    requirements=GearRequirements(level=80, class_type=ClassType.WARRIOR, skills=((Skill.STRENGTH, 30),)),
    attack_speed=AttackSpeed.NORMAL,
    dps=300,
    damages=(DamageRange(DamageType.NEUTRAL, 100, 150), DamageRange(DamageType.EARTH, 20, 40)),
    health=100,
    defences=((Element.EARTH, 15),),
    identifications=(CraftedStat("rawStrength", 62, 5, perfect=True),),
    powder_slots=2,
    powders=("E6",),
)
assert decode(encode(spear)) == spear
assert spear.display_name == "Crafted Spear"

potion = CraftedConsumable(
    consumable_type=ConsumableType.POTION,
    uses=2,
    max_uses=3,
    level=50,
    effects=((ConsumableEffect.HEAL, 500), (ConsumableEffect.DURATION, 30)),
    identifications=(CraftedStat("manaRegen", 34, 12),),
)
assert decode(encode(potion)) == potion
```

#### Mounts
A `Mount` enforces on construction the rules Artemis applies after decoding (stat and potential caps, wyverns carry
altitude instead of jump height, colours must fit the mount, max stats must add up to the potential), so an invalid
mount raises `ValueError` whether it comes from a chat string or from your own code. Colours resolve through
Static-Storage's `mount_colors.json`; unknown ids become colour 0 like in Artemis.
```python
from wynntilsresolver import Mount, MountStatValue, decode, encode
from wynntilsresolver.enums import MountStat, MountType

stats = [s for s in MountStat if s is not MountStat.ALTITUDE]
horse = Mount(
    MountType.HORSE,
    potential=1200,
    energy=80,
    max_energy=100,
    stats={s: MountStatValue(100, 150) for s in stats},
    max_stats=dict.fromkeys(stats, 150),
)
assert decode(encode(horse)) == horse
```

#### Create your own resolver
A resolver is a codec for one entity. Declare its blocks as annotated attributes in wire order (`Block | None`
marks a block the item may omit), then map blocks to your entity in `to_item` and back in `from_item`;
`decode` / `encode` come with `ItemResolver`.
```python
from dataclasses import dataclass
from typing import Self

from wynntilsresolver import ItemResolver
from wynntilsresolver.blocks import GearItem, Name, Reroll


@dataclass(frozen=True)
class Rerolled:
    name: str
    rerolls: int


class RerollResolver(ItemResolver[Rerolled]):
    item_type: GearItem
    name: Name
    reroll: Reroll | None

    def to_item(self) -> Rerolled:
        return Rerolled(self.name.name, self.reroll.rerolls if self.reroll else 0)

    @classmethod
    def from_item(cls, item: Rerolled, version: int = 2) -> Self:
        resolver = cls(version)
        resolver.item_type = GearItem()
        resolver.name = Name(item.name)
        if item.rerolls:  # Artemis omits the block for 0 rerolls; optional blocks default to None
            resolver.reroll = Reroll(item.rerolls)
        return resolver


chat_string = RerollResolver.encode(Rerolled("Warp", 2), version=1)
assert RerollResolver.decode(chat_string) == Rerolled("Warp", 2)
assert RerollResolver.from_utf16(chat_string).to_bytes() == bytes([0, 1, 1, 0, 2, *b"Warp", 0, 5, 2, 255])
```
The resolver owns the framing (`[0][version]`, one `[start byte][payload]` per block, `[255]`). A new block
subclasses `Block`, sets `_start_byte` and implements `decode(reader, ctx)` / `encode(writer, version)` over
`ByteReader` / `ByteWriter`; anything its layout needs from the stream (`ctx.version`) or from an earlier block
(`ctx.require(Name)`) comes through the `DecodeContext`. See `wynntilsresolver/blocks/` and `wynntilsresolver/items/`.


### Data Files
The item database, id table, shiny table and mount colour table are loaded on first use, not at import: api-sourced
files are downloaded when missing or older than 24 hours and cached under `DATA_LOCATION`. Call
`wynntilsresolver.data_store.bootstrap()` to load everything up front (e.g. at service start-up).

Decoding resolves stat ids, item bases and shiny ids against a `DataStore`; the module-level `data_store` is the
default and any `decode` / `from_utf16` / `from_bytes` accepts another one:
```python
import pathlib

from wynntilsresolver import GearResolver
from wynntilsresolver.datastore import DataStore

snapshot = DataStore(pathlib.Path("cache"), itemdb_path=pathlib.Path("snapshots/itemdb-2026-09.json"))
gear = GearResolver.decode(shiny_warp, store=snapshot)
```

#### Environment Variables
- `DATA_LOCATION`: The directory to store the cache files. Default: `pathlib.Path.home() / "AppData" / "Local" / "wynntilsresolver"` or
`pathlib.Path.home() / ".local" / "share" / "wynntilsresolver"`
- `ITEMDB_PATH`: The path to the itemdb file.
- `SHINY_TABLE_PATH`: The path to the shiny table file.
- `ID_TABLE_PATH`: The path to the id table file.
- `MOUNT_COLORS_PATH`: The path to the mount colour table file.
- `http_proxy` / `https_proxy` / `all_proxy` (or upper-case): proxy used for the downloads.
> Note that setting the path to those files will disable auto update.

### Benchmark
Cataclysm V3 sample, Python 3.11, data files cached locally (`python -m timeit`-style loop of 10000 calls):
```
GearResolver.decode: ~52000 ops/s
GearResolver.encode: ~115000 ops/s
```
Script:
```python
import timeit

from wynntilsresolver import GearResolver

chat_string = "󰀂󰄀󰉍󶅳󷑥󷉷󶽲󶬠󴍡󷑡󶍬󷥳󶴀󰌆󰁋󰰄󱩌󳐄󰬸󼽁󰔣󴵎󰐟󲔊󰐣󲜊󰐣󰐃󰀅󰋿"
gear = GearResolver.decode(chat_string)

for label, call in [("decode", lambda: GearResolver.decode(chat_string)), ("encode", lambda: GearResolver.encode(gear))]:
    elapsed = timeit.timeit(call, number=10000)
    print(f"{label}: {10000 / elapsed:.0f} ops/s")
```