from contextlib import suppress

import jingrow
from posthog import Posthog

from jcloud.utils import log_error


def init_telemetry():
	"""Init posthog for server side telemetry."""
	if hasattr(jingrow.local, "posthog"):
		return

	posthog_host = jingrow.conf.get("posthog_host")
	posthog_project_id = jingrow.conf.get("posthog_project_id")

	if not posthog_host or not posthog_project_id:
		return

	with suppress(Exception):
		jingrow.local.posthog = Posthog(posthog_project_id, host=posthog_host)


def capture(event, app, site=None):
	init_telemetry()
	ph: Posthog = getattr(jingrow.local, "posthog", None)
	with suppress(Exception):
		ph and ph.capture(site or jingrow.local.site, f"{app}_{event}")


def identify(site, **kwargs):
	init_telemetry()
	ph: Posthog = getattr(jingrow.local, "posthog", None)
	with suppress(Exception):
		ph and ph.identify(site, kwargs)


@jingrow.whitelist(allow_guest=True)
def capture_read_event(email: str = None):
	try:
		capture("read_email", "fc_signup", email)
	except Exception as e:
		log_error("Failed to capture read_email event", e)
	finally:
		jingrow.response.update(jingrow.utils.get_imaginary_pixel_response())
