import os
from typing import Any

from posthog import Posthog

_posthog: Posthog | None = None

if os.environ.get("ENVIRONMENT", default="") == "PRODUCTION":
    _posthog = Posthog(project_api_key="phc_aUO790jHd7z1SXwsYCz8dRApxueplZlZWeDSpKc5hol", host="https://us.posthog.com")

ENVIRONMENT_TYPE = os.environ.get("ENVIRONMENT", default="None")
OPENAI_API_TYPE = os.environ.get("OPENAI_API_TYPE", default="azure")


def ph(user_id: str, event: str, properties: dict[str, Any] | None = None) -> None:
    """Log an event to PostHog.

    :param user_id: user id e.g. github|1234567890
    :param event: The name of the event.
    :param properties: A dictionary of properties to attach to the event.
    """
    if _posthog is None:
        return

    if properties is None:
        properties = {}

    properties["environment"] = ENVIRONMENT_TYPE
    properties["openai_api_type"] = OPENAI_API_TYPE

    _posthog.capture(distinct_id=user_id, event=event, properties=properties)
