"""Sentry and PostHog telemetry initialization."""

from __future__ import annotations

import logging
from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
    from ._platform import PlatformClient

_posthog: Any = None
_user_id: str | None = None
_version: str | None = None


def init_telemetry(
    client: PlatformClient,
    *,
    version: str = "",
    enabled: bool = True,
    exclude_sentry_errors: bool = True,
    user_id: str | None = None,
) -> None:
    """Initialize all telemetry (Sentry + PostHog) in one call.

    When *user_id* is provided it is used directly; otherwise the
    user ID is fetched via *client*.
    """
    if not enabled:
        return

    _init_sentry(exclude_errors=exclude_sentry_errors)

    if user_id is None:
        user_id = client.get_user_id()
    _init_posthog(user_id=user_id, version=version)


def ph(event: str, properties: dict[str, Any] | None = None) -> None:
    """Log an event to PostHog."""
    if _posthog is None or _user_id is None:
        return

    props = dict(properties) if properties else {}
    if _version is not None:
        props["cli_version"] = _version

    _posthog.capture(
        distinct_id=_user_id,
        event=event,
        properties=props,
    )


def _init_sentry(*, exclude_errors: bool = False) -> None:
    """Configure and initialize the Sentry SDK."""
    import sentry_sdk  # noqa: PLC0415
    from sentry_sdk.integrations.logging import (  # noqa: PLC0415
        LoggingIntegration,
    )
    from sentry_sdk.integrations.stdlib import (  # noqa: PLC0415
        StdlibIntegration,
    )

    sentry_logging = LoggingIntegration(
        level=logging.INFO,
        event_level=logging.CRITICAL if exclude_errors else logging.ERROR,
    )

    sentry_sdk.init(
        dsn=(
            "https://4b9a1902f9361b48c04376df6483bc96"
            "@o4506833230561280.ingest.sentry.io/4506833262477312"
        ),
        integrations=[sentry_logging],
        disabled_integrations=[StdlibIntegration],  # type: ignore[list-item]
        traces_sample_rate=0,
        profiles_sample_rate=0,
        ignore_errors=[KeyboardInterrupt],
    )


def _init_posthog(
    *,
    user_id: str | None = None,
    version: str = "",
) -> None:
    """Configure and initialize the PostHog analytics client."""
    from posthog import Posthog  # noqa: PLC0415

    global _posthog, _user_id, _version  # noqa: PLW0603
    _user_id = user_id
    _version = version
    _posthog = Posthog(
        project_api_key=("phc_aUO790jHd7z1SXwsYCz8dRApxueplZlZWeDSpKc5hol"),
        host="https://us.posthog.com",
    )
    _posthog.log.setLevel(logging.CRITICAL)
    ph("cli-telemetry-enabled")
