"""Fetch and parse Wago.tools build feed.

Response shape (as of 2026-05): a JSON object keyed by product
(e.g., "wow", "wow_classic_era") whose values are arrays of records
like `{"version": "11.2.7.59185", "created_at": "..."}`. The build
number is the integer suffix of `version`.

If Wago changes shape, adjust `parse_builds` and refresh the fixture.
"""
from dataclasses import dataclass
from typing import Iterable
from bot.lib.http import fetch_json

BUILDS_URL = "https://wago.tools/api/builds"


@dataclass(frozen=True)
class Build:
    branch: str
    version: str  # full string, e.g. "11.2.7.59185"
    build: int    # integer suffix, e.g. 59185


def _build_int(version: str) -> int:
    # version looks like "11.2.7.59185"; the build number is the last dotted segment.
    parts = version.split(".")
    return int(parts[-1])


def parse_builds(raw) -> list[Build]:
    out: list[Build] = []
    if isinstance(raw, dict):
        items: Iterable = raw.items()
    else:
        # Some responses are arrays of {"product": "...", ...}.
        items = ((row.get("product"), [row]) for row in raw)
    for branch, records in items:
        if not branch or not records:
            continue
        for rec in records:
            ver = rec.get("version")
            if not ver:
                continue
            try:
                out.append(Build(branch=branch, version=ver, build=_build_int(ver)))
            except (ValueError, IndexError):
                continue
    return out


def latest_per_branch(builds: list[Build]) -> dict[str, Build]:
    latest: dict[str, Build] = {}
    for b in builds:
        cur = latest.get(b.branch)
        if cur is None or b.build > cur.build:
            latest[b.branch] = b
    return latest


def fetch_builds() -> list[Build]:
    return parse_builds(fetch_json(BUILDS_URL))
