import type { Metadata } from "next";
import { CodeBlock } from "@/components/code-block";

export const metadata: Metadata = {
  title: "OpenAI Integration",
  description:
    "Auto-trace all OpenAI API calls with a single wrapper. Captures model, tokens, cost, and latency.",
};

export default function OpenAIIntegrationPage() {
  return (
    <div>
      <h1 className="text-4xl font-bold tracking-tight mb-4">
        OpenAI Integration
      </h1>
      <p className="text-lg text-neutral-400 mb-10 leading-relaxed">
        Wrap the OpenAI client once and every API call is automatically traced.
        AgentLens captures the model name, token usage, cost, latency, input
        messages, and output completions.
      </p>

      <section className="mb-12">
        <h2 className="text-2xl font-semibold mb-4">Installation</h2>
        <CodeBlock title="terminal" language="bash">{`pip install vectry-agentlens openai`}</CodeBlock>
      </section>

      <section className="mb-12">
        <h2 className="text-2xl font-semibold mb-4">Quick setup</h2>
        <CodeBlock title="main.py" language="python">{`import agentlens
from agentlens.integrations.openai import wrap_openai
import openai

agentlens.init(
    api_key="your-api-key",
    endpoint="https://agentlens.vectry.tech",
)

client = wrap_openai(openai.OpenAI())

# All calls are now auto-traced
response = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Explain quantum computing in one paragraph."},
    ],
)`}</CodeBlock>
      </section>

      <section className="mb-12">
        <h2 className="text-2xl font-semibold mb-4">What gets captured</h2>
        <p className="text-neutral-400 leading-relaxed mb-4">
          Each OpenAI API call creates an LLM_CALL span with the following data:
        </p>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-neutral-800">
                <th className="text-left py-2 pr-4 text-neutral-400 font-medium">Field</th>
                <th className="text-left py-2 text-neutral-400 font-medium">Description</th>
              </tr>
            </thead>
            <tbody className="text-neutral-300">
              <tr className="border-b border-neutral-800/50">
                <td className="py-2 pr-4 font-mono text-emerald-400 text-xs">input.model</td>
                <td className="py-2">Model name (gpt-4o, gpt-4o-mini, etc.)</td>
              </tr>
              <tr className="border-b border-neutral-800/50">
                <td className="py-2 pr-4 font-mono text-emerald-400 text-xs">input.messages</td>
                <td className="py-2">Full message array sent to the API</td>
              </tr>
              <tr className="border-b border-neutral-800/50">
                <td className="py-2 pr-4 font-mono text-emerald-400 text-xs">output.content</td>
                <td className="py-2">Response content from the model</td>
              </tr>
              <tr className="border-b border-neutral-800/50">
                <td className="py-2 pr-4 font-mono text-emerald-400 text-xs">tokenCount</td>
                <td className="py-2">Total tokens (prompt + completion)</td>
              </tr>
              <tr className="border-b border-neutral-800/50">
                <td className="py-2 pr-4 font-mono text-emerald-400 text-xs">costUsd</td>
                <td className="py-2">Estimated cost based on model pricing</td>
              </tr>
              <tr className="border-b border-neutral-800/50">
                <td className="py-2 pr-4 font-mono text-emerald-400 text-xs">durationMs</td>
                <td className="py-2">Wall-clock time for the request</td>
              </tr>
              <tr>
                <td className="py-2 pr-4 font-mono text-emerald-400 text-xs">metadata.finish_reason</td>
                <td className="py-2">How the model stopped (stop, length, tool_calls)</td>
              </tr>
            </tbody>
          </table>
        </div>
      </section>

      <section className="mb-12">
        <h2 className="text-2xl font-semibold mb-4">Async client</h2>
        <p className="text-neutral-400 leading-relaxed mb-4">
          The wrapper works with both sync and async OpenAI clients:
        </p>
        <CodeBlock title="async_example.py" language="python">{`from agentlens.integrations.openai import wrap_openai
import openai

async_client = wrap_openai(openai.AsyncOpenAI())

response = await async_client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Hello!"}],
)`}</CodeBlock>
      </section>

      <section className="mb-12">
        <h2 className="text-2xl font-semibold mb-4">
          Combining with @trace
        </h2>
        <p className="text-neutral-400 leading-relaxed mb-4">
          When used inside a <code className="text-emerald-400 font-mono text-xs bg-emerald-500/5 px-1.5 py-0.5 rounded">@trace</code>-decorated
          function, OpenAI calls appear as child spans of the trace:
        </p>
        <CodeBlock title="combined.py" language="python">{`import agentlens
from agentlens import trace
from agentlens.integrations.openai import wrap_openai
import openai

agentlens.init(api_key="...", endpoint="...")
client = wrap_openai(openai.OpenAI())

@trace(name="research-agent")
async def research(topic: str) -> str:
    # This LLM call becomes a child span of "research-agent"
    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[
            {"role": "system", "content": "Summarize the following topic."},
            {"role": "user", "content": topic},
        ],
    )
    return response.choices[0].message.content`}</CodeBlock>
      </section>

      <section className="mb-12">
        <h2 className="text-2xl font-semibold mb-4">Tool calls</h2>
        <p className="text-neutral-400 leading-relaxed mb-4">
          When the model invokes tools (function calling), AgentLens
          automatically captures each tool call as a TOOL_SELECTION decision
          point and the tool execution as a TOOL_CALL span:
        </p>
        <CodeBlock title="tools.py" language="python">{`@trace(name="tool-agent")
async def agent_with_tools(prompt: str):
    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[{"role": "user", "content": prompt}],
        tools=[{
            "type": "function",
            "function": {
                "name": "get_weather",
                "description": "Get weather for a city",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "city": {"type": "string"}
                    },
                },
            },
        }],
    )
    # AgentLens captures the tool selection decision automatically
    return response`}</CodeBlock>
      </section>

      <section>
        <h2 className="text-2xl font-semibold mb-4">Supported API methods</h2>
        <ul className="text-sm text-neutral-400 space-y-2 ml-1">
          <li>
            <code className="font-mono text-emerald-400 text-xs">chat.completions.create()</code> — Chat completions (including streaming)
          </li>
          <li>
            <code className="font-mono text-emerald-400 text-xs">completions.create()</code> — Legacy completions
          </li>
          <li>
            <code className="font-mono text-emerald-400 text-xs">embeddings.create()</code> — Embedding generation
          </li>
        </ul>
      </section>
    </div>
  );
}
