# Copyright 2024 Klira AI
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Span processors for the Klira telemetry pipeline."""

from __future__ import annotations

import logging

from opentelemetry.context import Context
from opentelemetry.sdk.trace import ReadableSpan, Span, SpanProcessor

logger = logging.getLogger(__name__)


def _try_set_attribute(span: ReadableSpan, key: str, value: object) -> None:
    """Try to set an attribute on a span, handling the ReadableSpan/Span typing.

    In OTel's pipeline, on_end() receives a ReadableSpan, but the actual
    object is a Span (which has set_attribute). We use getattr to safely
    call it without type errors.
    """
    setter = getattr(span, "set_attribute", None)
    if setter is not None:
        setter(key, value)


class NoneAttributeFilterProcessor(SpanProcessor):
    """Filter out None attribute values before export.

    Protobuf encoding fails on None values. This processor replaces
    None attribute values with empty strings to prevent encoding errors.

    Also sets klira.duration_ms on span end for all klira.* spans.
    """

    def __init__(self, next_processor: SpanProcessor) -> None:
        self._next = next_processor

    def on_start(self, span: Span, parent_context: Context | None = None) -> None:
        self._next.on_start(span, parent_context)

    def on_end(self, span: ReadableSpan) -> None:
        # Set duration_ms for klira spans
        if span.name.startswith("klira.") and span.start_time and span.end_time:
            duration_ms = (span.end_time - span.start_time) / 1_000_000
            _try_set_attribute(span, "klira.duration_ms", duration_ms)
            if span.name.startswith("klira.guardrails."):
                _try_set_attribute(span, "klira.guardrails.latency_ms", duration_ms)

        # Filter None attributes and forward.
        # In practice, None values can be set dynamically despite OTel's
        # type annotations. We check defensively to prevent protobuf errors.
        if span.attributes:
            for key in list(span.attributes.keys()):
                if span.attributes[key] is None:  # type: ignore[comparison-overlap]
                    _try_set_attribute(span, key, "")

        self._next.on_end(span)

    def shutdown(self) -> None:
        self._next.shutdown()

    def force_flush(self, timeout_millis: int = 30000) -> bool:
        return self._next.force_flush(timeout_millis)
