"""Entry point for ``python -m ieum.server``."""

import argparse
import os

from ieum.server import run_server
from ieum.server.config import ServerConfig


def parse_args() -> argparse.Namespace:
    """Parse command line arguments for standalone server mode."""
    parser = argparse.ArgumentParser(description="IEUM API Server")
    parser.add_argument("--host", default="127.0.0.1", help="Server host (default: 127.0.0.1)")
    parser.add_argument("--port", type=int, default=8765, help="Server port (default: 8765)")
    parser.add_argument(
        "--cors-origins",
        default="",
        help="Comma-separated CORS origins (default: server config defaults)",
    )
    parser.add_argument(
        "--path",
        default=None,
        help="Working directory for file operations (default: current directory)",
    )
    return parser.parse_args()


def main() -> None:
    """Run the IEUM API server."""
    args = parse_args()

    if args.path:
        working_directory = os.path.abspath(args.path)
    else:
        working_directory = os.getcwd()

    os.makedirs(working_directory, exist_ok=True)

    config_kwargs = dict(
        host=args.host,
        port=args.port,
        working_directory=working_directory,
    )
    if args.cors_origins:
        cors_origins = [origin.strip() for origin in args.cors_origins.split(",") if origin.strip()]
        if "*" in cors_origins:
            msg = "Wildcard CORS origin '*' is not allowed."
            raise SystemExit(msg)
        config_kwargs["cors_origins"] = cors_origins

    config = ServerConfig(**config_kwargs)
    run_server(config)


if __name__ == "__main__":
    main()
