# retoor <retoor@molodetz.nl>

from .groups import ORDERED_GROUPS as API_GROUPS


_GROUPS_BY_SLUG = {group["slug"]: group for group in API_GROUPS}


def get_group(slug):
    return _GROUPS_BY_SLUG.get(slug)


def api_doc_pages():
    return [
        {
            "slug": group["slug"],
            "title": group["title"],
            "kind": "api",
            "admin": group.get("admin", False),
            "dynamic": group.get("dynamic", False),
        }
        for group in API_GROUPS
    ]


def _substitute(value, replacements):
    if isinstance(value, str):
        for token, replacement in replacements.items():
            value = value.replace(token, replacement)
        return value
    if isinstance(value, list):
        return [_substitute(item, replacements) for item in value]
    if isinstance(value, dict):
        return {key: _substitute(item, replacements) for key, item in value.items()}
    return value


def render_group(slug, base, username, api_key):
    group = get_group(slug)
    if not group:
        return None
    replacements = {
        "{{ base }}": base,
        "{{ username }}": username or "YOUR_USERNAME",
        "{{ api_key }}": api_key or "YOUR_API_KEY",
        "{{ app_reference }}": f"user-{username}-app-v-1-0-0" if username else "user-app-v-13.37.0",
    }
    return _substitute(group, replacements)
