import logging
import json
import requests
from queue import Queue
from threading import Thread
from datetime import datetime, timezone


class VictoriaLogsHandler(logging.Handler):
    def __init__(self, endpoint: str, timeout=1.0):
        super().__init__()
        self.endpoint = endpoint
        self.timeout = timeout

    def emit(self, record: logging.LogRecord):
        try:
            log = {
                "_msg": record.getMessage(),
                "level": record.levelname,
                "logger": record.name,
                "module": record.module,
                "func": record.funcName,
                "line": record.lineno,
                "service": "ldnode",
                "env": "dev",
                "ts": datetime.now(timezone.utc).isoformat()
            }

            requests.post(
                self.endpoint,
                data=json.dumps(log),
                headers={"Content-Type": "application/json"},
                timeout=self.timeout,
            )
        except Exception:
            # ⚠️ 千万不要在 logger 里再抛 logger
            pass

class AsyncVictoriaLogsHandler(VictoriaLogsHandler):
    def __init__(self, endpoint):
        super().__init__(endpoint)
        self.queue = Queue(maxsize=10000)
        Thread(target=self._worker, daemon=True).start()

    def emit(self, record):
        try:
            self.queue.put_nowait(record)
        except Exception:
            pass

    def _worker(self):
        buffer = []
        while True:
            record = self.queue.get()
            buffer.append(self.format_record(record))

            if len(buffer) >= 50:
                self.flush_buffer(buffer)
                buffer.clear()

    def format_record(self, record):
        return {
            "_msg": record.getMessage(),
            "level": record.levelname,
            "service": "ldnode",
            "ts": datetime.now(timezone.utc).isoformat(),
        }

    def flush_buffer(self, buffer):
        data = "\n".join(json.dumps(x) for x in buffer)
        requests.post(
            self.endpoint,
            data=data,
            headers={"Content-Type": "application/json"},
            timeout=1.0,
        )
