import logging
import httpx
from datetime import datetime


class LokiHandler(logging.Handler):
    """ Log handler for sending to Grafana Loki """

    def __init__(self, loki_host: str, loki_port: str | int, labels: dict):
        super().__init__()
        self.url = f"http://{loki_host}:{loki_port}/loki/api/v1/push"
        self.labels = labels
        self.client = httpx.Client()

    def emit(self, record: logging.LogRecord):
        """ Sending log to Loki """
        log_entry = {
            "streams": [
                {
                    "stream": self.labels, 
                    "values": [
                        [str(int(datetime.utcnow().timestamp() * 1e9)), self.format(record)]
                    ]
                }
            ]
        }
        try:
            response = self.client.post(self.url, json=log_entry)
            response.raise_for_status()
        except httpx.HTTPStatusError as e:
            print(f"Error sending log: {e}")

def setup_logger(loki_host, loki_port, labels: dict, logging_level: str = logging.DEBUG):
    logger = logging.getLogger("loki_logger")
    logger.setLevel(logging_level)

    loki_handler = LokiHandler(loki_host, loki_port, labels)
    formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
    loki_handler.setFormatter(formatter)
    logger.addHandler(loki_handler)
    return logger

# logger = setup_logger("185.253.7.140", 3100, labels={"app": "salesmanago_tools"})
# logger.info("TEST")