"""Entry point for the Blueprint MCP Server.

Usage:
    blueprint-mcp [--transport stdio|streamable-http] [--host HOST] [--port PORT]

Environment variables:
    BLUEPRINT_API_URL   Base URL for the Blueprint API
    BLUEPRINT_API_KEY   API key for the Blueprint API (hidden from LLM)
    BLUEPRINT_HOST      Host for HTTP transport (default: 0.0.0.0)
    BLUEPRINT_PORT      Port for HTTP transport (default: 8000)
"""

import argparse
import sys

from .config import settings


def main() -> None:
    parser = argparse.ArgumentParser(
        prog="blueprint-mcp",
        description="Sitemule Blueprint MCP Server",
    )
    parser.add_argument(
        "--version",
        action="store_true",
        help="Print version, git hash, and build date then exit",
    )
    parser.add_argument(
        "--changelog",
        action="store_true",
        help="Print the changelog and exit",
    )
    parser.add_argument(
        "--transport",
        choices=["stdio", "streamable-http"],
        default="stdio",
        help="Transport to use (default: stdio)",
    )
    parser.add_argument(
        "--host",
        default=None,
        help=f"Host to bind HTTP server to (default: {settings.host})",
    )
    parser.add_argument(
        "--port",
        type=int,
        default=None,
        help=f"Port to bind HTTP server to (default: {settings.port})",
    )
    args = parser.parse_args()

    if args.version:
        from . import __version__
        from .banner import _read_build_info
        git_hash, build_date = _read_build_info()
        print(f"blueprint-mcp {__version__}  ({git_hash}  {build_date})")
        sys.exit(0)

    if args.changelog:
        try:
            from importlib.resources import files
            data = files("blueprint_mcp").joinpath("CHANGELOG.md")
            print(data.read_text(encoding="utf-8"))
        except Exception:
            # Fallback: look for CHANGELOG.md two levels above this file (repo root)
            from pathlib import Path
            candidate = Path(__file__).resolve().parent.parent.parent.parent / "CHANGELOG.md"
            if candidate.exists():
                print(candidate.read_text(encoding="utf-8"))
            else:
                print("Changelog not available in this installation.", file=sys.stderr)
                sys.exit(1)
        sys.exit(0)

    # Warn if API URL is not explicitly set
    import os

    if not os.environ.get("BLUEPRINT_API_URL"):
        print(
            "Warning: BLUEPRINT_API_URL environment variable is not set. "
            f"Using default: {settings.api_base_url}",
            file=sys.stderr,
        )

    from .banner import log_banner
    from .server import mcp
    from . import tools  # noqa: F401 — registers MCP tools via decorators

    log_banner()

    host = args.host or settings.host
    port = args.port or settings.port

    if args.transport == "stdio":
        mcp.run(transport="stdio", show_banner=False)
    else:
        mcp.run(transport="streamable-http", host=host, port=port, show_banner=False)


if __name__ == "__main__":
    main()
