#!/usr/bin/env python3
"""Patch grpc-stubs to satisfy strict basedpyright checks.

Keeps the changes local to the project's venv for reproducibility during
Makefile-driven quality checks. This is a no-op if grpc-stubs is not present.
"""

from __future__ import annotations

from pathlib import Path
import re


def _patch_grpc_stubs(root: Path) -> bool:
    grpc_path = root / "__init__.pyi"
    aio_path = root / "aio" / "__init__.pyi"
    if not grpc_path.exists() or not aio_path.exists():
        return False

    grpc_text = grpc_path.read_text()
    grpc_text = re.sub(
        r"^Options: TypeAlias = _Options\\r?\\n",
        "",
        grpc_text,
        flags=re.MULTILINE,
    )
    grpc_text = grpc_text.replace(
        "_Options: TypeAlias = Sequence[_OptionKeyValue]",
        "_Options: TypeAlias = Sequence[_OptionKeyValue]\nOptions: TypeAlias = _Options",
    )
    grpc_text = re.sub(
        r"def traceback\(([^)]*)\):",
        r"def traceback(\1) -> TracebackType | None:",
        grpc_text,
    )
    grpc_text = re.sub(
        r"def __init__\(self, credentials\) -> None:",
        "def __init__(self, credentials: object) -> None:",
        grpc_text,
    )
    grpc_text = re.sub(
        r"def __init__\(self, certificate_configuration\) -> None:",
        "def __init__(self, certificate_configuration: object) -> None:",
        grpc_text,
    )
    grpc_path.write_text(grpc_text)

    aio_text = aio_path.read_text()
    aio_text = aio_text.replace("    _Options,\n", "    Options,\n")
    aio_text = re.sub(r"\b_Options\b", "Options", aio_text)
    aio_path.write_text(aio_text)
    return True


def main() -> None:
    repo_root = Path(__file__).resolve().parents[1]
    venv_root = repo_root / ".venv" / "lib" / "python3.12" / "site-packages" / "grpc-stubs"
    if not _patch_grpc_stubs(venv_root):
        return


if __name__ == "__main__":
    main()
