from __future__ import annotations

import atexit
import http.client
import importlib
import json
import logging
import os
import random
import socket
import ssl
import threading
import time
import traceback
import uuid
from collections import defaultdict, deque
from contextlib import contextmanager, suppress
from contextvars import ContextVar
from dataclasses import dataclass
from datetime import datetime, timezone
from urllib.parse import urlsplit

try:
    from dotenv import load_dotenv  # type: ignore[import-not-found]
except ImportError:
    # python-dotenv is optional: on minimal shared hosting the application
    # can set TELEMETRY_* / COLLECTOR_* variables directly in the environment.
    load_dotenv = None

# ==============================================================================
# MODULE-LEVEL SETUP
# ==============================================================================

# A dedicated logger for the telemetry client itself.
# This prevents mixing library logs with the application's logs.
logger = logging.getLogger("telemetry_client")
logger.propagate = (
    False  # Prevent this library's logs from leaking into the host app's handlers.
)
if not logger.handlers:
    handler = logging.StreamHandler()
    formatter = logging.Formatter(
        "[%(asctime)s] -> %(levelname)s (%(threadName)s): %(message)s"
    )
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    # Default level for the client's own logs; overridable via TELEMETRY_LOG_LEVEL
    # in load_config_from_env() / init_telemetry().
    logger.setLevel(logging.WARNING)

# ==============================================================================
# SECTION 1: CONFIGURATION
# ==============================================================================


@dataclass
class TelemetryConfig:
    """
    A data class to hold all configuration settings for the telemetry client.
    This provides type safety and a single object for configuration.
    """

    enabled: bool
    collector_url: str | None
    api_key: str | None
    service_name: str
    batch_interval: int
    batch_size: int
    buffer_size: int
    general_sample_rate: float
    priority_sample_rate: float
    instrument_requests: bool
    instrument_httpx: bool
    instrument_aiohttp: bool
    instrument_redis: bool
    instrument_celery: bool
    enable_system_monitor: bool
    system_monitor_interval: int
    notify_level: str
    log_level: int
    capture_bodies: bool
    # use_proxy: bool
    # http_proxy: str | None
    # https_proxy: str | None


def _env_bool(name: str, default: bool = False) -> bool:
    """Reads a boolean env var with a sane default."""
    return os.getenv(name, str(default)).strip().lower() in ("1", "true", "yes", "on")


def _env_int(
    name: str, default: int, minimum: int = 1, maximum: int | None = None
) -> int:
    """Reads an integer env var, clamped to a sane range."""
    raw = os.getenv(name)
    try:
        value = int(raw) if raw is not None else default
    except (TypeError, ValueError):
        logger.warning(f"Invalid {name} '{raw}'. Defaulting to {default}.")
        value = default
    if maximum is not None:
        value = max(minimum, min(value, maximum))
    else:
        value = max(minimum, value)
    return value


def _env_sample_rate(name: str, default: float) -> float:
    """Reads a sampling rate env var, clamped to [0.0, 1.0]."""
    raw = os.getenv(name)
    try:
        value = float(raw) if raw is not None else default
    except (TypeError, ValueError):
        logger.warning(f"Invalid {name} '{raw}'. Defaulting to {default}.")
        value = default
    return max(0.0, min(1.0, value))


def load_config_from_env() -> TelemetryConfig:
    """
    Loads configuration from a .env file into a TelemetryConfig object.

    NOTE: load_dotenv(override=False) intentionally does NOT overwrite
    environment variables that the host application already set; the .env
    file only fills in missing values. This keeps the library from hijacking
    the deployment environment of the application it is embedded in.

    Returns:
        TelemetryConfig: An object containing all configuration settings.
    """
    if load_dotenv is None:
        logger.debug(
            "python-dotenv is not installed; relying on pre-set environment variables."
        )
    else:
        try:
            load_dotenv(override=False)
        except TypeError:  # python-dotenv < 0.20.0 does not support `override`
            load_dotenv()

    # Validate notify_level to ensure it's a valid log level
    raw_notify_level = os.getenv("TELEMETRY_NOTIFY_LEVEL", "ERROR").upper()
    if raw_notify_level not in logging._nameToLevel:
        logger.warning(
            f"Invalid TELEMETRY_NOTIFY_LEVEL '{raw_notify_level}'. Defaulting to ERROR."
        )
        raw_notify_level = "ERROR"

    # Validate the client's own log level
    raw_log_level = os.getenv("TELEMETRY_LOG_LEVEL", "WARNING").upper()
    if raw_log_level not in logging._nameToLevel:
        logger.warning(
            f"Invalid TELEMETRY_LOG_LEVEL '{raw_log_level}'. Defaulting to WARNING."
        )
        raw_log_level = "WARNING"
    log_level = logging._nameToLevel[raw_log_level]

    collector_url = (os.getenv("COLLECTOR_URL") or "").strip().rstrip("/")

    return TelemetryConfig(
        enabled=_env_bool("TELEMETRY_ENABLED"),
        collector_url=collector_url or None,
        api_key=os.getenv("API_KEY"),
        service_name=(
            os.getenv("SERVICE_NAME", "unnamed-service").strip() or "unnamed-service"
        ),
        batch_interval=_env_int(
            "TELEMETRY_BATCH_INTERVAL", 10, minimum=1, maximum=3600
        ),
        batch_size=_env_int("TELEMETRY_BATCH_SIZE", 50, minimum=1, maximum=10000),
        buffer_size=_env_int("TELEMETRY_BUFFER_SIZE", 5000, minimum=10, maximum=100000),
        general_sample_rate=_env_sample_rate("TELEMETRY_GENERAL_SAMPLE_RATE", 0.25),
        priority_sample_rate=_env_sample_rate("TELEMETRY_PRIORITY_SAMPLE_RATE", 1.0),
        instrument_requests=_env_bool("TELEMETRY_INSTRUMENT_REQUESTS"),
        instrument_httpx=_env_bool("TELEMETRY_INSTRUMENT_HTTPX"),
        instrument_aiohttp=_env_bool("TELEMETRY_INSTRUMENT_AIOHTTP"),
        instrument_redis=_env_bool("TELEMETRY_INSTRUMENT_REDIS"),
        instrument_celery=_env_bool("TELEMETRY_INSTRUMENT_CELERY"),
        enable_system_monitor=_env_bool("TELEMETRY_ENABLE_SYSTEM_MONITOR"),
        system_monitor_interval=_env_int(
            "TELEMETRY_SYSTEM_MONITOR_INTERVAL", 60, minimum=5, maximum=86400
        ),
        notify_level=raw_notify_level,
        log_level=log_level,
        capture_bodies=_env_bool("TELEMETRY_CAPTURE_BODIES"),
        # use_proxy=_env_bool("USE_PROXY"),
        # http_proxy=os.getenv("HTTP_PROXY"),
        # https_proxy=os.getenv("HTTPS_PROXY"),
    )


# ==============================================================================
# SECTION 1.5: MINIMAL HTTPS TRANSPORT (stdlib only)
# ==============================================================================
#
# The transport is intentionally built on http.client / ssl instead of
# requests/urllib3:
#   - zero third-party dependencies (important on shared hosting),
#   - no urllib3 "Starting new HTTPS connection" debug logs in the host app,
#   - one persistent keep-alive connection per process, so batch sends do not
#     pay a full TLS handshake every time (the main cause of the slow/timeout
#     POSTs and log spam previously observed),
#   - explicit control of connect vs read timeouts, transient retries and
#     Retry-After handling.

_RETRIABLE_STATUS = frozenset({429, 500, 502, 503, 504})

_throttle_last_log: dict = {}
_throttle_counter: dict = {}
_throttle_lock = threading.Lock()


def _throttled_log(key: str, level: int, message: str, min_interval: float = 60.0):
    """
    Logs `message` at most once per `min_interval` seconds per `key`.
    Occurrences in between are counted and reported in the next visible log,
    so a flaky or slow collector can never flood the host app's logs.
    """
    now = time.monotonic()
    with _throttle_lock:
        if now - _throttle_last_log.get(key, 0.0) >= min_interval:
            _throttle_last_log[key] = now
            suppressed = _throttle_counter.pop(key, 0)
            suffix = f" ({suppressed} occurrences suppressed)" if suppressed else ""
            logger.log(level, f"{message}{suffix}")
        else:
            _throttle_counter[key] = _throttle_counter.get(key, 0) + 1


class HTTPSender:
    """
    A tiny keep-alive HTTP(S) client built on the standard library.

    One instance is shared by the TelemetryClient worker thread, so all batch
    sends reuse a single connection. Plain http:// is only accepted for local
    hosts (dev/test); anything else must be https://.
    """

    def __init__(
        self,
        connect_timeout: float = 5.0,
        read_timeout: float = 15.0,
        retries: int = 2,
        retry_backoff: float = 0.5,
    ):
        self.connect_timeout = connect_timeout
        self.read_timeout = read_timeout
        self.retries = retries
        self.retry_backoff = retry_backoff
        self._context = ssl.create_default_context()
        self._conn: http.client.HTTPConnection | None = None
        self._conn_netloc: str | None = None
        self._lock = threading.Lock()

    def _close_locked(self):
        """Closes the persistent connection. Caller MUST already hold self._lock."""
        if self._conn is not None:
            with suppress(Exception):
                self._conn.close()
            self._conn = None
            self._conn_netloc = None

    def close(self):
        """Closes the persistent connection, if any."""
        with self._lock:
            self._close_locked()

    def _new_connection(self, scheme: str, host: str, port: int):
        if scheme == "https":
            return http.client.HTTPSConnection(
                host, port, timeout=self.connect_timeout, context=self._context
            )
        if scheme == "http":
            if host not in ("localhost", "127.0.0.1", "::1"):
                raise ValueError(
                    f"Refusing plaintext http:// to non-local host '{host}'. "
                    "Use https:// for the telemetry collector."
                )
            return http.client.HTTPConnection(host, port, timeout=self.connect_timeout)
        raise ValueError(f"Unsupported scheme '{scheme}' in collector URL.")

    def post_json(self, url: str, body: bytes, headers: dict) -> tuple[int, bytes]:
        """
        POSTs `body` to `url` over the persistent connection.

        Returns (status_code, response_body).
        Raises OSError / http.client.HTTPException / ssl.SSLError / ValueError
        after transient retries are exhausted; the caller decides how to react.
        """
        parsed = urlsplit(url)
        host = parsed.hostname or ""
        port = parsed.port or (443 if parsed.scheme == "https" else 80)
        netloc = f"{parsed.scheme}:{host}:{port}"
        path = parsed.path or "/"
        if parsed.query:
            path += "?" + parsed.query

        last_error: Exception | None = None

        with self._lock:
            for attempt in range(self.retries + 1):
                try:
                    if self._conn is None or self._conn_netloc != netloc:
                        self._close_locked()
                        self._conn = self._new_connection(parsed.scheme, host, port)
                        self._conn_netloc = netloc
                    conn = self._conn
                    conn.request("POST", path, body=body, headers=dict(headers))
                    if conn.sock is not None:
                        conn.sock.settimeout(self.read_timeout)
                    resp = conn.getresponse()
                    status = resp.status
                    resp_body = resp.read()
                    if status in _RETRIABLE_STATUS and attempt < self.retries:
                        # Transient server-side failure: honor Retry-After when
                        # present, otherwise exponential backoff, then retry.
                        self._close_locked()
                        try:
                            retry_after = int(
                                (resp.getheader("Retry-After") or "").strip() or 0
                            )
                        except (TypeError, ValueError):
                            retry_after = 0
                        time.sleep(
                            min(retry_after, 30)
                            if retry_after
                            else self.retry_backoff * (2**attempt)
                        )
                        continue
                    return status, resp_body
                except (
                    TimeoutError,
                    ConnectionError,
                    OSError,
                    http.client.HTTPException,
                    ssl.SSLError,
                ) as exc:
                    last_error = exc
                    self._close_locked()
                    if attempt < self.retries:
                        time.sleep(self.retry_backoff * (2**attempt))
                        continue
                    raise

        if last_error is None:
            raise RuntimeError(
                "HTTPSender.post_json finished without a result or error (unreachable)"
            )
        raise last_error


# ==============================================================================
# SECTION 1.6: PAYLOAD SANITIZATION (shared by web integrations)
# ==============================================================================

# Keys whose values are masked recursively (case-insensitive substring match).
SENSITIVE_KEYS = (
    "password",
    "token",
    "access_token",
    "csrf_token",
    "secret",
    "apikey",
    "api_key",
    "api_token",
    "authorization",
)

# Cap for captured request/response bodies (bytes before decode, characters
# after JSON re-serialization).
MAX_BODY_CAPTURE = 8192


def _mask_sensitive(value):
    """Recursively masks keys matching SENSITIVE_KEYS (dicts AND lists)."""
    if isinstance(value, dict):
        return {
            key: (
                "*** MASKED ***"
                if any(s in key.lower() for s in SENSITIVE_KEYS)
                else _mask_sensitive(val)
            )
            for key, val in value.items()
        }
    if isinstance(value, list):
        return [_mask_sensitive(item) for item in value]
    return value


def sanitize_payload(
    payload_str: str | None, max_chars: int = MAX_BODY_CAPTURE
) -> str | None:
    """
    Sanitizes a JSON string (dict or list) by recursively masking sensitive
    keys, then caps it at `max_chars`. Non-JSON input is simply truncated.
    Returns None for empty input so integrators can store an explicit
    "not captured" value.
    """
    if not payload_str:
        return None
    try:
        data = json.loads(payload_str)
    except (json.JSONDecodeError, TypeError, RecursionError):
        return payload_str[:max_chars]
    sanitized = json.dumps(_mask_sensitive(data), indent=2)
    if len(sanitized) > max_chars:
        return sanitized[:max_chars] + "\n... (truncated)"
    return sanitized


# ==============================================================================
# SECTION 2: CONTEXT MANAGEMENT & TRACING HELPERS
# ==============================================================================

# Context variables are used to store trace and span data in a way that is
# safe for both multi-threaded and asynchronous (asyncio) environments.
trace_id_var: ContextVar[str | None] = ContextVar("trace_id", default=None)
spans_var: ContextVar[list | None] = ContextVar("spans", default=None)


def start_trace() -> str:
    """Generates a new UUID for a trace and sets it in the current context."""
    trace_id = str(uuid.uuid4())
    trace_id_var.set(trace_id)
    return trace_id


def get_trace_id() -> str | None:
    """Retrieves the current trace ID from the context."""
    return trace_id_var.get()


# HTTP header used to propagate the trace id across services.
TRACE_ID_HEADER = "X-Telemetry-Trace-Id"


def extract_trace_id(headers) -> str | None:
    """
    Extracts and validates a trace id from incoming request headers.

    Returns None when absent or malformed so the caller starts a new trace
    instead of trusting bogus data. Values are normalized to the canonical
    UUID string form.
    """
    value = headers.get(TRACE_ID_HEADER) if headers is not None else None
    if not value:
        return None
    try:
        return str(uuid.UUID(str(value).strip()))
    except (ValueError, AttributeError, TypeError):
        return None


def inject_trace_id(target_headers: dict) -> None:
    """
    Adds the current trace id to an outgoing headers dict, if a trace is
    active. Used by the HTTP client integrations so downstream services can
    adopt the same trace.
    """
    trace_id = get_trace_id()
    if trace_id:
        target_headers[TRACE_ID_HEADER] = trace_id


@contextmanager
def trace_transaction(name: str):
    """
    A context manager to trace a block of code as a main transaction.
    Ideal for non-web applications like scripts or background workers.

    Usage:
        with trace_transaction("My Daily Job"):
            # code to be traced...

    Args:
        name (str): A descriptive name for the transaction.
    """
    client = get_current_client()
    if not client or not client.config.enabled:
        yield
        return

    # Initialize context for this transaction
    trace_id = start_trace()
    spans_var.set([])
    start_time = time.perf_counter()
    has_error = False
    # logger.info(f"Starting transaction: '{name}' (Trace ID: {trace_id})")

    try:
        yield
    except Exception as e:
        has_error = True
        capture_exception(e)  # Capture the exception as an error event
        raise  # Re-raise the exception so the application knows it failed
    finally:
        duration_ms = (time.perf_counter() - start_time) * 1000
        collected_spans = spans_var.get() or []
        # logger.info(f"Finished transaction: '{name}'. Duration: {duration_ms:.2f} ms")

        end_dt = datetime.now(timezone.utc)
        start_dt = datetime.fromtimestamp(
            end_dt.timestamp() - (duration_ms / 1000), tz=timezone.utc
        )

        trace_payload = {
            "trace": {
                "id": trace_id,
                "http_method": "JOB",  # Special method type for non-web transactions
                "http_path": name,
                "http_host": socket.gethostname(),
                "http_status_code": 500 if has_error else 200,
                "duration_ms": int(duration_ms),
                "has_error": has_error,
                "start_timestamp": start_dt.isoformat(),
                "end_timestamp": end_dt.isoformat(),
            },
            "logs_and_spans": collected_spans,
        }
        client.capture_trace(trace_payload)

        # Clean up context variables
        trace_id_var.set(None)
        spans_var.set(None)


def _build_span_payload(
    name: str,
    duration_ms: float,
    start_timestamp: str,
    attributes: dict | None = None,
    span_type: str = "function",
) -> dict:
    """
    Builds the canonical span payload dict shared by every integration.

    Keeping the shape in one place guarantees that spans recorded by the
    context manager, the log handler, DB wrappers and manual recorders all
    carry identical fields for the collector / dashboard.
    """
    try:
        duration_ms_int = int(duration_ms)
    except (TypeError, ValueError):
        # A malformed duration must never crash the caller's request path.
        duration_ms_int = 0
    return {
        "span_id": str(uuid.uuid4()),
        "trace_id": get_trace_id(),
        "type": span_type,
        "message": name,
        "duration_ms": duration_ms_int,
        "start_timestamp": start_timestamp,
        "attributes": attributes or {},
    }


def record_span(
    name: str,
    duration_ms: float,
    start_timestamp: str | None = None,
    attributes: dict | None = None,
    span_type: str = "function",
) -> dict | None:
    """
    Records a span directly into the currently active trace context without
    needing a `with` block. This is the API integrations use when an
    operation can only be measured through callbacks (PyMongo command
    monitoring, gRPC interceptors, custom wrappers).

    Returns the new span payload dict, or None if no trace is active.

    Usage:
        t0 = time.perf_counter()
        result = some_operation()
        record_span(
            "some.operation",
            (time.perf_counter() - t0) * 1000,
            span_type="db.query",
            attributes={"db.system": "redis"},
        )
    """
    active_spans = spans_var.get()
    if active_spans is None or get_trace_id() is None:
        return None

    span_payload = _build_span_payload(
        name,
        duration_ms,
        start_timestamp or datetime.now(timezone.utc).isoformat(),
        attributes,
        span_type,
    )
    active_spans.append(span_payload)
    return span_payload


@contextmanager
def trace_span(name: str, attributes: dict | None = None):
    """
    A context manager to trace a specific sub-process (span) within an
    active transaction. It does nothing if no transaction is active.

    Usage:
        with trace_transaction("Main Job"):
            with trace_span("Step 1: Reading file"):
                # code for step 1...

    Args:
        name (str): A descriptive name for the span.
        attributes (dict, optional): Extra key-value metadata for the span.
    """
    # Only run if we are inside an active trace
    active_spans = spans_var.get()
    trace_id = get_trace_id()
    if active_spans is None or trace_id is None:
        yield
        return

    start_time = time.perf_counter()
    logger.debug(f"Starting span: '{name}'")

    try:
        yield
    finally:
        duration_ms = (time.perf_counter() - start_time) * 1000
        logger.debug(f"Finished span: '{name}'. Duration: {duration_ms:.2f} ms")
        active_spans.append(
            _build_span_payload(
                name,
                duration_ms,
                datetime.now(timezone.utc).isoformat(),
                attributes,
            )
        )


# ==============================================================================
# SECTION 3: CORE TELEMETRY CLIENT
# ==============================================================================


class TelemetryClient:
    """
    Manages the data buffer and the background worker thread for sending
    telemetry data asynchronously.
    """

    def __init__(self, config: TelemetryConfig):
        self.config = config
        self._buffer = deque(maxlen=config.buffer_size)
        self._buffer_maxlen = config.buffer_size
        self._lock = threading.Lock()
        self._stop_event = threading.Event()
        # Self-observability counters for ops (sent/failed/dropped/batches).
        self._stats = {"sent": 0, "failed": 0, "dropped": 0, "batches": 0}
        self._worker_thread = threading.Thread(
            target=self._batch_sender_worker, name="TelemetryWorker", daemon=True
        )

        self._current_user_agent = None
        self._user_agent_expiry = time.time()

        # Persistent keep-alive transport shared by the worker thread.
        self._sender = HTTPSender()

        if self.config.enabled:
            logger.setLevel(self.config.log_level)
            # logger.info(f"Telemetry enabled for service '{self.config.service_name}'. Starting worker...")
            self._worker_thread.start()
            atexit.register(self.shutdown)

    def _get_user_agent(self) -> str:
        """
        Returns the current User-Agent. If the current one has expired,
        it selects a new one and sets a new expiry time.
        """
        now = time.time()

        VALID_USER_AGENTS = [
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:127.0) Gecko/20100101 Firefox/127.0",
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Safari/605.1.15",
            "Mozilla/5.0 (Linux; Android 14) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Mobile Safari/537.36",
        ]

        # Cek if User-Agent has expired or is not set or needs rotation
        if self._current_user_agent is None or now > self._user_agent_expiry:
            self._current_user_agent = random.choice(VALID_USER_AGENTS)
            # Set new expiry time, between 15 to 30 minutes from now
            expiry_seconds = random.randint(900, 1800)
            self._user_agent_expiry = now + expiry_seconds
            # logger.debug(f"Rotated User-Agent. New UA will be used for the next {expiry_seconds / 60:.1f} minutes.")

        return self._current_user_agent

    def _batch_sender_worker(self):
        """
        The main loop for the background worker thread.

        Implements adaptive backoff: when a batch cycle fails (flaky network,
        collector down), the wait interval doubles up to a cap so the client
        stops hammering a dead collector and stops repeating timeouts. The
        interval resets as soon as a cycle succeeds.
        """
        consecutive_failures = 0
        max_backoff = 300  # seconds — never wait longer than 5 minutes

        while not self._stop_event.is_set():
            wait_interval = min(
                self.config.batch_interval * (2**consecutive_failures),
                max_backoff,
            )
            self._stop_event.wait(wait_interval)

            batch_to_process = []
            with self._lock:
                while self._buffer and len(batch_to_process) < self.config.batch_size:
                    batch_to_process.append(self._buffer.popleft())

            if not batch_to_process:
                continue

            had_failure = self._process_and_send_batch(batch_to_process)
            consecutive_failures = consecutive_failures + 1 if had_failure else 0

    def _process_and_send_batch(self, batch_items: list) -> bool:
        """
        Groups data by endpoint, serializes it, and sends each group over the
        persistent keep-alive transport.

        Returns:
            bool: True if a TRANSIENT failure occurred (5xx / timeout /
            connection error) — used by the worker loop for adaptive backoff.
            Permanent 4xx rejections (bad payload, bad API key) do NOT drive
            backoff: they are dropped, counted, and reported once via a
            throttled log, so one bad endpoint cannot stall unrelated traffic.
        """
        grouped_payloads = defaultdict(lambda: {"key": None, "payloads": []})
        for item in batch_items:
            endpoint = item["endpoint"]
            grouped_payloads[endpoint]["key"] = item["batch_key"]
            grouped_payloads[endpoint]["payloads"].append(item["payload"])

        any_transient_failure = False

        for endpoint, data in grouped_payloads.items():
            final_payload = {data["key"]: data["payloads"]}
            try:
                headers = {
                    "Authorization": f"Bearer {self.config.api_key}",
                    "X-Telemetry-Service-Name": self.config.service_name,
                    "Content-Type": "application/json",
                    "User-Agent": self._get_user_agent(),
                }
                full_url = f"{self.config.collector_url}{endpoint}"
                status, _ = self._sender.post_json(
                    url=full_url,
                    body=json.dumps(final_payload).encode("utf-8"),
                    headers=headers,
                )
                if status >= 400:
                    # 5xx means the collector was reachable but sick; the
                    # sender already retried internally — surface it for
                    # backoff. A 4xx is permanent (config/payload problem):
                    # dropping and reporting once is the correct response.
                    if status in _RETRIABLE_STATUS:
                        any_transient_failure = True
                    self._stats["failed"] += len(data["payloads"])
                    _throttled_log(
                        f"status.{status}",
                        logging.ERROR,
                        f"Telemetry collector rejected {endpoint} with status {status}. "
                        "Check COLLECTOR_URL / API_KEY configuration.",
                    )
                else:
                    self._stats["sent"] += len(data["payloads"])
                    self._stats["batches"] += 1
            except Exception as e:
                # Never let a failed send take the worker down (matching the
                # original defense-in-depth intent), but count and log it.
                any_transient_failure = True
                self._stats["failed"] += len(data["payloads"])
                if isinstance(e, (socket.timeout, TimeoutError)):
                    _throttled_log(
                        f"timeout.{endpoint}",
                        logging.WARNING,
                        f"Request to {endpoint} timed out.",
                    )
                elif isinstance(e, ssl.SSLError):
                    _throttled_log(
                        f"ssl.{endpoint}",
                        logging.ERROR,
                        f"SSL error connecting to {self.config.collector_url}. Details: {e}",
                    )
                else:
                    _throttled_log(
                        f"conn.{endpoint}",
                        logging.ERROR,
                        f"Connection error: could not reach telemetry server at "
                        f"{self.config.collector_url}. Details: {e}",
                    )
        return any_transient_failure

    def _add_to_buffer(self, endpoint: str, payload: dict, batch_key: str):
        """Thread-safely adds a data item to the buffer."""
        if not self.config.enabled:
            return
        with self._lock:
            # Bounded buffer: if the collector is unreachable for a long time,
            # drop the oldest items instead of letting memory grow forever.
            if len(self._buffer) >= self._buffer_maxlen:
                self._buffer.popleft()
                self._stats["dropped"] += 1
            self._buffer.append(
                {"endpoint": endpoint, "payload": payload, "batch_key": batch_key}
            )

    def capture_trace(self, trace_payload: dict):
        """Public method to submit a trace payload."""
        self._add_to_buffer("/v1/traces", trace_payload, batch_key="traces")

    def capture_error(self, exception: Exception, context: dict | None = None):
        """Formats an exception and submits it as an error payload."""
        full_traceback = traceback.format_exc()
        try:
            # Coba ambil baris relevan dari traceback
            error_location = full_traceback.splitlines()[-3].strip()
        except IndexError:
            # Fallback jika traceback terlalu pendek
            error_location = "N/A (short traceback)"

        error_payload = {
            "trace_id": get_trace_id(),
            "error_class": type(exception).__name__,
            "error_message": str(exception),
            "error_location": error_location,
            "stack_trace": traceback.format_exc(),
            "request_context": context or {},
            "notify": True,  # Unhandled exceptions always trigger notification
        }
        self._add_to_buffer("/v1/errors", error_payload, batch_key="errors")

    def capture_metric(self, name: str, value: float, attributes: dict | None = None):
        """Public method to submit a single metric data point."""
        metric_payload = {
            "name": name,
            "value": value,
            "timestamp": datetime.now(timezone.utc).isoformat(),
            "attributes": attributes or {},
        }
        self._add_to_buffer("/v1/metrics", metric_payload, batch_key="metrics")

    def get_self_metrics(self) -> dict:
        """
        Returns a snapshot of the client's own counters — useful for ops to
        alert on (e.g., dropped > 0 while the collector is down):
        {"sent": int, "failed": int, "dropped": int, "batches": int}
        """
        with self._lock:
            return dict(self._stats)

    def shutdown(self):
        """Gracefully shuts down the worker, flushing any remaining data."""
        if not self.config.enabled or self._stop_event.is_set():
            return

        # logger.info("Telemetry client shutting down, flushing remaining buffer...")
        self._stop_event.set()

        final_batch = []
        with self._lock:
            final_batch.extend(self._buffer)
            self._buffer.clear()

        if final_batch:
            self._process_and_send_batch(final_batch)

        self._worker_thread.join(timeout=5)
        self._sender.close()


# ==============================================================================
# SECTION 4: LOGGING HANDLER
# ==============================================================================
class TelemetryLogHandler(logging.Handler):
    """
    A universal logging handler that captures log records and converts them
    into spans within an active telemetry trace.
    """

    def __init__(self, level=logging.NOTSET):
        super().__init__(level)
        self.client_config = None
        self.notify_level_value = logging.CRITICAL + 1

    def _initialize_config(self):
        """Lazily initialize config to avoid circular dependency at import time."""
        if self.client_config is None:
            client = get_current_client()
            if client:
                self.client_config = client.config
                self.notify_level_value = logging._nameToLevel.get(
                    self.client_config.notify_level, logging.CRITICAL + 1
                )

    def emit(self, record: logging.LogRecord):
        """
        Formats and appends a log record to the active span list.
        """
        active_spans = spans_var.get()
        if active_spans is not None:
            log_span = {
                "span_id": str(uuid.uuid4()),
                "trace_id": get_trace_id(),
                "type": "log",
                "level": record.levelname,
                "message": record.getMessage(),
                "start_timestamp": datetime.now(timezone.utc).isoformat(),
                "attributes": {"log.source": record.name, "log.lineno": record.lineno},
            }
            # Add notify flag if log level is at or above the configured threshold.
            if record.levelno >= self.notify_level_value:
                log_span["notify"] = True

            active_spans.append(log_span)


# ==============================================================================
# SECTION 5: GLOBAL SINGLETON AND PUBLIC API
# ==============================================================================

_client: TelemetryClient | None = None
_client_lock = threading.Lock()
# Global flag to track if telemetry has been initialized
_telemetry_initialized = False


def _system_monitor_worker(client: TelemetryClient):
    """
    Background worker that periodically collects and sends system metrics.
    Runs in a separate thread from within the client application process.
    """
    try:
        import psutil  # type: ignore[import-not-found]
    except ImportError:
        logger.error(
            "psutil library is required for system monitoring but is not installed."
        )
        return

    # logger.info("System metrics monitoring thread has started.")
    # Retrieve initial network I/O statistics for comparison
    net_io_start = psutil.net_io_counters()

    static_attributes = {
        "host.cpu.cores": psutil.cpu_count(logical=True),
        "host.memory.total_gb": round(psutil.virtual_memory().total / (1024**3), 2),
        "host.memory.available_gb": round(
            psutil.virtual_memory().available / (1024**3), 2
        ),
        "host.disk.total_gb": round(psutil.disk_usage("/").total / (1024**3), 2),
        "host.disk.used_gb": round(psutil.disk_usage("/").used / (1024**3), 2),
    }

    while True:
        try:
            # Wait for the next interval
            time.sleep(client.config.system_monitor_interval)

            # --- Retrieve CPU, Memory, Network, Disk I/O ---
            # net_io_end = psutil.net_io_counters()
            # bytes_sent = net_io_end.bytes_sent - net_io_start.bytes_sent
            # bytes_recv = net_io_end.bytes_recv - net_io_start.bytes_recv
            # net_io_start = net_io_end

            # system_metrics = {
            #    # CPU
            #    "cpu.usage_percent": psutil.cpu_percent(interval=1),
            #    "cpu.core_count": psutil.cpu_count(logical=True),
            #    # Memory
            #    "memory.total_gb": round(psutil.virtual_memory().total / (1024**3), 2),
            #    "memory.available_gb": round(psutil.virtual_memory().available / (1024**3), 2),
            #    "memory.usage_percent": psutil.virtual_memory().percent,
            #    # Disk (untuk root partition '/')
            #    "disk.total_gb": round(psutil.disk_usage('/').total / (1024**3), 2),
            #    "disk.used_gb": round(psutil.disk_usage('/').used / (1024**3), 2),
            #    "disk.usage_percent": psutil.disk_usage('/').percent,
            #    # Network
            #    "network.bytes_sent_per_interval": bytes_sent,
            #    "network.bytes_recv_per_interval": bytes_recv,
            # }
            # --- End Retrieval ---

            # Wrap and send data
            # with trace_transaction("System Metrics Report"):
            #    with trace_span("psutil.collect", attributes=system_metrics):
            #        pass # Just a placeholder to create a span

            # --- Retrieve CPU, Memory, Network, Disk I/O ---
            # CPU
            cpu_usage = psutil.cpu_percent(interval=1)
            # Memory
            memory_usage = psutil.virtual_memory().percent
            # Disk (for root partition '/')
            disk_usage = psutil.disk_usage("/").percent
            # Network
            net_io_end = psutil.net_io_counters()
            bytes_sent = net_io_end.bytes_sent - net_io_start.bytes_sent
            bytes_recv = net_io_end.bytes_recv - net_io_start.bytes_recv
            net_io_start = net_io_end

            # Send all metrics
            client.capture_metric(
                "system.cpu.usage",
                cpu_usage,
                attributes={**static_attributes, "unit": "%"},
            )
            # client.capture_metric('system.cpu.core_count', cpu_core_count, attributes={'unit': 'cores'})
            # client.capture_metric('system.memory.total_gb', memory_total_gb, attributes={'unit': 'GB'})
            # client.capture_metric('system.memory.available_gb', memory_available_gb, attributes={'unit': 'GB'})
            client.capture_metric(
                "system.memory.usage",
                memory_usage,
                attributes={**static_attributes, "unit": "%"},
            )
            # client.capture_metric('system.disk.total_gb', disk_total_gb, attributes={'unit': 'GB', 'path': '/'})
            # client.capture_metric('system.disk.used_gb', disk_used_gb, attributes={'unit': 'GB', 'path': '/'})
            client.capture_metric(
                "system.disk.usage",
                disk_usage,
                attributes={**static_attributes, "unit": "%", "path": "/"},
            )
            client.capture_metric(
                "network.bytes.sent", bytes_sent, attributes={"unit": "bytes"}
            )
            client.capture_metric(
                "network.bytes.received", bytes_recv, attributes={"unit": "bytes"}
            )

            # logger.debug("System metrics sent successfully.")

        except Exception as e:
            logger.error(f"Error in system monitor thread: {e}", exc_info=True)
            # If an error occurs, we can log it and continue monitoring.
            time.sleep(
                client.config.system_monitor_interval * 5
            )  # Sleep longer to avoid tight loop on errors
            # time.sleep(300)  # Sleep for 5 minutes before retrying to avoid tight loop


def init_telemetry(app=None, db_engine=None, log_level=logging.INFO):
    """
    Initializes the global telemetry client. This is the main entry point.

    It sets up a singleton TelemetryClient instance, attaches the log handler,
    and automatically detects and sets up integrations for known frameworks
    like Flask and FastAPI. This function should be called once at application startup.

    Args:
        app (optional): A web framework application instance (e.g., Flask, FastAPI).
        db_engine (optional): A SQLAlchemy Engine instance.
        log_level (int, optional): The minimum level for logs to be captured by
                                    the telemetry handler. Defaults to logging.INFO.

    Returns:
        TelemetryClient | None: The active client instance, or None if disabled.
    """
    global _client, _telemetry_initialized

    if _telemetry_initialized:
        return _client

    with _client_lock:
        if _telemetry_initialized:
            return _client

        # if _client:
        #    return _client

        config = load_config_from_env()
        if not config.enabled:
            if not _telemetry_initialized:
                logger.warning("Telemetry is disabled by configuration.")
            _telemetry_initialized = True
            return None
        if not all([config.collector_url, config.api_key]):
            if not _telemetry_initialized:
                logger.error(
                    "Telemetry disabled: COLLECTOR_URL and API_KEY must be set."
                )
            _telemetry_initialized = True
            return None

        _client = TelemetryClient(config)
        # logger.info(f"Telemetry client initialized for service '{config.service_name}'.")

        # Attach the universal log handler to the root logger. This is done only once.
        telemetry_handler = TelemetryLogHandler()
        telemetry_handler.setLevel(log_level)
        logging.getLogger().addHandler(telemetry_handler)
        # logger.info(f"TelemetryLogHandler attached to root logger with level {logging.getLevelName(log_level)}.")

        # --- Extensibility Point for Framework Integrations ---
        # Each integration is loaded lazily and OPTIONALLY. On a portable,
        # copy-and-embed package the import context may lack the framework,
        # so a missing/broken optional dependency must degrade silently
        # instead of breaking the host application's startup.
        def _load_integration(name: str):
            try:
                return importlib.import_module(f".integrations.{name}", package=__package__)
            except (ImportError, ValueError):
                logger.debug(f"Telemetry integration '{name}' unavailable, skipped.")
                return None

        if app:
            app_type_name = type(app).__name__.lower()
            for name in ("flask", "fastapi"):
                if name in app_type_name:
                    module = _load_integration(name)
                    if module is not None and hasattr(module, "setup"):
                        module.setup(app, _client)
                    break

        if db_engine:
            module = _load_integration("sqlalchemy")
            if module is not None and hasattr(module, "setup"):
                module.setup(db_engine, _client)

        # --- Automatic Instrumentation ---
        for name in ("requests", "httpx", "aiohttp", "redis", "celery"):
            if not getattr(_client.config, f"instrument_{name}", False):
                continue
            module = _load_integration(name)
            if module is not None and hasattr(module, "instrument"):
                module.instrument()

        # --- Thread Monitor System ---
        if _client.config.enable_system_monitor:
            monitor_thread = threading.Thread(
                target=_system_monitor_worker,
                args=(_client,),
                name="SystemMonitorWorker",
                daemon=True,
            )
            monitor_thread.start()
            # logger.info("System metrics monitoring thread started.")

        # Mark telemetry as initialized
        _telemetry_initialized = True

    return _client


def capture_exception(exc: Exception, context: dict | None = None):
    """A convenient public function to capture an exception manually."""
    if _client:
        _client.capture_error(exc, context)


def get_current_client() -> TelemetryClient | None:
    """Returns the globally active client instance."""
    return _client
