from __future__ import annotations

from collections import defaultdict
from pathlib import Path

from fastgws.helpers import project_root, title_case


def emit_pyi(services, root: str | Path | None = None):
    lines = ["from typing import Any", "", "class FastGWS: ...", ""]
    for service in services:
        lines += _service_lines(service)
    (project_root(root) / "fastgws" / "generated" / "services.pyi").write_text("\n".join(lines).rstrip() + "\n")


def _service_lines(service):
    tree = defaultdict(set)
    methods = defaultdict(list)
    for method in service.methods:
        parts = method.dotted_path.split(".")[1:]
        for idx in range(len(parts) - 1):
            parent = ".".join(parts[:idx]) or service.alias
            tree[parent].add(parts[idx])
        methods[".".join(parts[:-1]) or service.alias].append(method)
    lines = [f"class {title_case(service.alias)}Service:", f"    ...", ""]
    for group, group_methods in sorted(methods.items()):
        if group == service.alias:
            continue
        class_name = title_case(service.alias) + title_case(group.replace(".", "_")) + "Group"
        lines += [f"class {class_name}:"]
        for method in sorted(group_methods, key=lambda o: o.py_name):
            lines.append(f"    def {method.py_name}(self, *args: Any, **kwargs: Any) -> Any: ...")
        lines += ["", ""]
    return lines
