from __future__ import annotations

import argparse
from collections.abc import Sequence

from .config import RabbitMQConfig


def _parse_bool(value: str) -> bool:
    normalized = value.strip().lower()
    if normalized in {"1", "true", "yes", "y", "on"}:
        return True
    if normalized in {"0", "false", "no", "n", "off"}:
        return False
    raise argparse.ArgumentTypeError("Boolean value expected")


def parse_cli(args: Sequence[str] | None = None) -> RabbitMQConfig:
    parser = argparse.ArgumentParser(description="RabbitMQ MCP server")
    parser.add_argument("--host", required=True)
    parser.add_argument("--port", type=int, required=True)
    parser.add_argument("--user", required=True)
    parser.add_argument("--password", required=True)
    parser.add_argument("--allow-destructive", type=_parse_bool, required=True)
    parser.add_argument("--amqp-port", type=int, default=5672)
    parser.add_argument("--vhost", default="/")
    parser.add_argument("--scheme", choices=["http", "https"], default="http")
    parser.add_argument("--verify-ssl", type=_parse_bool, default=None)
    parser.add_argument("--timeout", type=float, default=10.0)
    parser.add_argument("--max-connections", type=int, default=20)
    parser.add_argument("--max-keepalive", type=int, default=10)
    parser.add_argument("--retries", type=int, default=1)
    parser.add_argument("--retry-backoff", type=float, default=0.2)
    parser.add_argument("--vhost-cache-ttl", type=float, default=60.0)

    parsed = parser.parse_args(args)
    verify_ssl = (
        parsed.verify_ssl
        if parsed.verify_ssl is not None
        else parsed.scheme == "https"
    )

    return RabbitMQConfig(
        env="cli",
        host=parsed.host,
        port=parsed.port,
        amqp_port=parsed.amqp_port,
        username=parsed.user,
        password=parsed.password,
        vhost=parsed.vhost,
        scheme=parsed.scheme,
        verify_ssl=verify_ssl,
        timeout=parsed.timeout,
        max_connections=parsed.max_connections,
        max_keepalive_connections=parsed.max_keepalive,
        retries=parsed.retries,
        retry_backoff=parsed.retry_backoff,
        vhost_cache_ttl=parsed.vhost_cache_ttl,
        allow_destructive=parsed.allow_destructive,
    )
