import logging
from typing import Any, Optional

import clickhouse_connect


logger = logging.getLogger(__name__)


class ClickHouseClient:
    def __init__(
        self,
        host: str,
        port: int = 8123,
        username: str = "default",
        password: str = "",
        database: str = "default",
        secure: bool = False,
    ):
        try:
            self.client = clickhouse_connect.get_client(
                host=host,
                port=port,
                username=username,
                password=password,
                database=database,
                secure=secure,
            )
        except Exception:
            logger.exception("Failed to initialize ClickHouse client")
            raise

    def query(self, sql: str, parameters: Optional[dict[str, Any]] = None):
        try:
            return self.client.query(sql, parameters=parameters)
        except Exception:
            logger.exception("ClickHouse query failed")
            raise

    def command(self, sql: str, parameters: Optional[dict[str, Any]] = None):
        try:
            return self.client.command(sql, parameters=parameters)
        except Exception:
            logger.exception("ClickHouse command failed")
            raise

    def close(self):
        try:
            self.client.close()
        except Exception:
            logger.exception("Failed to close ClickHouse client")
            raise

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()
