from config import CNY_TO_USD_RATE # ══════════════════════════════════════════════════════════════════════════════ # PARSER — raw API JSON → clean item dicts # ══════════════════════════════════════════════════════════════════════════════ def cny_to_usd(cny_price) -> float: """Convert a CNY price value to USD using the configured exchange rate.""" if cny_price is None: return 0.0 return float(cny_price) * CNY_TO_USD_RATE def _extract_tag(tags: list[str], prefix: str, strip: str = "") -> str: """Return the human-readable value of the first tag matching *prefix*.""" for tag in tags: if tag.startswith(prefix + "#"): raw = tag.split("#", 1)[-1] if strip: raw = raw.replace(strip, "") return raw.replace("_", " ").title() return "Unknown" def extract_and_enrich_items(api_data: dict) -> list[dict]: """ Merge the 'assets' list with the 'classinfos' lookup table found in the SteamDT API response and return a list of enriched item dicts. """ items_list: list = [] classinfos: dict = {} data_block = api_data.get("data", api_data) if isinstance(data_block, dict): inventory = data_block.get("inventory", {}) if isinstance(inventory, dict): items_list = inventory.get("assets", []) classinfos = inventory.get("classinfos", {}) else: items_list = data_block.get("inventory", data_block.get("list", [])) classinfos = data_block.get("classinfos", {}) elif isinstance(data_block, list): items_list = data_block classinfos = api_data.get("classinfos", {}) cleaned: list[dict] = [] for item in items_list: asset_id = str(item.get("assetId")) if not asset_id or asset_id == "None": continue info = classinfos.get(str(item.get("classinfoKey", "")), {}) tags = info.get("tags", []) name: str = ( info.get("marketHashName") or info.get("hashName") or f"Unknown ({item.get('classinfoKey', '?')})" ) price = cny_to_usd(item.get("evaluatePrice")) rarity = _extract_tag(tags, "Rarity", strip="Rarity_") if rarity == "Unknown": rarity = "Normal" quality = _extract_tag(tags, "Quality", strip="Quality_") if quality == "Unknown": quality = "Normal" weapon_type = _extract_tag(tags, "Type", strip="Type_") item_type = "Normal" if "StatTrak™" in name: item_type = "StatTrak" elif "Souvenir" in name: item_type = "Souvenir" is_knife = ( "Knife" in weapon_type or "★" in name or any(k in name for k in ("Karambit", "Butterfly", "M9 Bayonet")) ) is_glove = "Glove" in weapon_type or "Gloves" in name cleaned.append( { "assetId": asset_id, "name": name, "price": price, "rarity": rarity, "quality": quality, "type": item_type, "weaponType": weapon_type, "isKnife": is_knife, "isGlove": is_glove, } ) return cleaned