# 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.

"""FilteringSpanExporter — suppress noisy framework spans."""

from __future__ import annotations

import logging
from typing import Sequence

from opentelemetry.sdk.trace import ReadableSpan
from opentelemetry.sdk.trace.export import SpanExporter, SpanExportResult

logger = logging.getLogger(__name__)

# Span name prefixes to suppress (noisy framework spans)
_SUPPRESSED_PREFIXES: tuple[str, ...] = (
    "openai.",
    "langchain.",
    "langsmith.",
    "crewai.",
    "llamaindex.",
    "litellm.",
    "anthropic.",
    "google.",
    "ollama.",
    "agents_sdk.",
)


class FilteringSpanExporter(SpanExporter):
    """Wraps an exporter and filters out noisy framework spans.

    Only klira.* spans are exported. All framework-generated spans
    are suppressed to prevent duplicate telemetry. (Learning #13)
    """

    def __init__(self, inner: SpanExporter) -> None:
        self._inner = inner

    def export(self, spans: Sequence[ReadableSpan]) -> SpanExportResult:
        filtered = [span for span in spans if span.name.startswith("klira.")]
        if not filtered:
            return SpanExportResult.SUCCESS
        return self._inner.export(filtered)

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

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