import argparse
import logging
import os
import sys

sys.path.insert(0, os.path.dirname(__file__))

from service.grpc_server import serve

DEFAULT_PORT = 50051
DEFAULT_MAX_WORKERS = 10

def main():
    parser = argparse.ArgumentParser(
        description="Document Parser gRPC Server (MarkItDown)",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )
    parser.add_argument(
        "--port",
        type=int,
        default=DEFAULT_PORT,
        help="Port to listen on",
    )
    parser.add_argument(
        "--max-workers",
        type=int,
        default=DEFAULT_MAX_WORKERS,
        help="Maximum number of worker threads",
    )
    parser.add_argument(
        "--log-level",
        type=str,
        default="INFO",
        choices=["DEBUG", "INFO", "WARNING", "ERROR"],
        help="Log level",
    )
    
    args = parser.parse_args()

    logging.basicConfig(
        level=getattr(logging, args.log_level),
        format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    )
    
    logger = logging.getLogger(__name__)
    logger.info("Starting Document Parser gRPC Server (MarkItDown)")
    logger.info("Port: %d", args.port)
    logger.info("Max workers: %d", args.max_workers)
    
    try:
        serve(port=args.port, max_workers=args.max_workers)
    except KeyboardInterrupt:
        logger.info("Server shutdown requested")
    except Exception as e:
        logger.error("Server error: %s", str(e), exc_info=True)
        sys.exit(1)

if __name__ == "__main__":
    main()
