"""TrailBase MCP Server CLI 入口点"""

import argparse
import asyncio
import sys

from trailbase_mcp.server import TrailBaseMCPServer


async def _main_async():
    """异步主函数"""
    parser = argparse.ArgumentParser(description="TrailBase MCP Server")
    parser.add_argument(
        "--transport",
        choices=["stdio", "http", "streamable_http"],
        default="stdio",
        help="传输方式：stdio（默认，自动启动）或 http/streamable_http（需要单独启动服务器）",
    )
    parser.add_argument(
        "--host",
        default="0.0.0.0",
        help="HTTP 服务器主机地址（仅用于 http/streamable_http 传输）",
    )
    parser.add_argument(
        "--port",
        type=int,
        default=9118,
        help="HTTP 服务器端口（仅用于 http/streamable_http 传输）",
    )
    parser.add_argument(
        "--trailbase-url",
        default=None,
        help="TrailBase 服务器地址（默认从 TRAILBASE_URL 环境变量读取）",
    )
    parser.add_argument(
        "--trailbase-token",
        default=None,
        help="TrailBase 认证令牌（默认从 ADMIN_TOKEN 环境变量读取）",
    )

    args = parser.parse_args()

    server = TrailBaseMCPServer(
        trailbase_url=args.trailbase_url,
        trailbase_token=args.trailbase_token,
    )

    try:
        # 默认使用 Streamable HTTP（最新标准）
        transport = args.transport or "http"
        if transport == "http" or transport == "streamable_http":
            await server.run_streamable_http(args.host, args.port)
        else:
            await server.run_stdio()
    except KeyboardInterrupt:
        print("\nShutting down...", file=sys.stderr)
        sys.stderr.flush()
    except Exception as e:
        print(f"Error: {e}", file=sys.stderr)
        sys.stderr.flush()
        raise


def main():
    """同步入口点函数（供 uvx 使用）"""
    asyncio.run(_main_async())


if __name__ == "__main__":
    main()

