"""Agno agent with LangSmith + Brizz SDK observability.

Traces flow to both LangSmith and Brizz: the LangSmith OTLP exporter is set up
first, then Brizz.initialize() detects the existing TracerProvider and adds its
own BrizzSpanProcessor (with masking + session context) to it.

Requirements:
- pip install agno openai openinference-instrumentation-agno opentelemetry-sdk opentelemetry-exporter-otlp brizz
- Set environment variables: LANGSMITH_API_KEY, LANGSMITH_PROJECT, OPENAI_API_KEY
"""
import os
import uuid

from agno.agent import Agent
from agno.models.openai import OpenAIChat
from agno.tools.duckduckgo import DuckDuckGoTools
from dotenv import load_dotenv
from openinference.instrumentation.agno import AgnoInstrumentor
from opentelemetry import trace as trace_api
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor

from brizz import Brizz, start_session

load_dotenv()


# 1. Set up LangSmith TracerProvider
tracer_provider = TracerProvider()
tracer_provider.add_span_processor(
    SimpleSpanProcessor(
        OTLPSpanExporter(
            endpoint="https://api.smith.langchain.com/otel/v1/traces",
            headers={
                "x-api-key": os.getenv("LANGSMITH_API_KEY", ""),
                "Langsmith-Project": os.getenv("LANGSMITH_PROJECT", ""),
            },
        )
    )
)
trace_api.set_tracer_provider(tracer_provider)

# 2. Initialize Brizz — detects existing TracerProvider, adds its span processor
Brizz.initialize(
    disable_batch=True,
    app_name="agno-example",
)

# 3. Instrument Agno — all agent spans now go to both LangSmith and Brizz
AgnoInstrumentor().instrument()

# 4. Create agent
agent = Agent(
    name="Web Search Agent",
    model=OpenAIChat(id="gpt-4o-mini"),
    tools=[DuckDuckGoTools()],
    instructions=["Always include sources in your answers."],
    markdown=True,
)

if __name__ == "__main__":
    session_id = uuid.uuid4().hex
    query = "What are the latest developments in AI agents?"

    with start_session(session_id):
        response = agent.run(query)
        output = response.content if response and response.content else "No response"
        print(f"Agent Response: {output}")
