import importlib
import re
from pathlib import Path

from google.ads.googleads import client

overload_lines = []
import_lines = []
for i, version in enumerate(sorted(client._VALID_API_VERSIONS)):

    for service_package_path in Path("google-ads-python/google/ads/googleads", version, "services/services").iterdir():
        if service_package_path.name == "__init__.py":
            continue
        import_path = f"google.ads.googleads.{version}.services.services.{service_package_path.name}"
        service_package = importlib.import_module(import_path)
        import_lines.append(f"import {import_path}")
        for service_name in service_package.__all__:
            service_name_without_suffix = service_name[: -len("Client")]
            overload_lines.append(
                f'    @overload\n    def get_service(self, name: Literal["{service_name_without_suffix}"], version: _{version.upper()}) -> {import_path}.{service_name}: ...'
            )
            if version == client._DEFAULT_VERSION:
                overload_lines.append(
                    f'    @overload\n    def get_service(self, name: Literal["{service_name_without_suffix}"]) -> {import_path}.{service_name}: ...'
                )

    if i < len(client._VALID_API_VERSIONS) - 1:
        overload_lines.append("\n")

overload_lines.append(
    f'    @overload\n    def get_service(self, name: str, version: _V = "{client._DEFAULT_VERSION}") -> Any: ...'
)

with open("google-stubs/ads/googleads/client.pyi") as f:
    client_pyi = f.read()
overload_lines.insert(0, "# Autogenerated service overloads")
overload_lines.append("    # End of autogenerated service overloads")
client_pyi = re.sub(
    "# Autogenerated service overloads.+# End of autogenerated service overloads",
    "\n".join(overload_lines),
    client_pyi,
    flags=re.DOTALL,
)
import_lines.insert(0, "# Autogenerated service imports")
import_lines.append("# End of autogenerated service imports")
client_pyi = re.sub(
    "# Autogenerated service imports.+# End of autogenerated service imports",
    "\n".join(import_lines),
    client_pyi,
    flags=re.DOTALL,
)
with open("google-stubs/ads/googleads/client.pyi", mode="w") as f:
    f.write(client_pyi)
