from typing import Dict, Any, Optional

import segment.analytics as analytics
import kanaries_track

from pygwalker.services.global_var import GlobalVarManager
from pygwalker.services.config import get_local_user_id

analytics.write_key = 'z58N15R8LShkpUbBSt1ZjdDSdSEF5VpR'
kanaries_public_key = "tk-6572d7b34a03d7fcf6cf0c86-cOzZyr6xqd"
kanaries_track.config.auth_token = kanaries_public_key
kanaries_track.config.proxies = {}
kanaries_track.config.max_retries = 2


# pylint: disable=broad-exception-caught
def track_event(event: str, properties: Optional[Dict[str, Any]] = None):
    """
    Track an event in Segment and Kanaries.
    When privacy config of user is 'events',
    PyGWalker will collect certain events data share which events about which feature is used in pygwalker, it only contains events tag about which feature you arrive for product optimization. No DATA YOU ANALYZE IS SENT.
    We only use these data to improve the user experience of pygwalker. Events data will bind with a unique id, which is generated by pygwalker when it is installed based on timestamp. We will not collect any other information about you.
    EXAMPLE:
    - pygwalker's version
    - pygwalker's mode: 'light', 'dark' or 'auto'
    - pygwalker's spec type: 'json', 'file', 'url'. We won't collect the exact value of spec. No DATA YOU ANALYZE OR THEIR METADATA IS COLLECTED.

    - privacy  ['offline', 'update-only', 'events'] (default: events).
        "offline": fully offline, no data is send or api is requested
        "update-only": only check whether this is a new version of pygwalker to update
        "events": share which events about which feature is used in pygwalker, it only contains events data about which feature you arrive for product optimization. No DATA YOU ANALYZE IS SENT.
    """
    if GlobalVarManager.privacy == "events":
        try:
            analytics.track(
                user_id=get_local_user_id(),
                event=event,
                properties=properties
            )
            kanaries_track.track({**properties, "user_id": get_local_user_id()})
        except Exception:
            pass
