"""Module management — list, info, install, update Odoo modules."""

from cli_anything.odoo_12.utils.odoo_backend import OdooBackend


def list_modules(rpc: OdooBackend, state: str | None = None,
                 search_term: str | None = None) -> dict:
    """List modules, optionally filtered by state or name."""
    modules = rpc.module_list(state=state)
    if search_term:
        term = search_term.lower()
        modules = [
            m for m in modules
            if term in (m.get("name", "") or "").lower()
            or term in (m.get("shortdesc", "") or "").lower()
            or term in (m.get("summary", "") or "").lower()
        ]
    return {
        "count": len(modules),
        "filter": {"state": state, "search": search_term},
        "modules": modules,
    }


def module_info(rpc: OdooBackend, name: str) -> dict:
    """Get detailed information about a module."""
    info = rpc.module_info(name)
    if not info:
        raise RuntimeError(f"Module '{name}' not found")
    return info


def install_module(rpc: OdooBackend, name: str) -> dict:
    """Install a module."""
    return rpc.module_install(name)


def update_module(rpc: OdooBackend, name: str) -> dict:
    """Update a module."""
    return rpc.module_update(name)
