import { CodeBlock } from "../components/CodeBlock";
import { Callout } from "../components/Callout";
import { ApiEndpoint } from "../components/ApiEndpoint";
import { ParamTable } from "../components/ParamTable";

export function ChatCompletionsPage() {
  return (
    <div>
      <h1 id="chat-completions">Chat Completions</h1>
      <p>
        The primary inference endpoint. Fully compatible with the OpenAI Chat Completions API —
        switch your <code>base_url</code> to Veylant IA and all existing SDK calls work unchanged.
      </p>

      <ApiEndpoint
        method="POST"
        path="/v1/chat/completions"
        description="Create an AI chat completion with automatic PII anonymization, routing, and audit logging."
      />

      <Callout type="info" title="OpenAI-compatible">
        This endpoint is a superset of the OpenAI Chat Completions API. All standard OpenAI
        parameters are supported and forwarded to the upstream provider. Veylant IA adds governance
        on top without changing the request/response schema.
      </Callout>

      <h2 id="request">Request Body</h2>
      <ParamTable
        params={[
          { name: "model", type: "string", required: true, description: "Model ID to use (e.g. gpt-4o, claude-3-5-sonnet-20241022). The routing engine may override this." },
          { name: "messages", type: "array", required: true, description: "List of messages in the conversation. Each message has role (system|user|assistant) and content." },
          { name: "stream", type: "boolean", required: false, default: "false", description: "If true, responses are streamed as Server-Sent Events (SSE). Compatible with EventSource and the OpenAI SDK streaming API." },
          { name: "temperature", type: "float", required: false, default: "1.0", description: "Sampling temperature (0–2). Forwarded to the provider." },
          { name: "max_tokens", type: "integer", required: false, description: "Maximum tokens to generate. Forwarded to the provider." },
          { name: "top_p", type: "float", required: false, description: "Nucleus sampling. Forwarded to the provider." },
          { name: "n", type: "integer", required: false, default: "1", description: "Number of completions. Note: PII anonymization applies to each choice." },
        ]}
      />

      <h2 id="example-request">Example Request</h2>
      <CodeBlock
        language="bash"
        code={`curl http://localhost:8090/v1/chat/completions \\
  -H "Authorization: Bearer $TOKEN" \\
  -H "Content-Type: application/json" \\
  -d '{
    "model": "gpt-4o",
    "messages": [
      {
        "role": "system",
        "content": "You are a helpful assistant."
      },
      {
        "role": "user",
        "content": "Summarize the contract for John Smith (john@acme.com)."
      }
    ],
    "temperature": 0.7
  }'`}
      />

      <h2 id="pii-anonymization">PII Anonymization in Action</h2>
      <p>
        Before the request is forwarded to the LLM, the PII service scans all message content.
        Detected entities are anonymized in the prompt. The audit log records what was found.
      </p>
      <CodeBlock
        language="json"
        code={`// Original user message:
"Summarize the contract for John Smith (john@acme.com)."

// After PII anonymization (what the LLM sees):
"Summarize the contract for [PERSON] ([EMAIL_ADDRESS])."

// Audit log records:
{
  "pii_entities": [
    {"type": "PERSON",        "original": "John Smith",    "start": 31, "end": 41},
    {"type": "EMAIL_ADDRESS", "original": "john@acme.com", "start": 43, "end": 56}
  ]
}`}
      />

      <h2 id="response">Response</h2>
      <p>Responses are identical to the OpenAI API format:</p>
      <CodeBlock
        language="json"
        code={`{
  "id": "chatcmpl-veylant-8f3k2j",
  "object": "chat.completion",
  "created": 1735000000,
  "model": "gpt-4o",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Here is a summary of the contract..."
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 28,
    "completion_tokens": 142,
    "total_tokens": 170
  }
}`}
      />

      <h2 id="streaming">Streaming (SSE)</h2>
      <p>
        Set <code>"stream": true</code> to receive chunks via Server-Sent Events. PII
        anonymization applies to the <strong>request</strong> before it's sent upstream — not to
        the streamed response. This keeps streaming latency minimal.
      </p>
      <CodeBlock
        language="bash"
        code={`curl http://localhost:8090/v1/chat/completions \\
  -H "Authorization: Bearer $TOKEN" \\
  -H "Content-Type: application/json" \\
  -d '{
    "model": "gpt-4o",
    "messages": [{"role": "user", "content": "Tell me a story"}],
    "stream": true
  }'

# Response (streaming chunks):
data: {"id":"chatcmpl-...","object":"chat.completion.chunk","choices":[{"delta":{"content":"Once"},"index":0}]}
data: {"id":"chatcmpl-...","object":"chat.completion.chunk","choices":[{"delta":{"content":" upon"},"index":0}]}
data: [DONE]`}
      />

      <CodeBlock
        language="python"
        code={`from openai import OpenAI

client = OpenAI(base_url="http://localhost:8090/v1", api_key="dev-token")

stream = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Tell me a story"}],
    stream=True,
)
for chunk in stream:
    print(chunk.choices[0].delta.content or "", end="", flush=True)`}
      />

      <h2 id="errors">Error Responses</h2>
      <CodeBlock
        language="json"
        code={`// 429 — Rate limit exceeded
{
  "error": {
    "type": "rate_limit_error",
    "message": "rate limit exceeded, retry after 1 second",
    "code": "rate_limit_exceeded"
  }
}
// Headers:
// Retry-After: 1

// 503 — Provider unavailable (circuit breaker open)
{
  "error": {
    "type": "provider_error",
    "message": "all providers unavailable",
    "code": "service_unavailable"
  }
}

// 400 — Bad request
{
  "error": {
    "type": "invalid_request_error",
    "message": "messages field is required",
    "code": "invalid_request"
  }
}`}
      />

      <h2 id="routing-override">How Routing Affects the Model</h2>
      <p>
        The routing engine evaluates rules against the request context. A matched rule can override
        the requested model or select a different provider. The <code>model</code> in the response
        reflects the model actually used (which may differ from what was requested).
      </p>
      <Callout type="tip">
        Use the <code>GET /v1/admin/logs</code> endpoint to see <code>model_requested</code> vs{" "}
        <code>model_used</code> in the audit trail.
      </Callout>
    </div>
  );
}
