#!/usr/bin/env python3
"""Generate gRPC Python stubs from kyrodb.proto."""

from __future__ import annotations

import argparse
from pathlib import Path

from grpc_tools import protoc


def _parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--proto",
        type=Path,
        default=Path("proto/kyrodb.proto"),
        help="Path to kyrodb.proto",
    )
    parser.add_argument(
        "--out",
        type=Path,
        default=Path("src/kyrodb/_generated"),
        help="Output directory for generated Python modules",
    )
    return parser.parse_args()


def _patch_relative_import(grpc_file: Path) -> None:
    content = grpc_file.read_text(encoding="utf-8")
    content = content.replace(
        "import kyrodb_pb2 as kyrodb__pb2",
        "from . import kyrodb_pb2 as kyrodb__pb2",
    )
    grpc_file.write_text(content, encoding="utf-8")


def main() -> int:
    args = _parse_args()
    proto_path = args.proto.resolve()
    out_dir = args.out.resolve()

    if not proto_path.exists():
        raise SystemExit(f"proto file not found: {proto_path}")

    out_dir.mkdir(parents=True, exist_ok=True)
    init_path = out_dir / "__init__.py"
    if not init_path.exists():
        init_path.write_text("", encoding="utf-8")

    status = protoc.main(
        [
            "grpc_tools.protoc",
            f"-I{proto_path.parent}",
            f"--python_out={out_dir}",
            f"--grpc_python_out={out_dir}",
            str(proto_path),
        ]
    )
    if status != 0:
        return status

    _patch_relative_import(out_dir / "kyrodb_pb2_grpc.py")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
