"""
cornerdatastore-mcp CLI

Thin wrapper around mcp-proxy that connects to the CornerdataStore MCP server
using the CDS_API_KEY environment variable.

Usage:
    uvx cornerdatastore-mcp

Required environment:
    CDS_API_KEY  — your CornerdataStore API key (get one at cornerdatastore.com)
"""

import os
import pathlib
import shutil
import sys

SERVER_URL = "https://mcp.cornerdatastore.com/mcp"


def main() -> None:
    api_key = os.environ.get("CDS_API_KEY", "").strip()
    if not api_key:
        print(
            "Error: CDS_API_KEY environment variable is not set.\n"
            "Get your API key at https://cornerdatastore.com\n\n"
            "Then configure your MCP client:\n"
            '  { "command": "uvx", "args": ["cornerdatastore-mcp"],\n'
            '    "env": { "CDS_API_KEY": "cds_sk_..." } }',
            file=sys.stderr,
        )
        sys.exit(1)

    # Prefer mcp-proxy installed alongside this package (same venv/uvx environment)
    mcp_proxy = pathlib.Path(sys.executable).parent / "mcp-proxy"
    if not mcp_proxy.exists():
        # Fall back to PATH
        found = shutil.which("mcp-proxy")
        if not found:
            print(
                "Error: mcp-proxy not found. Try reinstalling:\n"
                "  uvx cornerdatastore-mcp",
                file=sys.stderr,
            )
            sys.exit(1)
        mcp_proxy = pathlib.Path(found)

    os.execv(
        str(mcp_proxy),
        [
            "mcp-proxy",
            "--transport", "streamablehttp",
            "-H", "X-Api-Key", api_key,
            SERVER_URL,
        ],
    )
