from __future__ import annotations

import logging
import os
import pathlib
import sys

from .client import DEFAULT_BASE_URL, DropmailClient
from .server import create_server

logger = logging.getLogger("dropmail_mcp")

DEFAULT_LOG_FILE = pathlib.Path.home() / ".local" / "share" / "dropmail-mcp" / "dropmail-mcp.log"


def _setup_logging(level: str, log_file: str | None) -> None:
    if level == "NONE":
        logging.disable(logging.CRITICAL)
        return
    numeric = getattr(logging, level.upper(), logging.WARNING)
    if log_file:
        dest = pathlib.Path(log_file)
        dest.parent.mkdir(parents=True, exist_ok=True)
        handler: logging.Handler = logging.FileHandler(dest)
    else:
        handler = logging.StreamHandler(sys.stderr)
    handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(name)s: %(message)s"))
    root = logging.getLogger("dropmail_mcp")
    root.setLevel(numeric)
    root.addHandler(handler)
    if numeric == logging.DEBUG:
        mcp_logger = logging.getLogger("mcp")
        mcp_logger.setLevel(logging.DEBUG)
        mcp_logger.addHandler(handler)


def main() -> None:
    import argparse

    parser = argparse.ArgumentParser(
        description="DropMail MCP server — exposes temporary email via MCP tools.",
    )
    parser.add_argument(
        "--token",
        default=os.environ.get("DROPMAIL_TOKEN"),
        help="DropMail API token. Obtain one at https://dropmail.me/api/ (or set DROPMAIL_TOKEN env var).",
    )
    parser.add_argument(
        "--base-url",
        default=os.environ.get("DROPMAIL_BASE_URL", DEFAULT_BASE_URL),
        help=f"GraphQL endpoint base URL (default: {DEFAULT_BASE_URL}).",
    )
    parser.add_argument(
        "--log-level",
        default=os.environ.get("DROPMAIL_LOG_LEVEL", "WARNING"),
        choices=["DEBUG", "INFO", "WARNING", "ERROR", "NONE"],
        help="Log verbosity (default: WARNING). Use NONE to suppress all logs.",
    )
    parser.add_argument(
        "--log-file",
        default=os.environ.get("DROPMAIL_LOG_FILE"),
        metavar="PATH",
        help=(
            f"Write logs to a file instead of stderr. "
            f"Suggested: {DEFAULT_LOG_FILE}"
        ),
    )
    args = parser.parse_args()

    _setup_logging(args.log_level, args.log_file)

    if not args.token:
        print(
            "Error: a DropMail token is required.\n"
            "Obtain one at https://dropmail.me/api/ and set it via\n"
            "--token or the DROPMAIL_TOKEN environment variable.",
            file=sys.stderr,
        )
        sys.exit(1)

    logger.info("Starting dropmail-mcp (base_url=%s)", args.base_url)
    client = DropmailClient(token=args.token, base_url=args.base_url)
    server = create_server(client)
    server.run()


if __name__ == "__main__":
    main()
