"""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)

    if config is None:
        # Pre-bootstrap mode (#156). Server runs with a reduced tool
        # surface — scaffold_project and check_skill_version only —
        # so the operator can bootstrap without restarting first.
        print(
            f"[active-claude-github-mcp] v{__version__} started in "
            f"PRE-BOOTSTRAP mode: .claude/github-config.json not found "
            f"under {args.project_dir.resolve()}. Run `scaffold_project` "
            "or follow §Self-Bootstrap. Restart Claude Code after "
            "bootstrap to load the full tool surface.",
            file=sys.stderr,
        )
    else:
        print(
            f"[active-claude-github-mcp] v{__version__} started. "
            f"Project: {config.repos.private}",
            file=sys.stderr,
        )

    async def _serve() -> None:
        try:
            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={},
                        ),
                    ),
                )
        finally:
            # Release the shared httpx.AsyncClient connection pool on
            # graceful shutdown (#176).
            from ..github.core import aclose_client
            await aclose_client()

    asyncio.run(_serve())


if __name__ == "__main__":
    main()
