# retoor <retoor@molodetz.nl>

from __future__ import annotations

from devplacepy.services.statistics.common import (
    VALID_TABS,
    cache_get,
    cache_set,
    iso,
    now_utc,
    window_config,
)
from devplacepy.services.statistics.tabs_data import (
    build_ai,
    build_awards,
    build_containers,
    build_content,
    build_devii,
    build_engagement,
    build_game,
    build_members,
    build_moderation,
    build_overview,
    build_services,
    build_social,
    build_storage,
    build_tools,
    build_visitors,
)

TAB_BUILDERS = {
    "overview": build_overview,
    "visitors": build_visitors,
    "members": build_members,
    "content": build_content,
    "engagement": build_engagement,
    "social": build_social,
    "ai": build_ai,
    "devii": build_devii,
    "services": build_services,
    "containers": build_containers,
    "game": build_game,
    "awards": build_awards,
    "moderation": build_moderation,
    "tools": build_tools,
    "storage": build_storage,
}


def build_statistics_tab(
    tab: str,
    hours: int = 168,
    *,
    compare: bool = True,
    top_n: int = 10,
) -> dict:
    key = (tab or "overview").strip().lower()
    if key not in VALID_TABS:
        key = "overview"
    bounded_top = max(1, min(int(top_n or 10), 50))
    window = window_config(hours)
    cache_key = f"stats:{key}:{window['hours']}:{int(compare)}:{bounded_top}"
    cached = cache_get(cache_key)
    if cached is not None:
        return cached
    builder = TAB_BUILDERS[key]
    body = builder(window["hours"], compare, bounded_top)
    payload = {
        "tab": key,
        "window_hours": window["hours"],
        "granularity": window["granularity"],
        "generated_at": iso(now_utc()),
        "compare": bool(compare),
        **body,
    }
    cache_set(cache_key, payload)
    return payload