"""CLI entry point for active-claude-github-mcp."""
from __future__ import annotations

import argparse
import asyncio
import sys
from pathlib import Path

import mcp.server.stdio
from mcp.server import NotificationOptions
from mcp.server.models import InitializationOptions

from .. import __version__
from ..config import ConfigError
from .build import build_server


def main() -> None:
    """
    Entry point for active-claude-github-mcp.

    Parses --project-dir, loads config, starts MCP server on stdio.
    Fails immediately (exit code 1) if config is invalid.
    """
    parser = argparse.ArgumentParser(
        prog="active-claude-github-mcp",
        description="MCP server for the active-claude-github skill",
    )
    parser.add_argument(
        "--project-dir",
        type=Path,
        default=Path("."),
        help="Path to the *-dev repo root containing .claude/github-config.json",
    )
    parser.add_argument(
        "--version",
        action="version",
        version=f"%(prog)s {__version__}",
    )
    args = parser.parse_args()

    try:
        server, config, _, _ = build_server(args.project_dir.resolve())
    except ConfigError as exc:
        print(f"[active-claude-github-mcp] FATAL: {exc}", file=sys.stderr)
        sys.exit(1)

    print(
        f"[active-claude-github-mcp] v{__version__} started. "
        f"Project: {config.repos.private}",
        file=sys.stderr,
    )

    async def _serve() -> None:
        async with mcp.server.stdio.stdio_server() as (read_stream, write_stream):
            await server.run(
                read_stream,
                write_stream,
                InitializationOptions(
                    server_name="active-claude-github",
                    server_version=__version__,
                    capabilities=server.get_capabilities(
                        notification_options=NotificationOptions(),
                        experimental_capabilities={},
                    ),
                ),
            )

    asyncio.run(_serve())


if __name__ == "__main__":
    main()
