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

export const metadata: Metadata = {
  title: "TypeScript SDK",
  description:
    "Full reference for the AgentLens TypeScript SDK: init(), TraceBuilder, createDecision(), and shutdown().",
};

function ApiSection({
  name,
  signature,
  description,
  children,
}: {
  name: string;
  signature: string;
  description: string;
  children?: React.ReactNode;
}) {
  return (
    <div className="mb-10 pb-10 border-b border-neutral-800/50 last:border-0">
      <h3 className="text-xl font-semibold mb-1">{name}</h3>
      <div className="px-3 py-1.5 rounded-lg bg-neutral-900/50 border border-neutral-800/50 inline-block mb-3">
        <code className="text-sm font-mono text-emerald-400">{signature}</code>
      </div>
      <p className="text-neutral-400 leading-relaxed mb-4">{description}</p>
      {children}
    </div>
  );
}

export default function TypeScriptSdkPage() {
  return (
    <div>
      <h1 className="text-4xl font-bold tracking-tight mb-4">
        TypeScript SDK
      </h1>
      <p className="text-lg text-neutral-400 mb-4 leading-relaxed">
        The AgentLens TypeScript SDK provides a builder-based API for
        constructing and sending traces from Node.js and edge runtimes.
      </p>

      <div className="px-4 py-3 rounded-lg bg-neutral-900/50 border border-neutral-800/50 mb-10">
        <code className="text-sm font-mono text-emerald-400">
          npm install agentlens-sdk
        </code>
      </div>

      <h2 className="text-2xl font-semibold mb-6">API Reference</h2>

      <ApiSection
        name="init()"
        signature='init({ apiKey, endpoint, flushInterval?, maxBatchSize?, enabled? })'
        description="Initialize the SDK. Must be called once before creating any traces. Your API key can be created after registering at agentlens.vectry.tech — go to Dashboard > API Keys to generate one."
      >
        <h4 className="text-sm font-medium text-neutral-300 mb-2">
          Options
        </h4>
        <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">Property</th>
                <th className="text-left py-2 pr-4 text-neutral-400 font-medium">Type</th>
                <th className="text-left py-2 pr-4 text-neutral-400 font-medium">Default</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">apiKey</td>
                <td className="py-2 pr-4 text-neutral-500">string</td>
                <td className="py-2 pr-4 text-neutral-500">required</td>
                <td className="py-2">Your AgentLens API key (from <a href="/dashboard/keys" className="text-emerald-400 hover:underline">Dashboard &rarr; API Keys</a>)</td>
              </tr>
              <tr className="border-b border-neutral-800/50">
                <td className="py-2 pr-4 font-mono text-emerald-400 text-xs">endpoint</td>
                <td className="py-2 pr-4 text-neutral-500">string</td>
                <td className="py-2 pr-4 text-neutral-500">required</td>
                <td className="py-2">AgentLens server URL</td>
              </tr>
              <tr className="border-b border-neutral-800/50">
                <td className="py-2 pr-4 font-mono text-emerald-400 text-xs">flushInterval</td>
                <td className="py-2 pr-4 text-neutral-500">number</td>
                <td className="py-2 pr-4 text-neutral-500">5000</td>
                <td className="py-2">Milliseconds between flushes</td>
              </tr>
              <tr className="border-b border-neutral-800/50">
                <td className="py-2 pr-4 font-mono text-emerald-400 text-xs">maxBatchSize</td>
                <td className="py-2 pr-4 text-neutral-500">number</td>
                <td className="py-2 pr-4 text-neutral-500">100</td>
                <td className="py-2">Max traces per batch</td>
              </tr>
              <tr>
                <td className="py-2 pr-4 font-mono text-emerald-400 text-xs">enabled</td>
                <td className="py-2 pr-4 text-neutral-500">boolean</td>
                <td className="py-2 pr-4 text-neutral-500">true</td>
                <td className="py-2">Toggle tracing on/off</td>
              </tr>
            </tbody>
          </table>
        </div>
        <CodeBlock title="init.ts" language="typescript">{`import { init } from "agentlens-sdk";

init({
  apiKey: process.env.AGENTLENS_API_KEY!,
  endpoint: "https://agentlens.vectry.tech",
  flushInterval: 10000,
});`}</CodeBlock>
      </ApiSection>

      <ApiSection
        name="TraceBuilder"
        signature='new TraceBuilder(name, options?)'
        description="Builder for constructing a trace incrementally. Add spans, decision points, and events, then call end() to finalize and send."
      >
        <h4 className="text-sm font-medium text-neutral-300 mb-2">
          Constructor options
        </h4>
        <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">Property</th>
                <th className="text-left py-2 pr-4 text-neutral-400 font-medium">Type</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">tags</td>
                <td className="py-2 pr-4 text-neutral-500">string[]</td>
                <td className="py-2">Tags for this trace</td>
              </tr>
              <tr className="border-b border-neutral-800/50">
                <td className="py-2 pr-4 font-mono text-emerald-400 text-xs">sessionId</td>
                <td className="py-2 pr-4 text-neutral-500">string</td>
                <td className="py-2">Group traces into a session</td>
              </tr>
              <tr>
                <td className="py-2 pr-4 font-mono text-emerald-400 text-xs">metadata</td>
                <td className="py-2 pr-4 text-neutral-500">Record&lt;string, unknown&gt;</td>
                <td className="py-2">Arbitrary metadata</td>
              </tr>
            </tbody>
          </table>
        </div>

        <h4 className="text-sm font-medium text-neutral-300 mb-2 mt-6">
          Methods
        </h4>

        <div className="space-y-4 mb-6">
          <div className="p-3 rounded-lg border border-neutral-800/50 bg-neutral-900/30">
            <code className="text-sm font-mono text-emerald-400">
              addSpan(span: SpanInput): string
            </code>
            <p className="text-xs text-neutral-500 mt-1">
              Add a span to the trace. Returns the generated span ID. Pass <code className="text-emerald-400/80 font-mono bg-emerald-500/5 px-1 rounded">parentSpanId</code> to nest spans.
            </p>
          </div>
          <div className="p-3 rounded-lg border border-neutral-800/50 bg-neutral-900/30">
            <code className="text-sm font-mono text-emerald-400">
              addDecision(decision: DecisionInput): string
            </code>
            <p className="text-xs text-neutral-500 mt-1">
              Add a decision point. Returns the generated decision ID.
            </p>
          </div>
          <div className="p-3 rounded-lg border border-neutral-800/50 bg-neutral-900/30">
            <code className="text-sm font-mono text-emerald-400">
              addEvent(event: EventInput): string
            </code>
            <p className="text-xs text-neutral-500 mt-1">
              Add an event to the trace. Returns the generated event ID.
            </p>
          </div>
          <div className="p-3 rounded-lg border border-neutral-800/50 bg-neutral-900/30">
            <code className="text-sm font-mono text-emerald-400">
              end(status?: &quot;COMPLETED&quot; | &quot;ERROR&quot;): Promise&lt;void&gt;
            </code>
            <p className="text-xs text-neutral-500 mt-1">
              Finalize and send the trace. Defaults to COMPLETED.
            </p>
          </div>
        </div>

        <CodeBlock title="trace-builder.ts" language="typescript">{`import { TraceBuilder } from "agentlens-sdk";

const trace = new TraceBuilder("customer-support", {
  tags: ["support", "v2"],
  sessionId: "session-abc",
});

const agentSpan = trace.addSpan({
  name: "classify-intent",
  type: "LLM_CALL",
  input: { messages: [{ role: "user", content: "I need a refund" }] },
  output: { intent: "refund", confidence: 0.95 },
  status: "COMPLETED",
  tokenCount: 150,
  costUsd: 0.002,
  durationMs: 340,
});

trace.addDecision({
  type: "ROUTING",
  chosen: { handler: "refund-flow" },
  alternatives: [{ handler: "faq-flow" }, { handler: "escalate" }],
  reasoning: "High confidence refund intent",
  parentSpanId: agentSpan,
});

trace.addSpan({
  name: "process-refund",
  type: "TOOL_CALL",
  input: { orderId: "ord-123" },
  output: { success: true },
  status: "COMPLETED",
  parentSpanId: agentSpan,
});

await trace.end();`}</CodeBlock>
      </ApiSection>

      <ApiSection
        name="createDecision()"
        signature='createDecision(type, chosen, alternatives, options?)'
        description="Standalone helper to create a decision point outside of a TraceBuilder. Useful when building traces from raw data."
      >
        <CodeBlock title="standalone.ts" language="typescript">{`import { createDecision } from "agentlens-sdk";

const decision = createDecision(
  "TOOL_SELECTION",
  { tool: "calculator", confidence: 0.88 },
  [
    { tool: "web_search", confidence: 0.52 },
    { tool: "code_exec", confidence: 0.34 },
  ],
  { reasoning: "Math expression detected in input" }
);`}</CodeBlock>
      </ApiSection>

      <ApiSection
        name="shutdown()"
        signature="shutdown(timeout?: number): Promise<void>"
        description="Flush all pending traces and tear down the background sender. Default timeout is 10 seconds."
      >
        <CodeBlock title="shutdown.ts" language="typescript">{`import { shutdown } from "agentlens-sdk";

process.on("SIGTERM", async () => {
  await shutdown(30000);
  process.exit(0);
});`}</CodeBlock>
      </ApiSection>

      <section className="mt-12">
        <h2 className="text-2xl font-semibold mb-4">Environment Variables</h2>
        <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">Variable</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">AGENTLENS_API_KEY</td>
                <td className="py-2">API key (overrides init param)</td>
              </tr>
              <tr className="border-b border-neutral-800/50">
                <td className="py-2 pr-4 font-mono text-emerald-400 text-xs">AGENTLENS_ENDPOINT</td>
                <td className="py-2">Server URL (overrides init param)</td>
              </tr>
              <tr>
                <td className="py-2 pr-4 font-mono text-emerald-400 text-xs">AGENTLENS_ENABLED</td>
                <td className="py-2">Set to &quot;false&quot; to disable</td>
              </tr>
            </tbody>
          </table>
        </div>
      </section>
    </div>
  );
}
