> ## Documentation Index
> Fetch the complete documentation index at: https://docs.litigationlabs.io/llms.txt
> Use this file to discover all available pages before exploring further.

# API Reference

> Comprehensive documentation for all API routes, library functions, components, and type definitions.

## API Routes

### Authentication API

#### `GET/POST /api/auth/[...nextauth]`

NextAuth.js authentication handler supporting multiple providers.

**Supported Providers:** Email (Magic Links), Google OAuth, Apple Sign In, Lit Gator (Development/Preview mode).

**Usage:**

```typescript theme={null}
import { signIn, signOut } from "next-auth/react";

await signIn("google", { callbackUrl: "/dashboard" });
await signIn("email", { email: "user@example.com", redirect: false });
await signOut({ callbackUrl: "/" });
```

### Scenarios API

#### `GET /api/scenarios`

Retrieves all available trial scenarios.

**Response:**

```typescript theme={null}
{ scenarios: Scenario[] }
```

**Status Codes:** `200` Success, `500` Server error.

### Sessions API

#### `GET /api/sessions`

Retrieves courtroom session(s) based on query parameters.

**Query Parameters:**

* `sessionId` (string, optional) -- Specific session ID
* `scenarioId` (string, optional) -- User's session for a scenario
* `recent` (boolean, optional) -- Get user's recent sessions

#### `POST /api/sessions`

Creates a new courtroom session.

**Request Body:**

```typescript theme={null}
{ scenarioId: string }
```

### Courtroom Turn API

#### `POST /api/courtroom/turn`

Processes a player's turn in the courtroom simulation.

**Request Body:**

```typescript theme={null}
{
  sessionId: string;
  userUtterance: string;
}
```

**Response:**

```typescript theme={null}
{
  events: CourtEvent[];
  session: CourtroomSession;
}
```

**Process Flow:**

1. Player submits a question (`userUtterance`)
2. Opposing Counsel evaluates for objections
3. If objection raised, Judge rules (sustain/overrule)
4. If sustained, question is blocked; if overruled, witness answers
5. Witness agent generates response based on scenario data
6. Score is calculated based on key facts elicited
7. Updated session and events are returned

## Library Functions

### `callAgentThroughGateway` (`lib/courtroom/gateway.ts`)

Calls an AI agent through the Vercel AI Gateway.

```typescript theme={null}
async function callAgentThroughGateway({
  agentId: string;
  systemPrompt: string;
  messages: Array<{ role: "user" | "assistant" | "system"; content: string }>;
  model?: string;
}): Promise<string>
```

### `handleTurn` (`lib/courtroom/orchestrator.ts`)

Orchestrates a complete turn in the courtroom simulation.

```typescript theme={null}
async function handleTurn({
  session: CourtroomSession;
  scenario: Scenario;
  userUtterance: string;
}): Promise<{ events: CourtEvent[]; updatedSession: CourtroomSession }>
```

### Prompt Builders (`lib/courtroom/prompts.ts`)

* `buildOCSystemPrompt(scenario, session)` -- System prompt for Opposing Counsel agent.
* `buildJudgeSystemPrompt(scenario, session)` -- System prompt for Judge agent.
* `buildWitnessSystemPrompt(scenario, witness, session)` -- System prompt for Witness agent.

### Scoring (`lib/courtroom/scoring.ts`)

```typescript theme={null}
function computeScoreDeltaFromAnswer(
  scenario: Scenario,
  witness: WitnessProfile | undefined,
  answer: string | undefined
): ScoreState
```

### Payload Functions (`lib/payload.ts`)

* `listScenarios()` -- Retrieves all available scenarios.
* `getScenarioById(id)` -- Retrieves a specific scenario by ID or slug.
* `createSession({ scenarioId, userId })` -- Creates a new courtroom session.
* `getSessionById(id)` -- Retrieves a session by its sessionId.
* `getUserSessionForScenario({ userId, scenarioId })` -- Gets the most recent session for a user + scenario combination.
* `getUserRecentSessions({ userId, limit })` -- Gets recent sessions for a user.
* `saveSession(session)` -- Saves/updates a courtroom session.

## Core Types

### `CourtroomSession`

```typescript theme={null}
interface CourtroomSession {
  id: string;
  sessionId: string;
  scenarioId: string;
  userId?: string | null;
  phase: Phase;
  currentWitnessId: string | null;
  currentSide: "plaintiff" | "defendant";
  turn: RoleTurn;
  transcript: CourtEvent[];
  score: ScoreState;
  metrics?: {
    questionsAsked?: number;
    objectionsRaised?: number;
    objectionsSustained?: number;
    lagMs?: number;
  };
  createdAt?: string;
  updatedAt?: string;
}
```

### `Scenario`

```typescript theme={null}
interface Scenario {
  id: string;
  slug: string;
  title: string;
  description?: string;
  difficulty?: "intro" | "intermediate" | "advanced";
  estimatedMinutes?: number;
  forAgents: ScenarioForAgents;
  metadata?: Record<string, unknown>;
  competencies?: Array<{ id: string; name: string; description?: string }>;
}
```

### `CourtEvent`

```typescript theme={null}
type CourtEvent = {
  speaker: "player" | "opposing_counsel" | "judge" | "witness" | "system";
  type: "question" | "answer" | "objection" | "ruling" | "system";
  text: string;
  timestamp: number;
  meta?: Record<string, any>;
};
```

### Other Types

* **`Phase`**: `"pretrial" | "opening" | "direct" | "cross" | "sidebar" | "bench_ruling" | "ended"`
* **`RoleTurn`**: `"player" | "opposing_counsel" | "judge"`
* **`ScoreState`**: `{ points, keyFactsHit?, deductions?, details? }`
* **`WitnessProfile`**: `{ id, name, role?, affidavit?, tendencies?, keyFacts? }`
* **`KeyFact`**: `{ label, weight?, tags? }`

## Environment Variables

### Required for Production

```bash theme={null}
NEXTAUTH_URL=https://your-domain.com
NEXTAUTH_SECRET=your-secret-key
NEON_DATABASE_URL=postgresql://...
PAYLOAD_SECRET=your-payload-secret
AI_GATEWAY_API_KEY=your-gateway-key
VERCEL_AI_MODEL_DEFAULT=openai/gpt-4o-mini
```

### Optional Providers

```bash theme={null}
GOOGLE_CLIENT_ID=...
GOOGLE_CLIENT_SECRET=...
APPLE_CLIENT_ID=...
APPLE_TEAM_ID=...
APPLE_KEY_ID=...
APPLE_PRIVATE_KEY=...
EMAIL_SERVER_HOST=smtp.example.com
EMAIL_SERVER_PORT=587
EMAIL_SERVER_USER=...
EMAIL_SERVER_PASSWORD=...
EMAIL_FROM=noreply@example.com
ENABLE_LIT_GATOR=true
LIT_GATOR_ACCESS_CODE=litigator-preview
```
