import subprocess
import sys
import os

proto_file = "proto/document_parser.proto"
proto_path = "proto"
python_out = "proto"
grpc_python_out = "proto"

def generate_grpc():
    """Generate gRPC Python code from proto file"""
    print(f"Generating gRPC code from {proto_file}...")
    
    cmd = [
        sys.executable,
        "-m",
        "grpc_tools.protoc",
        f"--proto_path={proto_path}",
        f"--python_out={python_out}",
        f"--grpc_python_out={grpc_python_out}",
        proto_file,
    ]
    
    try:
        subprocess.run(cmd, check=True)
        print("gRPC code generated successfully!")
        
        pb2_file = os.path.join(python_out, "document_parser_pb2.py")
        pb2_grpc_file = os.path.join(python_out, "document_parser_pb2_grpc.py")
        
        if os.path.exists(pb2_file) and os.path.exists(pb2_grpc_file):
            print(f"Generated files:")
            print(f"  - {pb2_file}")
            print(f"  - {pb2_grpc_file}")
        else:
            print("Warning: Expected files not found")
            
    except subprocess.CalledProcessError as e:
        print(f"Error generating gRPC code: {e}")
        sys.exit(1)
    except Exception as e:
        print(f"Unexpected error: {e}")
        sys.exit(1)

if __name__ == "__main__":
    generate_grpc()
