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

export function AdminLogsPage() {
  return (
    <div>
      <h1 id="admin-logs">Admin — Audit Logs & Costs</h1>
      <p>
        Query the immutable audit trail and cost breakdown for all AI requests. Data is stored in
        ClickHouse (append-only — no DELETE operations). In development without ClickHouse, an
        in-memory fallback is used (data is lost on restart).
      </p>

      <h2 id="audit-logs">Audit Logs</h2>
      <ApiEndpoint
        method="GET"
        path="/v1/admin/logs"
        description="Query audit log entries with optional filters. Returns paginated results."
      />

      <ParamTable
        title="Query Parameters"
        params={[
          { name: "provider", type: "string", required: false, description: "Filter by provider: openai | anthropic | azure | mistral | ollama" },
          { name: "min_sensitivity", type: "string", required: false, description: "Minimum PII sensitivity level: none | low | medium | high | critical" },
          { name: "start", type: "string (RFC3339 or RFC3339Nano)", required: false, description: "Start of time range. Accepts JavaScript toISOString() format (e.g. 2026-03-01T00:00:00.000Z) or standard RFC3339." },
          { name: "end", type: "string (RFC3339 or RFC3339Nano)", required: false, description: "End of time range. Same format as start." },
          { name: "limit", type: "integer", required: false, default: "50", description: "Max entries to return (max 10 000)." },
          { name: "offset", type: "integer", required: false, default: "0", description: "Pagination offset." },
        ]}
      />

      <CodeBlock
        language="bash"
        code={`# All logs for the authenticated tenant (default: last 50)
curl "http://localhost:8090/v1/admin/logs" \\
  -H "Authorization: Bearer $TOKEN"

# Filter by provider and sensitivity
curl "http://localhost:8090/v1/admin/logs?provider=anthropic&min_sensitivity=medium" \\
  -H "Authorization: Bearer $TOKEN"

# Date range — RFC3339 (API clients)
curl "http://localhost:8090/v1/admin/logs?start=2026-03-01T00:00:00Z&end=2026-03-31T23:59:59Z&limit=100" \\
  -H "Authorization: Bearer $TOKEN"

# Date range — RFC3339Nano (JavaScript frontend)
curl "http://localhost:8090/v1/admin/logs?start=2026-03-01T00:00:00.000Z&end=2026-03-31T23:59:59.999Z" \\
  -H "Authorization: Bearer $TOKEN"`}
      />

      <CodeBlock
        language="json"
        code={`// 200 — Success
{
  "data": [
    {
      "request_id": "req_01HV...",
      "tenant_id": "dev-tenant",
      "user_id": "a1b2c3d4-0000-0000-0000-000000000001",
      "timestamp": "2026-03-10T14:32:11Z",
      "provider": "anthropic",
      "model_requested": "gpt-4o",
      "model_used": "claude-3-5-sonnet-20241022",
      "department": "Legal",
      "user_role": "user",
      "sensitivity_level": "high",
      "token_input": 128,
      "token_output": 345,
      "token_total": 473,
      "cost_usd": 0.003412,
      "latency_ms": 1423,
      "status": "ok",
      "error_type": "",
      "pii_entity_count": 3,
      "stream": false,
      "prompt_hash": "sha256:a3f...",
      "response_hash": "sha256:b7c..."
    }
  ],
  "total": 142
}`}
      />

      <Callout type="info" title="Audit-of-the-audit">
        All accesses to audit logs are themselves logged. This satisfies the meta-logging
        requirement for data protection authorities.
      </Callout>

      <Callout type="warning" title="prompt_anonymized is never returned">
        The <code>prompt_anonymized</code> field (AES-256-GCM encrypted) is stored in ClickHouse
        but is excluded from all API responses. Use the CSV export or GDPR access endpoint for
        compliance data requests.
      </Callout>

      <h3 id="audit-entry-fields">Audit Entry Fields</h3>
      <div className="overflow-x-auto my-4">
        <table className="w-full text-sm border rounded-lg overflow-hidden">
          <thead>
            <tr className="bg-muted/50 border-b">
              <th className="text-left px-4 py-2.5 font-semibold">Field</th>
              <th className="text-left px-4 py-2.5 font-semibold">Type</th>
              <th className="text-left px-4 py-2.5 font-semibold">Description</th>
            </tr>
          </thead>
          <tbody>
            {[
              { field: "request_id", type: "string", desc: "Unique request identifier (X-Request-ID header)." },
              { field: "tenant_id", type: "string", desc: "Tenant UUID — always scoped to the authenticated tenant." },
              { field: "user_id", type: "string", desc: "User UUID from the JWT sub claim." },
              { field: "timestamp", type: "RFC3339", desc: "UTC timestamp when the request was processed." },
              { field: "provider", type: "string", desc: "LLM provider that served the request: openai | anthropic | azure | mistral | ollama" },
              { field: "model_requested", type: "string", desc: "Model requested by the client (may differ from model_used after routing)." },
              { field: "model_used", type: "string", desc: "Actual model used after routing rule evaluation." },
              { field: "department", type: "string", desc: "User department from JWT claims (used in routing conditions)." },
              { field: "user_role", type: "string", desc: "RBAC role: admin | manager | user | auditor" },
              { field: "sensitivity_level", type: "string", desc: "Highest PII sensitivity detected: none | low | medium | high | critical" },
              { field: "token_input", type: "integer", desc: "Prompt tokens consumed." },
              { field: "token_output", type: "integer", desc: "Completion tokens generated." },
              { field: "token_total", type: "integer", desc: "token_input + token_output." },
              { field: "cost_usd", type: "float", desc: "Estimated cost in USD (per-provider pricing table)." },
              { field: "latency_ms", type: "integer", desc: "End-to-end latency in milliseconds (proxy entry → last byte)." },
              { field: "status", type: "string", desc: "\"ok\" or \"error\"." },
              { field: "error_type", type: "string", desc: "Error category if status=error (empty otherwise)." },
              { field: "pii_entity_count", type: "integer", desc: "Number of PII entities detected in the prompt." },
              { field: "stream", type: "boolean", desc: "Whether the request used Server-Sent Events streaming." },
              { field: "prompt_hash", type: "string", desc: "SHA-256 of the original prompt (for deduplication/integrity)." },
              { field: "response_hash", type: "string", desc: "SHA-256 of the response content." },
            ].map((row) => (
              <tr key={row.field} className="border-b last:border-0">
                <td className="px-4 py-2.5 font-mono text-xs">{row.field}</td>
                <td className="px-4 py-2.5 text-muted-foreground text-xs">{row.type}</td>
                <td className="px-4 py-2.5 text-muted-foreground text-xs">{row.desc}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <h2 id="costs">Cost Breakdown</h2>
      <ApiEndpoint
        method="GET"
        path="/v1/admin/costs"
        description="Aggregate token consumption and cost, grouped by provider, model, or department."
      />

      <ParamTable
        title="Query Parameters"
        params={[
          { name: "group_by", type: "string", required: false, default: "provider", description: "Grouping dimension: provider | model | department" },
          { name: "start", type: "string (RFC3339)", required: false, description: "Start of billing period." },
          { name: "end", type: "string (RFC3339)", required: false, description: "End of billing period." },
        ]}
      />

      <CodeBlock
        language="bash"
        code={`# Costs by provider for March 2026
curl "http://localhost:8090/v1/admin/costs?group_by=provider&start=2026-03-01T00:00:00Z&end=2026-03-31T23:59:59Z" \\
  -H "Authorization: Bearer $TOKEN"

# Costs by department (for chargeback)
curl "http://localhost:8090/v1/admin/costs?group_by=department" \\
  -H "Authorization: Bearer $TOKEN"

# Costs by model
curl "http://localhost:8090/v1/admin/costs?group_by=model&start=2026-03-01T00:00:00Z" \\
  -H "Authorization: Bearer $TOKEN"`}
      />

      <CodeBlock
        language="json"
        code={`// 200 — Costs grouped by provider
{
  "data": [
    {
      "key": "openai",
      "total_tokens": 2840000,
      "total_cost_usd": 28.40,
      "request_count": 1423
    },
    {
      "key": "anthropic",
      "total_tokens": 462000,
      "total_cost_usd": 6.93,
      "request_count": 231
    },
    {
      "key": "mistral",
      "total_tokens": 180000,
      "total_cost_usd": 0.54,
      "request_count": 89
    }
  ]
}

// 200 — Costs grouped by department
{
  "data": [
    { "key": "Legal",     "total_tokens": 1200000, "total_cost_usd": 18.00, "request_count": 650 },
    { "key": "Finance",   "total_tokens": 900000,  "total_cost_usd": 9.00,  "request_count": 410 },
    { "key": "IT",        "total_tokens": 540000,  "total_cost_usd": 8.10,  "request_count": 280 }
  ]
}`}
      />

      <h2 id="csv-export">CSV Export</h2>
      <ApiEndpoint
        method="GET"
        path="/v1/admin/compliance/export/logs"
        description="Export audit logs as a CSV file (up to 10 000 rows). For bulk compliance downloads or GDPR documentation."
      />

      <ParamTable
        title="Query Parameters"
        params={[
          { name: "provider", type: "string", required: false, description: "Filter by provider." },
          { name: "start", type: "string (RFC3339 or YYYY-MM-DD)", required: false, description: "Start date. Accepts RFC3339 or date-only format (e.g. 2026-03-01)." },
          { name: "end", type: "string (RFC3339 or YYYY-MM-DD)", required: false, description: "End date. When date-only, the full day (23:59:59) is included automatically." },
        ]}
      />

      <CodeBlock
        language="bash"
        code={`# Export all logs as CSV
curl "http://localhost:8090/v1/admin/compliance/export/logs" \\
  -H "Authorization: Bearer $TOKEN" \\
  --output audit_logs.csv

# Export for a specific date range using simple date format
curl "http://localhost:8090/v1/admin/compliance/export/logs?start=2026-03-01&end=2026-03-31" \\
  -H "Authorization: Bearer $TOKEN" \\
  --output march_2026_logs.csv

# Export only high-sensitivity entries from OpenAI
curl "http://localhost:8090/v1/admin/compliance/export/logs?provider=openai" \\
  -H "Authorization: Bearer $TOKEN" \\
  --output openai_logs.csv`}
      />

      <CodeBlock
        language="text"
        code={`# CSV columns (header row):
request_id,timestamp,user_id,tenant_id,provider,model_requested,model_used,department,user_role,sensitivity_level,token_input,token_output,token_total,cost_usd,latency_ms,status,error_type,pii_entity_count,stream

# Example rows:
req_01HV...,2026-03-10T14:32:11Z,a1b2c3d4-...,dev-tenant,anthropic,gpt-4o,claude-3-5-sonnet-20241022,Legal,user,high,128,345,473,0.003412,1423,ok,,3,false
req_01HW...,2026-03-10T15:01:44Z,b2c3d4e5-...,dev-tenant,openai,gpt-4o-mini,gpt-4o-mini,Finance,user,none,64,120,184,0.000074,342,ok,,0,false`}
      />

      <h2 id="rate-limits">Rate Limit Configuration</h2>
      <p>
        Per-tenant rate limits override the global defaults configured in{" "}
        <code>rate_limit.default_tenant_rpm</code>.
      </p>
      <ApiEndpoint method="GET" path="/v1/admin/rate-limits" description="List all per-tenant rate limit overrides." />
      <ApiEndpoint method="GET" path="/v1/admin/rate-limits/{tenant_id}" description="Get rate limit configuration for a specific tenant (returns default if no override exists)." />
      <ApiEndpoint method="PUT" path="/v1/admin/rate-limits/{tenant_id}" description="Create or update a per-tenant rate limit. Applied immediately — no restart required." />
      <ApiEndpoint method="DELETE" path="/v1/admin/rate-limits/{tenant_id}" description="Remove the per-tenant override. The tenant reverts to global defaults." />

      <CodeBlock
        language="bash"
        code={`# Set a rate limit override for a tenant
curl -X PUT http://localhost:8090/v1/admin/rate-limits/acme-corp-tenant-id \\
  -H "Authorization: Bearer $TOKEN" \\
  -H "Content-Type: application/json" \\
  -d '{
    "requests_per_min": 500,
    "burst_size": 50,
    "user_rpm": 60,
    "user_burst": 10,
    "is_enabled": true
  }'

# Get current config (returns default if no override)
curl http://localhost:8090/v1/admin/rate-limits/acme-corp-tenant-id \\
  -H "Authorization: Bearer $TOKEN"

# Remove override (reverts to global defaults)
curl -X DELETE http://localhost:8090/v1/admin/rate-limits/acme-corp-tenant-id \\
  -H "Authorization: Bearer $TOKEN"`}
      />

      <CodeBlock
        language="json"
        code={`// PUT/GET response:
{
  "tenant_id": "acme-corp-tenant-id",
  "requests_per_min": 500,
  "burst_size": 50,
  "user_rpm": 60,
  "user_burst": 10,
  "is_enabled": true
}

// 429 response when rate limit is exceeded:
{
  "error": {
    "type": "rate_limit_error",
    "message": "rate limit exceeded",
    "code": "rate_limit_exceeded"
  }
}
// The response also includes: Retry-After: 1`}
      />
    </div>
  );
}
