import urllib.parse
from typing import List, Optional

DEFAULT_PORT = 9000


def parse(database_url: str) -> dict:
    parsed = urllib.parse.urlparse(database_url)

    if parsed.scheme not in ("clickhouse",):
        raise ValueError(f"Invalid DSN: {parsed.scheme}")

    _, _hosts_part = parsed.netloc.split("@")

    hosts = _parse_hosts_spec(_hosts_part)

    database = parsed.path[1:]

    query = dict(urllib.parse.parse_qsl(parsed.query))

    secure = _parse_bool(query.pop("secure", "false"))
    ca_certs = query.get("ca_certs", None)

    return {
        "user": parsed.username,
        "password": parsed.password,
        "hosts": hosts,
        "database": database,
        "secure": secure,
        "ca_certs": ca_certs,
    }


def _parse_bool(value: Optional[str]) -> bool:
    if not str:
        return False
    return bool(value.strip().lower() in ("true", "1", "t", "yes", "y"))


def _parse_hosts_spec(hosts_dsn_part: str) -> List[dict]:
    result = []

    for host_spec in hosts_dsn_part.split(","):
        parsed = urllib.parse.urlparse(f"//{host_spec}")
        _host, _port = parsed.hostname, parsed.port
        result.append({"host": _host, "port": int(_port or DEFAULT_PORT)})

    return result
