"""Build the four generated catalogue pages of the EvoMO reference section.

The single writer of ``algorithms.md``, ``problems.md``, ``operators.md`` and
``utils.md``: a hand edit to any of them is erased by the next run.

It reads ``src/evomo/`` with ``ast`` and the standard library only — no
``evomo``, ``evox``, ``evoxc`` or numpy import — so the docs toolchain alone can
regenerate every table and the Sphinx build needs no runtime install. The one
mode that imports the live package is ``--verify``, a maintainer check that
cross-checks the committed rows against ``evomo.algorithms`` / ``evomo.problems``
/ ``evomo.operators`` / ``evomo.utils`` (see ``--help``).

One file is right because there is one parser and four emitters: module
constants, inherited config fields and ``n_con`` properties are resolved once
and consumed by every page. Row counts, family lists and ``TAKES_CV`` values
come from the parsed ``__all__`` lists, so a count in a page is never hardcoded.
"""

from __future__ import annotations

import argparse
import ast
import dataclasses
import math
import operator
import re
import sys
from pathlib import Path

REPO_ROOT = Path(__file__).resolve().parents[2]
SRC = REPO_ROOT / "src" / "evomo"
OUT_DIR = Path(__file__).resolve().parent

#: Rendered in a table cell for "no value": a required config field, or an
#: unconstrained problem's ``n_con``.
MISSING = "\u2014"

#: The four config fields every algorithm forces the caller to supply.
MANDATORY_ALGORITHM_FIELDS = ("pop_size", "n_objs", "lb", "ub")

#: Catalogue order of the problem families (alphabetical, and stable on purpose:
#: a new module is appended by editing this tuple, never by editing a page).
NUMERICAL_FAMILIES = ("dtlz", "lsmop", "maf", "wfg", "zdt")
CONSTRAINED_FAMILIES = ("ctp", "dascmop", "doc", "fcp", "lircmop", "lscm", "mw", "sdc")

#: ``evomo.operators`` subpackages, in dependency order, and the modules of
#: ``evomo.utils`` whose public names the utils page lists.
OPERATOR_SUBPACKAGES = ("selection", "sampling", "crossover", "mutation")
UTIL_MODULES = ("config", "pf", "state", "tensor_ops")

GENERATED = "<!-- generated by _generate_tables.py; do not edit -->"


def _fail(message: str) -> None:
    """Abort with a one-line diagnostic naming the offending symbol."""
    raise SystemExit(f"_generate_tables.py: error: {message}")


# --- AST model -----------------------------------------------------------------
@dataclasses.dataclass(frozen=True)
class SourceModule:
    """One parsed module: its constants, classes, functions and ``__all__``."""

    rel: str
    tree: ast.Module
    constants: dict[str, ast.expr]
    classes: dict[str, ast.ClassDef]
    functions: dict[str, ast.FunctionDef]
    all_names: tuple[str, ...] | None


@dataclasses.dataclass(frozen=True)
class Field:
    """A dataclass field: its name and the body default expression (if any)."""

    name: str
    annotation: str
    default: ast.expr | None


def _load(path: Path) -> SourceModule:
    """Parse ``path`` into a :class:`SourceModule` without importing it."""
    tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
    constants: dict[str, ast.expr] = {}
    classes: dict[str, ast.ClassDef] = {}
    functions: dict[str, ast.FunctionDef] = {}
    for node in tree.body:
        if isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name):
            constants[node.targets[0].id] = node.value
        elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) and node.value is not None:
            constants[node.target.id] = node.value
        elif isinstance(node, ast.ClassDef):
            classes[node.name] = node
        elif isinstance(node, ast.FunctionDef):
            functions[node.name] = node
    all_names: tuple[str, ...] | None = None
    raw_all = constants.get("__all__")
    if raw_all is not None:
        try:
            all_names = tuple(ast.literal_eval(raw_all))
        except (ValueError, SyntaxError) as exc:  # pragma: no cover - malformed source
            _fail(f"{path}: __all__ is not a literal list of names ({exc})")
    return SourceModule(
        rel=path.relative_to(SRC).as_posix(),
        tree=tree,
        constants=constants,
        classes=classes,
        functions=functions,
        all_names=all_names,
    )


def _module_constant(module: SourceModule, name: str):
    """Resolve a module-level constant to its literal value, or raise."""
    return _resolve(module.constants[name], _Context(module))


# --- Static evaluator ----------------------------------------------------------
class _Unresolved(Exception):
    """Raised when an expression cannot be reduced to a literal without running it."""


@dataclasses.dataclass(frozen=True)
class _Context:
    """Resolution environment: module, class constants, field defaults, bindings."""

    module: SourceModule
    class_attrs: dict[str, ast.expr] = dataclasses.field(default_factory=dict)
    field_defaults: dict[str, ast.expr] = dataclasses.field(default_factory=dict)
    bindings: dict[str, object] = dataclasses.field(default_factory=dict)

    def child(self, **bindings: object) -> "_Context":
        return dataclasses.replace(self, bindings={**self.bindings, **bindings})


_MATH = {"ceil": math.ceil, "floor": math.floor, "sqrt": math.sqrt}
_BINOPS = {
    ast.Add: operator.add,
    ast.Sub: operator.sub,
    ast.Mult: operator.mul,
    ast.Div: operator.truediv,
    ast.FloorDiv: operator.floordiv,
    ast.Mod: operator.mod,
    ast.Pow: operator.pow,
}


def _resolve(node: ast.expr | None, ctx: _Context, depth: int = 0):
    """Reduce ``node`` to a Python literal value.

    Understands literals, module constants, ``self.<field>`` /
    ``self.<ClassVar>``, unary and binary arithmetic on numbers,
    ``math.ceil``/``math.floor``/``math.sqrt``, and a call to a module-level
    helper whose body is a single ``return`` (``wfg._adjust_d(2, 12)``). Every
    other expression raises :class:`_Unresolved` so callers fall back instead
    of guessing.
    """
    if node is None:
        raise _Unresolved("empty expression")
    if depth > 24:
        raise _Unresolved("recursion limit")
    if isinstance(node, ast.Constant):
        return node.value
    if isinstance(node, ast.Name):
        if node.id in ctx.bindings:
            return ctx.bindings[node.id]
        if node.id in ctx.class_attrs:
            return _resolve(ctx.class_attrs[node.id], ctx, depth + 1)
        if node.id in ctx.module.constants:
            return _resolve(ctx.module.constants[node.id], ctx, depth + 1)
        raise _Unresolved(f"unknown name {node.id}")
    if isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name) and node.value.id == "self":
        if node.attr in ctx.field_defaults:
            return _resolve(ctx.field_defaults[node.attr], ctx, depth + 1)
        if node.attr in ctx.class_attrs:
            return _resolve(ctx.class_attrs[node.attr], ctx, depth + 1)
        raise _Unresolved(f"unknown attribute self.{node.attr}")
    if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.USub):
        return -_resolve(node.operand, ctx, depth + 1)
    if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.UAdd):
        return _resolve(node.operand, ctx, depth + 1)
    if isinstance(node, ast.BinOp) and type(node.op) in _BINOPS:
        left = _resolve(node.left, ctx, depth + 1)
        right = _resolve(node.right, ctx, depth + 1)
        return _BINOPS[type(node.op)](left, right)
    if isinstance(node, (ast.Tuple, ast.List)):
        return tuple(_resolve(item, ctx, depth + 1) for item in node.elts)
    if isinstance(node, ast.Call):
        return _resolve_call(node, ctx, depth)
    raise _Unresolved(f"unsupported expression {ast.unparse(node)}")


def _resolve_call(node: ast.Call, ctx: _Context, depth: int):
    """Evaluate a whitelisted call: a math helper or a single-return module function."""
    args = [_resolve(arg, ctx, depth + 1) for arg in node.args]
    if node.keywords:
        raise _Unresolved("keyword arguments in a constant call")
    func = node.func
    if isinstance(func, ast.Attribute) and isinstance(func.value, ast.Name) and func.value.id == "math":
        if func.attr in _MATH:
            return _MATH[func.attr](*args)
        raise _Unresolved(f"math.{func.attr}")
    if isinstance(func, ast.Name) and func.id in ctx.module.functions:
        helper = ctx.module.functions[func.id]
        body = [stmt for stmt in helper.body if not _is_docstring(stmt)]
        if len(body) != 1 or not isinstance(body[0], ast.Return):
            raise _Unresolved(f"helper {func.id} is not a single return")
        params = [arg.arg for arg in helper.args.args]
        if len(params) != len(args):
            raise _Unresolved(f"helper {func.id} arity")
        return _resolve(body[0].value, ctx.child(**dict(zip(params, args))), depth + 1)
    raise _Unresolved(f"call to {ast.unparse(func)}")


def _is_docstring(stmt: ast.stmt) -> bool:
    return isinstance(stmt, ast.Expr) and isinstance(stmt.value, ast.Constant) and isinstance(stmt.value.value, str)


def _literal_text(value: object) -> str:
    """Render a resolved literal as table-cell text (deterministic, repr-based)."""
    if isinstance(value, bool):
        return "True" if value else "False"
    if isinstance(value, str):
        return repr(value)
    if isinstance(value, tuple):
        items = ", ".join(_literal_text(item) for item in value)
        if len(value) == 1:
            return f"({items},)"
        return f"({items})"
    if isinstance(value, int):
        return str(value)
    if isinstance(value, float):
        return repr(value)
    raise _Unresolved(f"cannot render {type(value).__name__}")


# --- Class introspection -------------------------------------------------------
def _is_dataclass(cls: ast.ClassDef) -> bool:
    for decorator in cls.decorator_list:
        text = ast.unparse(decorator)
        if text == "dataclass" or text.startswith(("dataclass(", "dataclasses.dataclass")):
            return True
    return False


def _is_classvar(annotation: ast.expr | None) -> bool:
    if annotation is None:
        return False
    text = ast.unparse(annotation)
    return text == "ClassVar" or text.startswith("ClassVar[")


def _own_fields(cls: ast.ClassDef) -> list[Field]:
    fields = []
    for stmt in cls.body:
        if isinstance(stmt, ast.AnnAssign) and isinstance(stmt.target, ast.Name) and not _is_classvar(stmt.annotation):
            fields.append(Field(stmt.target.id, ast.unparse(stmt.annotation), stmt.value))
    return fields


def _fields(module: SourceModule, cls: ast.ClassDef) -> list[Field]:
    """Dataclass fields in declaration order, base classes first, overrides in place.

    Only a base class decorated with ``@dataclass`` contributes fields: a plain
    mixin's annotations are not dataclass fields of the subclass (``_LIRCMOPConfig``
    declares ``_N_IQ``/``_M_MAX`` but ``LIRCMOP1`` does not carry them).
    """
    collected: dict[str, Field] = {}
    for base in cls.bases:
        if not isinstance(base, ast.Name):
            continue
        parent = module.classes.get(base.id)
        if parent is None or not _is_dataclass(parent):
            continue
        for field in _fields(module, parent):
            collected[field.name] = field
    for field in _own_fields(cls):
        collected[field.name] = field
    return list(collected.values())


def _class_attrs(module: SourceModule, cls: ast.ClassDef, seen: tuple[str, ...] = ()) -> dict[str, ast.expr]:
    """Class-body constants (``ClassVar`` values and plain assignments), inherited."""
    attrs: dict[str, ast.expr] = {}
    for base in cls.bases:
        if not isinstance(base, ast.Name) or base.id in seen:
            continue
        parent = module.classes.get(base.id)
        if parent is not None:
            attrs.update(_class_attrs(module, parent, seen + (cls.name,)))
    for stmt in cls.body:
        if isinstance(stmt, ast.AnnAssign) and isinstance(stmt.target, ast.Name) and stmt.value is not None:
            attrs[stmt.target.id] = stmt.value
        elif isinstance(stmt, ast.Assign):
            for target in stmt.targets:
                if isinstance(target, ast.Name):
                    attrs[target.id] = stmt.value
    return attrs


def _context(module: SourceModule, cls: ast.ClassDef) -> _Context:
    defaults = {field.name: field.default for field in _fields(module, cls) if field.default is not None}
    return _Context(module=module, class_attrs=_class_attrs(module, cls), field_defaults=defaults)


def _find_property(module: SourceModule, cls: ast.ClassDef, name: str) -> ast.FunctionDef | None:
    """Find ``name`` as a property on ``cls`` or an ancestor class."""
    for stmt in cls.body:
        if isinstance(stmt, ast.FunctionDef) and stmt.name == name:
            return stmt
    for base in cls.bases:
        if not isinstance(base, ast.Name):
            continue
        parent = module.classes.get(base.id)
        if parent is not None:
            found = _find_property(module, parent, name)
            if found is not None:
                return found
    return None


def _n_con(cls: ast.ClassDef, module: SourceModule, warnings: list[str]) -> int | None:
    """Statically resolve the ``n_con`` property body of ``cls``."""
    prop = _find_property(module, cls, "n_con")
    if prop is None:
        return None
    returns = [stmt for stmt in prop.body if isinstance(stmt, ast.Return)]
    if len(returns) != 1 or returns[0].value is None:
        warnings.append(f"{module.rel}: {cls.name}.n_con is not a single return; n_con left as {MISSING}")
        return None
    try:
        value = _resolve(returns[0].value, _context(module, cls))
    except _Unresolved as exc:
        warnings.append(
            f"{module.rel}: {cls.name}.n_con = {ast.unparse(returns[0].value)!r} is not statically resolvable "
            f"({exc}); n_con left as {MISSING}"
        )
        return None
    if not isinstance(value, int) or isinstance(value, bool):
        warnings.append(f"{module.rel}: {cls.name}.n_con resolved to a non-int ({value!r}); n_con left as {MISSING}")
        return None
    return value


# --- Rows ----------------------------------------------------------------------
@dataclasses.dataclass(frozen=True)
class AlgorithmRow:
    config: str
    maker: str
    family: str
    module: str
    takes_cv: bool
    fields: tuple[Field, ...]
    fields_text: str

    @property
    def field_names(self) -> tuple[str, ...]:
        return tuple(field.name for field in self.fields)


@dataclasses.dataclass(frozen=True)
class ProblemRow:
    name: str
    family: str
    package: str
    module: str
    fields: tuple[Field, ...]
    fields_text: str
    constrained: bool
    n_con: int | None

    @property
    def field_names(self) -> tuple[str, ...]:
        return tuple(field.name for field in self.fields)

    @property
    def n_con_text(self) -> str:
        return MISSING if self.n_con is None else str(self.n_con)


@dataclasses.dataclass(frozen=True)
class KernelRow:
    name: str
    module: str
    contract: str


def _fields_cell(fields: list[Field], defaults: dict[str, str]) -> str:
    return ", ".join(f"`{field.name}={defaults[field.name]}`" for field in fields)


def _algorithm_defaults(module: SourceModule, cls: ast.ClassDef, maker: ast.FunctionDef) -> dict[str, str]:
    ctx = _context(module, cls)
    maker_defaults = _signature_defaults(maker)
    rendered: dict[str, str] = {}
    for field in _fields(module, cls):
        if field.default is not None:
            try:
                rendered[field.name] = _literal_text(_resolve(field.default, ctx))
                continue
            except _Unresolved:
                pass
        if field.name in MANDATORY_ALGORITHM_FIELDS:
            rendered[field.name] = MISSING
        else:
            rendered[field.name] = maker_defaults.get(field.name, MISSING)
    return rendered


def _problem_defaults(module: SourceModule, cls: ast.ClassDef, warnings: list[str]) -> dict[str, str]:
    ctx = _context(module, cls)
    rendered: dict[str, str] = {}
    for field in _fields(module, cls):
        if field.default is None:
            rendered[field.name] = MISSING
            continue
        try:
            rendered[field.name] = _literal_text(_resolve(field.default, ctx))
        except _Unresolved:
            warnings.append(
                f"{module.rel}: {cls.name}.{field.name} default {ast.unparse(field.default)!r} is not statically "
                f"resolvable; left as {MISSING}"
            )
            rendered[field.name] = MISSING
    return rendered


def _signature_defaults(func: ast.FunctionDef) -> dict[str, str]:
    """Keyword-only (and positional) defaults of a ``make_*`` signature, as source text."""
    defaults: dict[str, str] = {}
    positional = list(func.args.posonlyargs) + list(func.args.args)
    for arg, default in zip(positional[len(positional) - len(func.args.defaults) :], func.args.defaults):
        defaults[arg.arg] = ast.unparse(default)
    for arg, default in zip(func.args.kwonlyargs, func.args.kw_defaults):
        if default is not None:
            defaults[arg.arg] = ast.unparse(default)
    return defaults


def _calls_name(func: ast.FunctionDef, name: str) -> bool:
    return any(
        isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == name for node in ast.walk(func)
    )


def _config_maker(module: SourceModule, config: str) -> ast.FunctionDef:
    """The single ``make_*`` of ``module`` that builds ``config``."""
    candidates = [
        node
        for node in module.functions.values()
        if node.name.startswith("make_") and node.returns is not None and ast.unparse(node.returns) == config
    ]
    if not candidates:
        candidates = [node for node in module.functions.values() if node.name.startswith("make_") and _calls_name(node, config)]
    if len(candidates) != 1:
        _fail(f"{module.rel}: expected exactly one make_* returning {config}, found {[c.name for c in candidates]}")
    return candidates[0]


def _algorithm_rows(warnings: list[str]) -> tuple[list[AlgorithmRow], int]:
    """Parse the 61 algorithm rows out of ``evomo.algorithms``."""
    root = SRC / "algorithms"
    init = _load(root / "__init__.py")
    exports = init.all_names
    if exports is None:
        _fail("algorithms/__init__.py declares no __all__")
    configs = [name for name in exports if name.endswith("Config")]
    makers = [name for name in exports if name.startswith("make_")]

    modules: list[tuple[str, SourceModule]] = []
    for family_dir in sorted(path for path in root.iterdir() if path.is_dir()):
        if family_dir.name.startswith("_") or not (family_dir / "__init__.py").is_file():
            continue
        for path in sorted(family_dir.glob("*.py")):
            if path.name == "__init__.py" or path.name.startswith("_"):
                continue
            modules.append((family_dir.name, _load(path)))

    owners: dict[str, list[tuple[str, SourceModule]]] = {}
    for family, module in modules:
        for class_name in module.classes:
            owners.setdefault(class_name, []).append((family, module))

    rows: list[AlgorithmRow] = []
    paired: set[str] = set()
    for config in sorted(configs):
        hits = owners.get(config, [])
        if len(hits) != 1:
            _fail(
                f"{config}: expected exactly one defining module under algorithms/, found "
                f"{[module.rel for _, module in hits]}"
            )
        family, module = hits[0]
        if "TAKES_CV" not in module.constants:
            _fail(f"{module.rel}: {config} lives in a module without a module-level TAKES_CV")
        takes_cv = _module_constant(module, "TAKES_CV")
        if not isinstance(takes_cv, bool):
            _fail(f"{module.rel}: TAKES_CV is not a bool")
        maker_func = _config_maker(module, config)
        maker = maker_func.name
        if maker not in makers:
            _fail(f"{module.rel}: {maker} builds {config} but is missing from algorithms.__all__")
        if maker in paired:
            _fail(f"{module.rel}: {maker} is paired with more than one config")
        paired.add(maker)
        cls = module.classes[config]
        fields = _fields(module, cls)
        defaults = _algorithm_defaults(module, cls, maker_func)
        rows.append(
            AlgorithmRow(
                config=config,
                maker=maker,
                family=family,
                module=module.rel,
                takes_cv=takes_cv,
                fields=tuple(fields),
                fields_text=_fields_cell(fields, defaults),
            )
        )

    unpaired = sorted(set(makers) - paired)
    if unpaired:
        _fail(f"algorithms.__all__ lists make_* names no config pairs with: {unpaired}")
    return rows, len(exports)


def _problem_rows(package: str, families: tuple[str, ...], warnings: list[str]) -> list[ProblemRow]:
    """Parse the config rows of one problem package, family by family."""
    package_dir = SRC / "problems" / package
    init = _load(package_dir / "__init__.py")
    if init.all_names is None:
        _fail(f"problems/{package}/__init__.py declares no __all__")
    # ``__all__`` also lists the module aliases (``zdt``, ``ctp``, ...): a name is
    # an alias exactly when ``<package>/<name>.py`` exists.
    configs = [name for name in init.all_names if not (package_dir / f"{name}.py").exists()]

    rows: list[ProblemRow] = []
    seen: set[str] = set()
    for family in families:
        path = package_dir / f"{family}.py"
        if not path.is_file():
            _fail(f"problems/{package}: family module {path.name} is missing")
        module = _load(path)
        members = sorted((name for name in configs if name in module.classes), key=_natural_key)
        if not members:
            _fail(f"problems/{package}/{family}.py defines none of the exported configs")
        constrained = False
        if "CONSTRAINED" in module.constants:
            constrained = bool(_module_constant(module, "CONSTRAINED"))
        for name in members:
            cls = module.classes[name]
            fields = _fields(module, cls)
            defaults = _problem_defaults(module, cls, warnings)
            rows.append(
                ProblemRow(
                    name=name,
                    family=family,
                    package=package,
                    module=module.rel,
                    fields=tuple(fields),
                    fields_text=_fields_cell(fields, defaults),
                    constrained=constrained,
                    n_con=_n_con(cls, module, warnings),
                )
            )
            seen.add(name)

    uncovered = sorted(set(configs) - seen)
    if uncovered:
        _fail(f"problems/{package}: exported configs defined in no listed family module: {uncovered}")
    return rows


def _natural_key(name: str) -> tuple[str, int]:
    """Sort ``DTLZ2`` before ``DTLZ10`` (natural, not lexicographic, order)."""
    match = re.match(r"^(?P<stem>[^\d]*)(?P<num>\d*)$", name)
    if match is None:
        return (name, 0)
    return (match.group("stem"), int(match.group("num") or 0))


def _first_sentence(docstring: str | None) -> str:
    """First sentence of the first docstring paragraph, collapsed onto one line."""
    if not docstring:
        return MISSING
    paragraphs = [block for block in re.split(r"\n\s*\n", docstring.strip()) if block.strip()]
    if not paragraphs:
        return MISSING
    text = " ".join(paragraphs[0].split())
    match = re.search(r"(?<=[.!?])\s+(?=[A-Z(`*])", text)
    sentence = text[: match.start()] if match else text
    return sentence.strip()


def _kernel_rows(package: str, subpackages: tuple[str, ...], warnings: list[str]) -> list[tuple[str, list[KernelRow]]]:
    """Public kernels of each subpackage of ``evomo.<package>``, grouped per subpackage."""
    groups: list[tuple[str, list[KernelRow]]] = []
    for subpackage in subpackages:
        sub_dir = SRC / package / subpackage
        init = _load(sub_dir / "__init__.py")
        if init.all_names is None:
            _fail(f"{package}/{subpackage}/__init__.py declares no __all__")
        names = [name for name in init.all_names if not (sub_dir / f"{name}.py").exists()]
        definitions: dict[str, list[tuple[str, ast.AST, tuple[str, ...] | None]]] = {}
        for path in sorted(sub_dir.glob("*.py")):
            if path.name == "__init__.py" or path.name.startswith("_"):
                continue
            module = _load(path)
            for node in [*module.functions.values(), *module.classes.values()]:
                definitions.setdefault(node.name, []).append((module.rel, node, module.all_names))
        rows: list[KernelRow] = []
        for name in sorted(names):
            hits = definitions.get(name, [])
            if not hits:
                _fail(f"{package}/{subpackage}: {name} is exported but defined in no module of the subpackage")
            if len(hits) > 1:
                # Prefer the module that re-exports the name; otherwise take the
                # first module in sorted order and say so.
                hits = [hit for hit in hits if hit[2] is not None and name in hit[2]] or hits
                if len(hits) > 1:
                    warnings.append(
                        f"{package}/{subpackage}: {name} is defined in {[hit[0] for hit in hits]}; " f"reporting {hits[0][0]}"
                    )
            rel, node, _ = hits[0]
            contract = _first_sentence(ast.get_docstring(node))
            if contract == MISSING:
                warnings.append(f"{rel}: {name} has no docstring; contract left as {MISSING}")
            rows.append(KernelRow(name=name, module=rel, contract=contract))
        groups.append((subpackage, rows))
    return groups


def _util_groups(warnings: list[str]) -> list[tuple[str, list[KernelRow]]]:
    """``evomo.utils`` exports grouped by defining module."""
    init = _load(SRC / "utils" / "__init__.py")
    if init.all_names is None:
        _fail("utils/__init__.py declares no __all__")
    names = list(init.all_names)
    definitions: dict[str, tuple[str, ast.AST]] = {}
    for stem in UTIL_MODULES:
        module = _load(SRC / "utils" / f"{stem}.py")
        for node in [*module.functions.values(), *module.classes.values()]:
            if not node.name.startswith("_"):
                definitions.setdefault(node.name, (module.rel, node))
    groups: list[tuple[str, list[KernelRow]]] = []
    placed: set[str] = set()
    for stem in UTIL_MODULES:
        rows: list[KernelRow] = []
        for name in names:
            location = definitions.get(name)
            if location is None or not location[0].endswith(f"utils/{stem}.py"):
                continue
            rel, node = location
            contract = _first_sentence(ast.get_docstring(node))
            if contract == MISSING:
                warnings.append(f"{rel}: {name} has no docstring; contract left as {MISSING}")
            rows.append(KernelRow(name=name, module=rel, contract=contract))
            placed.add(name)
        rows.sort(key=lambda row: row.name)
        groups.append((stem, rows))
    missing = sorted(set(names) - placed)
    if missing:
        _fail(f"utils: exported names defined in no listed module: {missing}")
    return groups


# --- Page emitters ---------------------------------------------------------- #
def _paragraph(*sentences: str) -> str:
    """One prose paragraph as ``sentence\\nsentence``: a soft break keeps one sentence per line."""
    return "\n".join(sentences)


def _table(headers: tuple[str, ...], rows: list[tuple[str, ...]]) -> list[str]:
    """One GFM table; a ``|`` inside a cell is escaped for the table parser."""
    lines = ["| " + " | ".join(headers) + " |", "| " + " | ".join("---" for _ in headers) + " |"]
    lines.extend("| " + " | ".join(cell.replace("|", "\\|") for cell in row) + " |" for row in rows)
    return lines


def _page(header: str, title: str, paragraphs: list[str], body: list[str]) -> str:
    """Assemble a page: the two machine-readable comment lines, title, prose, tables."""
    lines = [GENERATED, f"<!-- {header} -->", "", f"# {title}", ""]
    for paragraph in paragraphs:
        lines.extend([paragraph, ""])
    return "\n".join(lines + body).rstrip("\n") + "\n"


def _algorithms_page(rows: list[AlgorithmRow], export_count: int) -> str:
    objective_only = sorted(row.config.removesuffix("Config") for row in rows if not row.takes_cv)
    paragraphs = [
        _paragraph(
            f"`evomo.algorithms` exports {len(rows)} multi-objective algorithms as {export_count} public names — one "
            "frozen `<Name>Config` dataclass and one `make_<name>` factory each — and that flat `__all__` list is the "
            "public contract.",
            "An algorithm is built with its `make_*` factory (`make_nsga2(pop_size=100, n_objs=3, lb=..., ub=...)`), "
            "which validates the arguments and returns the config the workflow resolves through "
            "`type(config).__module__`.",
            "The family directories of the `family` column (`nsga/`, `moead/`, `refvec/`, ...) are an internal routing "
            "device of the source tree, not part of the API.",
        ),
        _paragraph(
            f"The four mandatory fields are `pop_size`, `n_objs`, `lb` and `ub`; a `{MISSING}` marks such a required "
            "field, and every other field shows its default.",
            "A default is the dataclass body value with module constants resolved to their literal value, falling back "
            "to the `make_*` keyword default when the dataclass leaves the field unset — so `div=None` means the value "
            "is resolved inside `make_grea` from the objective count.",
        ),
        _paragraph(
            "`TAKES_CV` is the module-level seam that decides whether the workflow hands the algorithm a `(fitness, "
            f"cv)` pair: it is `True` for {len(rows) - len(objective_only)} of the {len(rows)} algorithms, and exactly "
            + ", ".join(f"`{name}`" for name in objective_only)
            + " declare `False`, so pairing one of those with a `CONSTRAINED` problem raises `ValueError` (see "
            "[the constraint protocol](../guide/constraints.md)).",
        ),
    ]
    body = _table(
        ("Config", "`make_*`", "Family", "Module", "`TAKES_CV`", "Fields (default)"),
        [(f"`{r.config}`", f"`{r.maker}`", f"`{r.family}/`", f"`{r.module}`", f"`{r.takes_cv}`", r.fields_text) for r in rows],
    )
    return _page(f"rows={len(rows)} algorithms, {export_count} exports", "Algorithms reference", paragraphs, body)


def _problem_table(rows: list[ProblemRow]) -> list[str]:
    return _table(
        ("Config", "Family", "Module", "`CONSTRAINED`", "`n_con`", "Fields (default)"),
        [
            (f"`{r.name}`", f"`{r.family}`", f"`{r.module}`", f"`{r.constrained}`", f"`{r.n_con_text}`", r.fields_text)
            for r in rows
        ],
    )


def _problems_page(numerical: list[ProblemRow], constrained: list[ProblemRow]) -> str:
    total = len(numerical) + len(constrained)
    paragraphs = [
        _paragraph(
            f"`evomo.problems` ships {total} benchmark problem configs — {len(numerical)} numerical and "
            f"{len(constrained)} constrained — as frozen config dataclasses in two family packages.",
            "Every config carries `d` (decision variables), `m` (objectives) and `ref_num` (the reference-vector count "
            "the decomposition algorithms sample), plus family extras such as `n_iq` (inequality constraints) or "
            "`difficulty`; a family `__post_init__` rejects an inconsistent combination.",
        ),
        _paragraph(
            "A problem's `evaluate(config, problem_state, pop)` returns `(fitness, problem_state)`, and a constrained "
            "family additionally declares `CONSTRAINED = True` and provides "
            "`evaluate_constrained(config, problem_state, pop) -> (fitness, cv, problem_state)`.",
            "`n_con` is the static width of that `cv` matrix (`(n, n_con)`, `cv == 0` meaning feasible); a "
            f"`{MISSING}` in the `n_con` column marks an unconstrained problem, which has no `n_con` property and never "
            "produces a `cv`.",
        ),
        _paragraph(
            "`pf(config)` builds a reference front as a traced tensor for in-graph use, while `pf_numpy(config)` "
            "evaluates it on the host and returns the float32 numpy array the metrics consume.",
            "The CTP family is the exception: its fronts are packaged data under `problems/constrained/pf/CTP/*.pf`, "
            "so its `pf` raises `NotImplementedError` and only `pf_numpy` (or "
            "`evomo.utils.load_pareto_front_from_file`) reads them.",
            "`evomo.problems.neuroevolution.MoRobtrol` completes the catalogue outside these two packages: it reaches "
            "Brax/JAX through an `external_call`, so it runs on the numpy backend only and a compiled backend rejects it.",
        ),
    ]
    body = [f"## Numerical problems ({len(numerical)})", ""]
    body += ["`CONSTRAINED` is not declared by these families, so the workflow takes the objective-only path.", ""]
    body += _problem_table(numerical)
    body += ["", f"## Constrained problems ({len(constrained)})", ""]
    body += ["Every family below declares `CONSTRAINED = True` and ships `evaluate_constrained`.", ""]
    body += _problem_table(constrained)
    return _page(f"rows={total} problems", "Problems reference", paragraphs, body)


def _kernel_table(rows: list[KernelRow], first_column: str) -> list[str]:
    return _table((first_column, "Module", "Contract"), [(f"`{r.name}`", f"`{r.module}`", r.contract) for r in rows])


def _operators_page(groups: list[tuple[str, list[KernelRow]]]) -> str:
    total = sum(len(rows) for _, rows in groups)
    counts = ", ".join(f"{len(rows)} `{name}`" for name, rows in groups)
    paragraphs = [
        _paragraph(
            f"`evomo.operators` holds the {total} evolutionary kernels that `evox` does not provide: constraint "
            "handling, truncation and archives, reference-vector utilities, sparse variation and EMO sampling.",
            "The genetic operators `evox.operators` already supplies are re-used, never copied, so a kernel here "
            f"always adds EMO-specific machinery (row counts: {counts}).",
        ),
        _paragraph(
            "Every kernel is a traced tensor function: call it inside `init`, `init_step`, `step` or `evaluate`, "
            "because `evoxc` has no eager mode and a tensor op outside an active trace raises `TraceError`.",
            "Each table below is one subpackage, its rows sorted by name, and the module column names the file the "
            "symbol is defined in — which is not always the file its name suggests.",
        ),
    ]
    body: list[str] = []
    for index, (subpackage, rows) in enumerate(groups):
        if index:
            body.append("")
        body += [f"## `{subpackage}` ({len(rows)})", ""] + _kernel_table(rows, "Kernel")
    return _page(f"rows={total} kernels", "Operators reference", paragraphs, body)


def _utils_page(groups: list[tuple[str, list[KernelRow]]]) -> str:
    total = sum(len(rows) for _, rows in groups)
    paragraphs = [
        _paragraph(
            f"`evomo.utils` exports {total} helpers in {len(groups)} modules — "
            + ", ".join(f"`{name}` ({len(rows)})" for name, rows in groups)
            + " — split by what they act on rather than by caller.",
            "The `require_*` validators, `normalize_bounds`, `to_float_tuple`, `validate_config` and "
            "`register_config_pytree` run in `make_*`, `pf` loads the packaged `.pf` data, and `state` replaces or "
            "inspects a workflow state tree.",
        ),
        _paragraph(
            "`bake_bounds` and `bake_float32_constant` build graph constants, and the `tensor_ops` helpers are "
            "lowering-safe tensor functions (`safe_divide`, `flip`, `cumsum_axis1`, `segment_reduce`, ...) that "
            "`evoxc` either lacks or that the compiled backends cannot export directly.",
            "Both groups are called inside `init`, `step` or `evaluate`, and outside a trace they raise `TraceError`; a "
            "helper `evox` already provides is not duplicated here.",
        ),
    ]
    body: list[str] = []
    for index, (stem, rows) in enumerate(groups):
        if index:
            body.append("")
        body += [f"## `{stem}` ({len(rows)})", ""] + _kernel_table(rows, "Helper")
    return _page(f"rows={total} helpers", "Utilities reference", paragraphs, body)


# --- Bundle --------------------------------------------------------------------
@dataclasses.dataclass
class Bundle:
    """Everything one run derives: the rows for verification and the page bodies."""

    algorithms: list[AlgorithmRow]
    numerical: list[ProblemRow]
    constrained: list[ProblemRow]
    operator_groups: list[tuple[str, list[KernelRow]]]
    util_groups: list[tuple[str, list[KernelRow]]]
    export_count: int
    pages: dict[str, str]
    warnings: list[str]


def build() -> Bundle:
    """Parse ``src/evomo/`` and render the four page bodies."""
    warnings: list[str] = []
    algorithms, export_count = _algorithm_rows(warnings)
    numerical = _problem_rows("numerical", NUMERICAL_FAMILIES, warnings)
    constrained = _problem_rows("constrained", CONSTRAINED_FAMILIES, warnings)
    operator_groups = _kernel_rows("operators", OPERATOR_SUBPACKAGES, warnings)
    util_groups = _util_groups(warnings)
    pages = {
        "algorithms.md": _algorithms_page(algorithms, export_count),
        "problems.md": _problems_page(numerical, constrained),
        "operators.md": _operators_page(operator_groups),
        "utils.md": _utils_page(util_groups),
    }
    return Bundle(
        algorithms=algorithms,
        numerical=numerical,
        constrained=constrained,
        operator_groups=operator_groups,
        util_groups=util_groups,
        export_count=export_count,
        pages=pages,
        warnings=warnings,
    )


def _write(pages: dict[str, str]) -> None:
    for name, text in pages.items():
        (OUT_DIR / name).write_text(text, encoding="utf-8", newline="\n")


def _report_warnings(warnings: list[str]) -> None:
    for warning in warnings:
        print(f"warning: {warning}", file=sys.stderr)


def _row_counts(bundle: Bundle) -> dict[str, int]:
    return {
        "algorithms.md": len(bundle.algorithms),
        "problems.md": len(bundle.numerical) + len(bundle.constrained),
        "operators.md": sum(len(rows) for _, rows in bundle.operator_groups),
        "utils.md": sum(len(rows) for _, rows in bundle.util_groups),
    }


# --- --check -------------------------------------------------------------------
def _stale(pages: dict[str, str]) -> list[str]:
    """Names of the pages whose committed file differs from a fresh render."""
    return [
        name
        for name, text in pages.items()
        if not (OUT_DIR / name).is_file() or (OUT_DIR / name).read_text(encoding="utf-8") != text
    ]


def _check(bundle: Bundle) -> int:
    stale = _stale(bundle.pages)
    for name in stale:
        print(f"stale: {name}")
    if stale:
        print(f"{len(stale)} of {len(bundle.pages)} pages are stale; re-run without --check to regenerate")
        return 1
    print(f"{len(bundle.pages)} pages are up to date")
    return 0


# --- --verify ------------------------------------------------------------------
_MISMATCHES: list[str] = []


def _expect(label: str, expected: object, got: object) -> None:
    if expected != got:
        _MISMATCHES.append(f"expected {label} {expected!r} got {got!r}")


def _committed_counts(path: Path) -> tuple[int, int]:
    """``(header_count, data_row_count)`` of a committed page."""
    text = path.read_text(encoding="utf-8")
    match = re.search(r"^<!-- rows=(\d+)", text, re.MULTILINE)
    header = int(match.group(1)) if match else -1
    table_lines = [line for line in text.splitlines() if line.startswith("|")]
    separators = sum(1 for line in table_lines if set(line) <= set("|-: "))
    return header, len(table_lines) - 2 * separators


def _verify_committed(bundle: Bundle) -> None:
    for name in _stale(bundle.pages):
        _MISMATCHES.append(f"expected {name} up to date got stale (re-run the generator)")
    for name, count in _row_counts(bundle).items():
        header, rows = _committed_counts(OUT_DIR / name)
        _expect(f"{name} header row count", count, header)
        _expect(f"{name} table row count", count, rows)


def _verify_live(bundle: Bundle) -> None:
    import dataclasses as dc
    import importlib

    import evomo.algorithms as algorithms
    import evomo.problems.constrained as constrained_pkg
    import evomo.problems.numerical as numerical_pkg
    import evomo.utils as utils

    # --- algorithms -------------------------------------------------------- #
    _expect("algorithms.__all__ length", 122, len(algorithms.__all__))
    _expect("algorithm config count", 61, sum(name.endswith("Config") for name in algorithms.__all__))
    _expect("algorithm maker count", 61, sum(name.startswith("make_") for name in algorithms.__all__))
    _expect("committed algorithm rows", 61, len(bundle.algorithms))
    for row in bundle.algorithms:
        config = getattr(algorithms, row.config, None)
        _expect(f"{row.config} exported", True, config is not None)
        if config is None:
            continue
        module_name = config.__module__
        expected_module = module_name.removeprefix("evomo.").replace(".", "/") + ".py"
        _expect(f"{row.config}.__module__", row.module, expected_module)
        _expect(f"{row.config} dataclass fields", row.field_names, tuple(f.name for f in dc.fields(config)))
        module = importlib.import_module(module_name)
        _expect(f"{module_name}.TAKES_CV", row.takes_cv, getattr(module, "TAKES_CV", "missing"))
        maker = getattr(algorithms, row.maker, None)
        _expect(f"{row.maker} exported", True, maker is not None)
        if maker is not None and "return" in getattr(maker, "__annotations__", {}):
            _expect(f"{row.maker} return annotation", row.config, _return_name(maker))

    # --- problems ---------------------------------------------------------- #
    numerical = bundle.numerical
    constrained = bundle.constrained
    for package, live_pkg, rows, expected in (
        ("numerical", numerical_pkg, numerical, 45),
        ("constrained", constrained_pkg, constrained, 86),
    ):
        package_dir = SRC / "problems" / package
        configs = [name for name in live_pkg.__all__ if not (package_dir / f"{name}.py").exists()]
        _expect(f"problems.{package} config count", expected, len(configs))
        _expect(f"committed {package} rows", expected, len(rows))
        for row in rows:
            module_name = f"evomo.problems.{package}.{row.family}"
            module = importlib.import_module(module_name)
            config_cls = getattr(module, row.name, None)
            _expect(f"{row.name} exported", True, config_cls is not None)
            if config_cls is None:
                continue
            _expect(f"{row.name} dataclass fields", row.field_names, tuple(f.name for f in dc.fields(config_cls)))
            _expect(f"{module_name}.CONSTRAINED", row.constrained, bool(getattr(module, "CONSTRAINED", False)))
            try:
                instance = config_cls()
            except Exception as exc:  # noqa: BLE001 - report it, never swallow it
                _MISMATCHES.append(f"expected {row.name}() constructible got {exc!r}")
                continue
            # An unconstrained config has no ``n_con`` property at all (page shows MISSING).
            _expect(f"{row.name}().n_con", row.n_con, getattr(instance, "n_con", None))
    _expect("committed problem rows", 131, len(numerical) + len(constrained))

    # --- operators --------------------------------------------------------- #
    for subpackage, rows in bundle.operator_groups:
        live = importlib.import_module(f"evomo.operators.{subpackage}")
        sub_dir = SRC / "operators" / subpackage
        names = [name for name in live.__all__ if not (sub_dir / f"{name}.py").exists()]
        _expect(f"operators.{subpackage} kernel count", len(names), len(rows))
        _expect(f"operators.{subpackage} names", tuple(sorted(names)), tuple(row.name for row in rows))
        for row in rows:
            _expect(f"{row.name} exported by operators.{subpackage}", True, hasattr(live, row.name))

    # --- utils ------------------------------------------------------------- #
    util_rows = [row for _, rows in bundle.util_groups for row in rows]
    _expect("evomo.utils.__all__ length", 32, len(utils.__all__))
    _expect("committed utils rows", len(utils.__all__), len(util_rows))
    _expect("committed utils names", tuple(sorted(utils.__all__)), tuple(sorted(row.name for row in util_rows)))
    for row in util_rows:
        _expect(f"{row.name} exported by evomo.utils", True, hasattr(utils, row.name))


def _return_name(func: object) -> str:
    """Return-annotation name of a live ``make_*`` factory."""
    annotation = getattr(func, "__annotations__", {}).get("return", "missing")
    return getattr(annotation, "__name__", str(annotation))


def _verify(bundle: Bundle) -> int:
    _report_warnings(bundle.warnings)
    _verify_committed(bundle)
    if _MISMATCHES:
        for line in _MISMATCHES:
            print(line)
        print(f"{len(_MISMATCHES)} mismatches; the committed pages do not match src/evomo/, re-run the generator")
        return 1
    print("committed pages are up to date")
    _verify_live(bundle)
    if _MISMATCHES:
        for line in _MISMATCHES:
            print(line)
        print(f"{len(_MISMATCHES)} mismatches between the committed pages and the live evomo API")
        return 1
    operator_counts = ", ".join(f"{len(rows)} {name}" for name, rows in bundle.operator_groups)
    util_total = sum(len(rows) for _, rows in bundle.util_groups)
    print(f"{len(bundle.algorithms)} algorithms ({bundle.export_count} exports)")
    print(
        f"{len(bundle.numerical)} numerical + {len(bundle.constrained)} constrained problems "
        f"({len(bundle.numerical) + len(bundle.constrained)})"
    )
    print(f"{sum(len(rows) for _, rows in bundle.operator_groups)} operator kernels ({operator_counts})")
    print(f"{util_total} utils exports ({len(bundle.util_groups)} modules)")
    print("verify: OK")
    return 0


# --- CLI -----------------------------------------------------------------------
def _parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="_generate_tables.py",
        description="Generate the four catalogue pages of docs/reference from src/evomo/ by static parsing.",
        epilog=(
            "modes:\n"
            "  (none)    regenerate algorithms.md, problems.md, operators.md and utils.md in place and print one\n"
            "            line per file with its row count\n"
            "  --check   re-render in memory and compare with the committed pages; exits 1 listing stale files and\n"
            "            imports nothing (safe on a docs-only machine)\n"
            "  --verify  assert the committed pages match src/evomo/ and then cross-check them against a live import\n"
            "            of evomo (needs env A: `source scripts/env.sh && $PYTHON_A docs/reference/_generate_tables.py\n"
            "            --verify` from the repository root); exits 1 with an `expected ... got ...` line per mismatch\n"
        ),
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    group = parser.add_mutually_exclusive_group()
    group.add_argument("--check", action="store_true", help="compare with the committed pages; no import")
    group.add_argument("--verify", action="store_true", help="cross-check against a live evomo import (env A)")
    return parser


def main(argv: list[str] | None = None) -> int:
    args = _parser().parse_args(argv)
    bundle = build()
    if args.check:
        return _check(bundle)
    if args.verify:
        return _verify(bundle)
    _report_warnings(bundle.warnings)
    _write(bundle.pages)
    for name, count in _row_counts(bundle).items():
        print(f"wrote {name}: {count} rows")
    return 0


if __name__ == "__main__":
    sys.exit(main())