from __future__ import annotations

import argparse
import os
import sys

from niannian.mcp.server.app import build_fastmcp
from niannian.mcp.service import create_service


def run_stdio(*, home: str | None = None, project: str | None = None, api_url: str | None = None) -> None:
    try:
        from mcp.server.fastmcp import FastMCP  # noqa: F401
    except ImportError as e:
        print("请安装 MCP 依赖: pip install 'niannian[mcp]'", file=sys.stderr)
        raise SystemExit(1) from e

    svc = create_service(home=home, project=project, api_url=api_url)
    mcp = build_fastmcp(svc)
    mcp.run(transport="stdio")


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(prog="niannian-mcp", description="念念 MCP Server（stdio / 远程 API）")
    parser.add_argument("--api", help="远程念念 API 基址，等同 NIANNIAN_API")
    parser.add_argument("--home", help="NIANNIAN_HOME 数据目录（本地模式）")
    parser.add_argument("--project", default=os.environ.get("NIANNIAN_PROJECT", "global"))
    parser.add_argument("--transport", default="stdio", choices=["stdio"])
    args = parser.parse_args(argv)

    run_stdio(home=args.home, project=args.project, api_url=args.api)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
