from __future__ import annotations

from pathlib import Path

from fastgws.helpers import project_root


def emit_docs(services, root: str | Path | None = None):
    docs = project_root(root) / "docs" / "api"
    docs.mkdir(parents=True, exist_ok=True)
    index = ["# API Reference", ""]
    for service in services:
        index.append(f"- [{service.title}]({service.alias}.md)")
        lines = [f"# {service.title}", "", service.description, ""]
        if service.documentation_link:
            lines += [f"Docs: {service.documentation_link}", ""]
        lines += ["## Methods", ""]
        for method in service.methods:
            sig = _signature(method)
            lines += [f"### `{method.dotted_path}`", "", f"`{sig}`", ""]
            if method.description:
                lines += [method.description, ""]
        (docs / f"{service.alias}.md").write_text("\n".join(lines).rstrip() + "\n")
    (docs / "index.md").write_text("\n".join(index).rstrip() + "\n")


def _signature(method):
    params = [p.py_name for p in method.path_params]
    params += [f"{p.py_name}=None" for p in method.query_params]
    if method.request_schema_ref:
        params.append("body=None")
    if method.supports_media_upload:
        params += ["upload=None", "upload_content_type=None"]
    if method.supports_media_download:
        params.append("download=None")
    return f"{method.dotted_path}({', '.join(params)})"
