"""
Main entry point for the MCP-RLM Proxy Server.
"""

import asyncio
import argparse
import json
import os
import sys
from pathlib import Path
from typing import Optional

from mcp_proxy.logging_config import setup_logging


_CONFIG_EXAMPLE = {
    "mcpServers": {
        "filesystem": {
            "command": "npx",
            "args": ["-y", "@modelcontextprotocol/server-filesystem", "/your/path"],
        }
    },
    "proxySettings": {
        "maxResponseSize": 8000,
        "cacheMaxEntries": 50,
        "cacheTTLSeconds": 300,
        "enableAutoTruncation": True,
        "enableAgentIsolation": True,
        "maxEntriesPerAgent": 20,
        "maxMemoryPerAgent": 104857600,
        "maxTotalAgents": 1000,
    },
}


def _build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="mcp-rlm-proxy",
        description="MCP-RLM-Proxy: Intelligent middleware for MCP servers.",
    )
    parser.add_argument(
        "--config",
        dest="config_path",
        default=None,
        help=(
            "Path to MCP client-style config JSON (mcp.json). "
            "If omitted, uses MCP_PROXY_CONFIG if set, otherwise ./mcp.json."
        ),
    )
    parser.add_argument(
        "--init-config",
        dest="init_config_path",
        nargs="?",
        const="mcp.json",
        default=None,
        help=(
            "Write an example mcp.json to the given path and exit "
            "(default: ./mcp.json)."
        ),
    )
    parser.add_argument(
        "--print-config-example",
        action="store_true",
        help="Print an example mcp.json to stdout and exit.",
    )
    return parser


def _resolve_config_path(cli_value: Optional[str]) -> str:
    if cli_value:
        return cli_value
    env_value = os.getenv("MCP_PROXY_CONFIG")
    if env_value:
        return env_value
    return "mcp.json"


def _write_example_config(path_str: str) -> None:
    path = Path(path_str)
    path.parent.mkdir(parents=True, exist_ok=True)
    if path.exists():
        raise FileExistsError(f"Refusing to overwrite existing file: {path}")
    path.write_text(json.dumps(_CONFIG_EXAMPLE, indent=2) + "\n", encoding="utf-8")


def main() -> None:
    """Main entry point."""
    parser = _build_parser()
    args = parser.parse_args()

    if args.print_config_example:
        print(json.dumps(_CONFIG_EXAMPLE, indent=2))
        return

    if args.init_config_path is not None:
        try:
            _write_example_config(args.init_config_path)
            print(f"Wrote example config to {args.init_config_path}")
            return
        except FileExistsError as e:
            print(str(e), file=sys.stderr)
            sys.exit(2)

    log_level = os.getenv("MCP_PROXY_LOG_LEVEL", "INFO")
    setup_logging(level=log_level)
    config_path = _resolve_config_path(args.config_path)
    asyncio.run(async_main(config_path))


async def async_main(config_path: str) -> None:
    """Async main entry point."""
    from mcp_proxy.config import load_config
    from mcp_proxy.server import MCPProxyServer

    underlying_servers, proxy_settings = load_config(config_path)
    proxy = MCPProxyServer(underlying_servers, proxy_settings=proxy_settings)
    await proxy.run()


if __name__ == "__main__":
    main()
