"""Entry point for the Cielara Agent Memory MCP server.

Usage:
    python -m memory_mcp                                    # STDIO (Claude Desktop / Claude Code)
    python -m memory_mcp --transport http                    # HTTP on 0.0.0.0:8888 (no auth)
    python -m memory_mcp --transport http --port 9000

    # HTTPS with Bearer-token auth (Claude.ai custom connector):
    MCP_SECRET_TOKEN=<token> python -m memory_mcp --transport http \
        --ssl-certfile /path/to/cert.pem --ssl-keyfile /path/to/key.pem

    # HTTP behind a TLS-terminating reverse proxy (e.g. nginx):
    MCP_SECRET_TOKEN=<token> python -m memory_mcp --transport http

Upstream URLs:
    MEMORY_API_URL       (required) — e.g. http://agent-memory:8001
    CIELARA_BACKEND_URL  (optional) — only used to ship tool-call audit events

Auth:
    MCP_SECRET_TOKEN  — when set, every HTTP request must include
                        "Authorization: Bearer <token>".  Unset = no auth
                        (local dev only).  Required for Claude.ai connector.
"""

import argparse
import logging
import os
import warnings

logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
logger = logging.getLogger("cielara-memory-mcp")


def main() -> None:
    parser = argparse.ArgumentParser(description="Cielara Agent Memory MCP Server")
    parser.add_argument(
        "--transport",
        choices=["stdio", "http"],
        default="stdio",
        help="Transport protocol (default: stdio)",
    )
    parser.add_argument("--host", default="0.0.0.0", help="HTTP bind host (default: 0.0.0.0)")
    parser.add_argument("--port", type=int, default=8888, help="HTTP bind port (default: 8888)")
    parser.add_argument(
        "--ssl-certfile",
        default=None,
        help="Path to TLS certificate file (PEM). When set, server speaks HTTPS directly.",
    )
    parser.add_argument(
        "--ssl-keyfile",
        default=None,
        help="Path to TLS private key file (PEM).",
    )
    args = parser.parse_args()

    if args.transport == "stdio":
        from memory_mcp.server import create_server
        mcp = create_server()
        mcp.run(transport="stdio")
        return

    import uvicorn

    from memory_mcp.server import create_asgi_app

    token = os.environ.get("MCP_SECRET_TOKEN") or None
    if not token:
        warnings.warn(
            "MCP_SECRET_TOKEN is not set. The MCP server is running WITHOUT authentication. "
            "Set MCP_SECRET_TOKEN before exposing this server publicly.",
            stacklevel=1,
        )
    else:
        logger.info("Bearer-token auth enabled (MCP_SECRET_TOKEN is set).")

    if args.ssl_certfile:
        logger.info("TLS enabled — serving HTTPS directly on %s:%d", args.host, args.port)
    else:
        logger.info(
            "Serving HTTP on %s:%d — ensure a TLS-terminating proxy (e.g. nginx) fronts this.",
            args.host, args.port,
        )

    app = create_asgi_app(token=token, host=args.host, port=args.port)

    uvicorn.run(
        app,
        host=args.host,
        port=args.port,
        ssl_certfile=args.ssl_certfile,
        ssl_keyfile=args.ssl_keyfile,
        log_level="info",
    )


if __name__ == "__main__":
    main()
