{# The final Go code is autogenerated, but this template is not. Please file bugs! #}
"""
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.

AUTOGENERATED BY glean_parser v{{ parser_version }}. DO NOT EDIT. DO NOT COMMIT.
"""

from __future__ import annotations
from datetime import datetime, timezone
from typing import Any
from uuid import uuid4
import json

GLEAN_EVENT_MOZLOG_TYPE = "glean-server-event"


{% for ping, metrics_by_type in pings.items() %}
class {{ ping|camelize }}ServerEventLogger:
    def __init__(
        self, application_id: str, app_display_version: str, channel: str
    ) -> None:
        """
        Create {{ ping|camelize }}ServerEventLogger instance.

        :param str application_id: The application ID.
        :param str app_display_version: The application display version.
        :param str channel: The channel.
        """
        self._application_id = application_id
        self._app_display_version = app_display_version
        self._channel = channel

    def record(
        self,
        user_agent: str,
        ip_address: str,
        {% for metric_type, metrics in metrics_by_type.items() %}
        {% if metric_type != 'event' %}
        {% for metric in metrics %}
        {{ metric.category }}_{{ metric.name }}: {{ metric.type|py_metric_type }},
        {% endfor %}
        {% endif %}
        {% endfor %}
        events: list[dict[str, Any]]
    ) -> None:
        now = datetime.now(timezone.utc)
        timestamp = now.isoformat()
        for event in events:
            event["timestamp"] = int(1000.0 * now.timestamp())  # Milliseconds since epoch
        event_payload = {
            "metrics": {
                {% for metric_type, metrics in metrics_by_type.items() %}
                {% if metric_type != 'event' %}
                "{{ metric_type }}": {
                    {% for metric in metrics %}
                    "{{ metric.category }}.{{ metric.name }}": {{ metric.category }}_{{ metric.name }},
                    {% endfor %}
                },
                {% endif %}
                {% endfor %}
            },
            "events": events,
            "ping_info": {
                # seq is required in the Glean schema, however is not useful in server context
                "seq": 0,
                "start_time": timestamp,
                "end_time": timestamp,
            },
            # `Unknown` fields below are required in the Glean schema, however they are
            # not useful in server context
            "client_info": {
                "telemetry_sdk_build": "glean_parser v{{ parser_version }}",
                "first_run_date": "Unknown",
                "os": "Unknown",
                "os_version": "Unknown",
                "architecture": "Unknown",
                "app_build": "Unknown",
                "app_display_version": self._app_display_version,
                "app_channel": self._channel,
            },
        }
        event_payload_serialized = json.dumps(event_payload)

        # This is the message structure that Decoder expects:
        # https://github.com/mozilla/gcp-ingestion/pull/2400
        ping = {
            "document_namespace": self._application_id,
            "document_type": "{{ ping }}",
            "document_version": "1",
            "document_id": str(uuid4()),
            "user_agent": user_agent,
            "ip_address": ip_address,
            "payload": event_payload_serialized,
        }


        self.emit_record(now, ping)

    def emit_record(self, now: datetime, ping:dict[str, Any]) -> None:
        """Log the ping to STDOUT.
        Applications might want to override this method to use their own logging.
        If doing so, make sure to log the ping as JSON, and to include the
        `Type: GLEAN_EVENT_MOZLOG_TYPE`."""
        ping_envelope = {
            "Timestamp": now.isoformat(),
            "Logger": "glean",
            "Type": GLEAN_EVENT_MOZLOG_TYPE,
            "Fields": ping,
        }
        ping_envelope_serialized = json.dumps(ping_envelope)

        print(ping_envelope_serialized)

    {% for event in metrics_by_type["event"] %}
    def {{ event|record_event_function_name }}(
        self,
        user_agent: str,
        ip_address: str,
        {% for metric_type, metrics in metrics_by_type.items() %}
        {% if metric_type != 'event' %}
        {% for metric in metrics %}
        {{ metric.category }}_{{ metric.name }}: {{ metric.type|py_metric_type }},
        {% endfor %}
        {% endif %}
        {% endfor %}
        {% for extra, metadata in event.extra_keys.items() %}
        {{ extra }}: {{ metadata.type|py_metric_type }},
        {% endfor %}
    ) -> None:
        """
        Record and submit a {{ event.category }}_{{ event.name }} event:
        {{ event.description|clean_string }}
        Event is logged to STDOUT via `print`.

        :param str user_agent: The user agent.
        :param str ip_address: The IP address. Will be used to decode Geo information
            and scrubbed at ingestion.
        {% for metric_type, metrics in metrics_by_type.items() %}
        {% if metric_type != 'event' %}
        {% for metric in metrics %}
        :param {{ metric.type|py_metric_type }} {{ metric.category }}_{{ metric.name }}: {{ metric.description|clean_string }}
        {% endfor %}
        {% endif %}
        {% endfor %}
        {% if event.extra_keys %}
        {% for extra, metadata in event.extra_keys.items() %}
        :param {{ metadata.type|py_metric_type }} {{ extra }}: {{ metadata.description|clean_string }}
        {% endfor %}
        {% endif %}
        """
        event = {
            "category": "{{ event.category }}",
            "name": "{{ event.name }}",
            {% if event.extra_keys %}
            "extra": {
                {% for extra, metadata in event.extra_keys.items() %}
                "{{ extra }}": str({{ extra }}){% if 'bool' == metadata.type|py_metric_type %}.lower(){% endif %},
                {% endfor %}
            },
            {% endif %}
        }
        self.record(
            user_agent,
            ip_address,
            {% for metric_type, metrics in metrics_by_type.items() %}
            {% if metric_type != 'event' %}
            {% for metric in metrics %}
            {{ metric.category }}_{{ metric.name }},
            {% endfor %}
            {% endif %}
            {% endfor %}
            [event],
        )
    {% endfor %}
{% endfor %}

{% for ping in pings %}
def {{ ping|factory_method }}(
    application_id: str,
    app_display_version: str,
    channel: str,
) -> {{ ping|camelize }}ServerEventLogger:
    """
    Factory function that creates an instance of Glean Server Event Logger to record
    `{{ ping }}` ping events.
    :param str application_id: The application ID.
    :param str app_display_version: The application display version.
    :param str channel: The channel.
    :return: An instance of {{ ping|camelize }}ServerEventLogger.
    :rtype: {{ ping|camelize }}ServerEventLogger
    """
    return {{ ping|camelize }}ServerEventLogger(application_id, app_display_version, channel)
{% endfor %}
