from __future__ import annotations

from pathlib import Path
import pprint

from fastgws.helpers import project_root


def render_service_module(service) -> str:
    payload = pprint.pformat(service.to_dict(), width=120, sort_dicts=False)
    return "\n".join(
        [
            '"""Generated service metadata."""',
            "",
            f"SERVICE = {payload}",
            "",
        ]
    )


def render_registry(services) -> str:
    payload = {
        service.alias: {
            "module": f"fastgws.generated.{service.alias}_meta",
            "title": service.title,
            "description": service.description,
        }
        for service in services
    }
    body = pprint.pformat(payload, width=120, sort_dicts=False)
    return f"REGISTRY = {body}\n"


def emit_generated(services, root: str | Path | None = None):
    base = project_root(root) / "fastgws" / "generated"
    base.mkdir(parents=True, exist_ok=True)
    for service in services:
        (base / f"{service.alias}_meta.py").write_text(render_service_module(service))
    (base / "registry.py").write_text(render_registry(services))
    (base / "__init__.py").write_text("from .registry import REGISTRY\n")
