# API Code Examples

Complete code examples for all Yemaya API endpoints.

## Table of Contents

1. [Authentication](#authentication)
2. [Projects](#projects)
3. [Assets](#assets)
4. [3D Generation](#3d-generation)
5. [Audio](#audio)
6. [NPC](#npc)
7. [Gameplay](#gameplay)
8. [WebSocket](#websocket)
9. [Webhooks](#webhooks)

---

## Authentication

### Register User

```typescript
// TypeScript
const response = await fetch('https://api.yemaya.io/v1/auth/register', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    email: 'user@example.com',
    password: 'SecurePassword123!',
    name: 'John Doe',
    acceptedTerms: true,
  }),
});

const { data } = await response.json();
console.log('User ID:', data.user.id);
console.log('Access Token:', data.tokens.accessToken);
```

```python
# Python
import requests

response = requests.post('https://api.yemaya.io/v1/auth/register', json={
    'email': 'user@example.com',
    'password': 'SecurePassword123!',
    'name': 'John Doe',
    'acceptedTerms': True
})

data = response.json()['data']
print(f"User ID: {data['user']['id']}")
print(f"Access Token: {data['tokens']['accessToken']}")
```

```bash
# cURL
curl -X POST https://api.yemaya.io/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "password": "SecurePassword123!",
    "name": "John Doe",
    "acceptedTerms": true
  }'
```

### Login

```typescript
// TypeScript
const login = async (email: string, password: string) => {
  const response = await fetch('https://api.yemaya.io/v1/auth/login', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ email, password }),
  });

  if (!response.ok) {
    throw new Error('Login failed');
  }

  const { data } = await response.json();
  return data.tokens;
};

// Usage
const tokens = await login('user@example.com', 'password123');
localStorage.setItem('accessToken', tokens.accessToken);
localStorage.setItem('refreshToken', tokens.refreshToken);
```

```python
# Python
import requests

def login(email: str, password: str) -> dict:
    response = requests.post('https://api.yemaya.io/v1/auth/login', json={
        'email': email,
        'password': password
    })
    response.raise_for_status()
    return response.json()['data']['tokens']

# Usage
tokens = login('user@example.com', 'password123')
access_token = tokens['accessToken']
```

### Token Refresh

```typescript
// TypeScript - Auto-refresh on 401
const fetchWithAuth = async (url: string, options: RequestInit = {}) => {
  let response = await fetch(url, {
    ...options,
    headers: {
      ...options.headers,
      Authorization: `Bearer ${localStorage.getItem('accessToken')}`,
    },
  });

  if (response.status === 401) {
    // Refresh token
    const refreshResponse = await fetch(
      'https://api.yemaya.io/v1/auth/refresh',
      {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          refreshToken: localStorage.getItem('refreshToken'),
        }),
      }
    );

    if (refreshResponse.ok) {
      const { data } = await refreshResponse.json();
      localStorage.setItem('accessToken', data.tokens.accessToken);

      // Retry original request
      response = await fetch(url, {
        ...options,
        headers: {
          ...options.headers,
          Authorization: `Bearer ${data.tokens.accessToken}`,
        },
      });
    }
  }

  return response;
};
```

---

## Projects

### List Projects

```typescript
// TypeScript
const listProjects = async (filters?: {
  status?: string;
  type?: string;
  page?: number;
  limit?: number;
}) => {
  const params = new URLSearchParams(filters as any);
  const response = await fetchWithAuth(
    `https://api.yemaya.io/v1/projects?${params}`
  );
  return response.json();
};

// Usage
const { data, meta } = await listProjects({
  status: 'active',
  type: 'game',
  page: 1,
  limit: 20,
});

console.log(`Found ${meta.total} projects`);
data.forEach((project) => {
  console.log(`- ${project.name} (${project.status})`);
});
```

```python
# Python
import requests

def list_projects(access_token: str, **filters) -> dict:
    response = requests.get(
        'https://api.yemaya.io/v1/projects',
        headers={'Authorization': f'Bearer {access_token}'},
        params=filters
    )
    return response.json()

# Usage
result = list_projects(access_token, status='active', type='game')
for project in result['data']:
    print(f"- {project['name']} ({project['status']})")
```

### Create Project

```typescript
// TypeScript
const createProject = async (project: {
  name: string;
  description?: string;
  type: 'film' | 'game' | 'animation' | 'mixed';
  settings?: Record<string, any>;
}) => {
  const response = await fetchWithAuth('https://api.yemaya.io/v1/projects', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(project),
  });
  return response.json();
};

// Usage
const { data: newProject } = await createProject({
  name: 'My Awesome Game',
  description: 'A platformer adventure',
  type: 'game',
  settings: {
    targetPlatforms: ['pc', 'switch'],
    gameEngine: 'godot',
  },
});

console.log(`Created project: ${newProject.id}`);
```

### Add Project Member

```typescript
// TypeScript
const addMember = async (
  projectId: string,
  member: {
    email?: string;
    userId?: string;
    role: 'admin' | 'editor' | 'viewer';
  }
) => {
  const response = await fetchWithAuth(
    `https://api.yemaya.io/v1/projects/${projectId}/members`,
    {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(member),
    }
  );
  return response.json();
};

// Invite by email
await addMember('proj_abc123', {
  email: 'teammate@example.com',
  role: 'editor',
});
```

---

## Assets

### Upload Asset (Chunked)

```typescript
// TypeScript - Complete chunked upload implementation
const uploadAsset = async (
  projectId: string,
  file: File,
  onProgress?: (progress: number) => void
) => {
  const CHUNK_SIZE = 5 * 1024 * 1024; // 5MB chunks

  // 1. Initialize upload
  const initResponse = await fetchWithAuth(
    `https://api.yemaya.io/v1/projects/${projectId}/assets/upload`,
    {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        filename: file.name,
        contentType: file.type,
        size: file.size,
      }),
    }
  );

  const {
    data: { uploadId, chunkSize },
  } = await initResponse.json();

  // 2. Upload chunks
  const chunks = Math.ceil(file.size / chunkSize);

  for (let i = 0; i < chunks; i++) {
    const start = i * chunkSize;
    const end = Math.min(start + chunkSize, file.size);
    const chunk = file.slice(start, end);

    await fetchWithAuth(
      `https://api.yemaya.io/v1/assets/upload/${uploadId}/chunks/${i}`,
      {
        method: 'PUT',
        headers: { 'Content-Type': 'application/octet-stream' },
        body: chunk,
      }
    );

    onProgress?.(((i + 1) / chunks) * 100);
  }

  // 3. Complete upload
  const completeResponse = await fetchWithAuth(
    `https://api.yemaya.io/v1/assets/upload/${uploadId}/complete`,
    {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        name: file.name,
        tags: ['uploaded'],
      }),
    }
  );

  return completeResponse.json();
};

// Usage
const fileInput = document.querySelector('input[type="file"]');
const file = fileInput.files[0];

const { data: asset } = await uploadAsset('proj_abc123', file, (progress) => {
  console.log(`Upload progress: ${progress.toFixed(1)}%`);
});

console.log(`Uploaded: ${asset.id}`);
```

### Download Asset

```typescript
// TypeScript
const downloadAsset = async (projectId: string, assetId: string) => {
  const response = await fetchWithAuth(
    `https://api.yemaya.io/v1/projects/${projectId}/assets/${assetId}/download`
  );

  const {
    data: { url, expiresAt },
  } = await response.json();

  // Download the file
  const downloadResponse = await fetch(url);
  const blob = await downloadResponse.blob();

  // Trigger browser download
  const a = document.createElement('a');
  a.href = URL.createObjectURL(blob);
  a.download = 'asset-file';
  a.click();
};
```

---

## 3D Generation

### Text-to-3D

```typescript
// TypeScript
const generateModel = async (options: {
  prompt: string;
  provider?: string;
  quality?: 'draft' | 'standard' | 'high' | 'ultra';
  style?: string;
}) => {
  const response = await fetchWithAuth('https://api.yemaya.io/v1/3d/generate', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(options),
  });

  const { data } = await response.json();
  return data; // { jobId, status, estimatedTime }
};

// Poll for completion
const waitForJob = async (jobId: string) => {
  while (true) {
    const response = await fetchWithAuth(
      `https://api.yemaya.io/v1/3d/jobs/${jobId}`
    );
    const { data } = await response.json();

    if (data.status === 'completed') {
      return data;
    } else if (data.status === 'failed') {
      throw new Error(data.error);
    }

    await new Promise((resolve) => setTimeout(resolve, 2000));
  }
};

// Usage
const job = await generateModel({
  prompt: 'A cute cartoon cat with big eyes, 3D model',
  provider: 'meshy',
  quality: 'high',
});

console.log(`Job started: ${job.jobId}`);

const result = await waitForJob(job.jobId);
console.log('Model URLs:', result.assets);
```

```python
# Python
import requests
import time

def generate_3d_model(access_token: str, prompt: str, **options) -> dict:
    response = requests.post(
        'https://api.yemaya.io/v1/3d/generate',
        headers={'Authorization': f'Bearer {access_token}'},
        json={'prompt': prompt, **options}
    )
    return response.json()['data']

def wait_for_job(access_token: str, job_id: str) -> dict:
    while True:
        response = requests.get(
            f'https://api.yemaya.io/v1/3d/jobs/{job_id}',
            headers={'Authorization': f'Bearer {access_token}'}
        )
        data = response.json()['data']

        if data['status'] == 'completed':
            return data
        elif data['status'] == 'failed':
            raise Exception(data.get('error', 'Job failed'))

        time.sleep(2)

# Usage
job = generate_3d_model(
    access_token,
    'A cartoon robot character',
    quality='high'
)

result = wait_for_job(access_token, job['jobId'])
print(f"Model: {result['assets']['glb']}")
```

### Batch Generation

```typescript
// TypeScript
const batchGenerate = async (prompts: string[], options = {}) => {
  const response = await fetchWithAuth('https://api.yemaya.io/v1/3d/batch', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      prompts,
      ...options,
    }),
  });

  return response.json();
};

// Usage
const { data: batch } = await batchGenerate(
  ['A wooden sword', 'A leather shield', 'A magic staff', 'A healing potion'],
  {
    quality: 'standard',
    style: 'low-poly',
  }
);

console.log(`Batch ID: ${batch.batchId}`);
console.log(`Jobs: ${batch.jobs.map((j) => j.jobId).join(', ')}`);
```

---

## Audio

### Generate Music

```typescript
// TypeScript
const generateMusic = async (options: {
  prompt: string;
  genre?: string;
  duration?: number;
  tempo?: number;
}) => {
  const response = await fetchWithAuth(
    'https://api.yemaya.io/v1/audio/music/generate',
    {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(options),
    }
  );

  return response.json();
};

// Usage
const { data: musicJob } = await generateMusic({
  prompt: 'Epic orchestral battle music',
  genre: 'orchestral',
  duration: 120,
  tempo: 140,
});

// Wait for completion...
const result = await waitForJob(musicJob.jobId);
console.log('Music URL:', result.audioUrl);
```

### Voice Synthesis

```typescript
// TypeScript
const synthesizeVoice = async (options: {
  text: string;
  voiceId: string;
  emotion?: string;
  speed?: number;
}) => {
  const response = await fetchWithAuth(
    'https://api.yemaya.io/v1/audio/voice/synthesize',
    {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(options),
    }
  );

  return response.json();
};

// Usage
const { data: voiceResult } = await synthesizeVoice({
  text: 'Welcome, brave adventurer! Your quest awaits.',
  voiceId: 'voice_fantasy_male',
  emotion: 'excited',
  speed: 1.0,
});

console.log('Voice URL:', voiceResult.audioUrl);
```

---

## NPC

### Create NPC

```typescript
// TypeScript
const createNPC = async (npc: {
  name: string;
  role: string;
  projectId: string;
  personality: {
    traits: string[];
    values: string[];
  };
  background: {
    occupation: string;
    history: string;
  };
}) => {
  const response = await fetchWithAuth('https://api.yemaya.io/v1/npcs/create', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(npc),
  });

  return response.json();
};

// Usage
const { data: npc } = await createNPC({
  name: 'Elena the Merchant',
  role: 'merchant',
  projectId: 'proj_abc123',
  personality: {
    traits: ['friendly', 'shrewd', 'patient'],
    values: ['fairness', 'prosperity'],
  },
  background: {
    occupation: 'General goods merchant',
    history: 'Former adventurer who settled down to run a shop.',
  },
});

console.log(`Created NPC: ${npc.npcId}`);
```

### Chat with NPC

```typescript
// TypeScript
const chatWithNPC = async (npcId: string, message: string, context = {}) => {
  const response = await fetchWithAuth(
    `https://api.yemaya.io/v1/npcs/${npcId}/chat`,
    {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        playerId: 'player_001',
        message,
        context,
        generateVoice: true,
      }),
    }
  );

  return response.json();
};

// Usage
const { data: response } = await chatWithNPC(
  'npc_elena_123',
  'Do you have any healing potions?',
  {
    location: 'shop_counter',
    timeOfDay: 'morning',
    playerReputation: 75,
  }
);

console.log('NPC says:', response.response);
console.log('Emotion:', response.emotion);
console.log('Voice:', response.audioUrl);
```

---

## Gameplay

### Combat Simulation

```typescript
// TypeScript
const simulateCombat = async (setup: {
  combatType: 'turn_based' | 'real_time';
  participants: Array<{
    id: string;
    team: 'player' | 'enemy';
    stats: { health: number; attack: number; defense: number };
  }>;
}) => {
  const response = await fetchWithAuth(
    'https://api.yemaya.io/v1/gameplay/combat/simulate',
    {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(setup),
    }
  );

  return response.json();
};

// Usage
const { data: combat } = await simulateCombat({
  combatType: 'turn_based',
  participants: [
    {
      id: 'player_1',
      team: 'player',
      stats: { health: 100, attack: 25, defense: 15 },
    },
    {
      id: 'goblin_1',
      team: 'enemy',
      stats: { health: 50, attack: 15, defense: 5 },
    },
  ],
});

console.log('Combat result:', combat.winner);
console.log('Turns:', combat.turns.length);
```

---

## WebSocket

### Real-Time Connection

```typescript
// TypeScript - Full WebSocket implementation
class YemayaWebSocket {
  private ws: WebSocket;
  private subscriptions: Set<string> = new Set();
  private handlers: Map<string, Function[]> = new Map();

  constructor(private token: string) {}

  connect(): Promise<void> {
    return new Promise((resolve, reject) => {
      this.ws = new WebSocket(`wss://api.yemaya.io/v1/ws?token=${this.token}`);

      this.ws.onopen = () => {
        console.log('WebSocket connected');
        resolve();
      };

      this.ws.onerror = (error) => {
        console.error('WebSocket error:', error);
        reject(error);
      };

      this.ws.onmessage = (event) => {
        const message = JSON.parse(event.data);
        this.handleMessage(message);
      };

      this.ws.onclose = () => {
        console.log('WebSocket disconnected');
        this.reconnect();
      };
    });
  }

  private handleMessage(message: any) {
    const handlers = this.handlers.get(message.type) || [];
    handlers.forEach((handler) => handler(message.data));
  }

  subscribe(channel: string) {
    this.subscriptions.add(channel);
    this.ws.send(
      JSON.stringify({
        type: 'subscribe',
        channel,
      })
    );
  }

  unsubscribe(channel: string) {
    this.subscriptions.delete(channel);
    this.ws.send(
      JSON.stringify({
        type: 'unsubscribe',
        channel,
      })
    );
  }

  on(event: string, handler: Function) {
    if (!this.handlers.has(event)) {
      this.handlers.set(event, []);
    }
    this.handlers.get(event)!.push(handler);
  }

  private reconnect() {
    setTimeout(() => {
      this.connect().then(() => {
        // Resubscribe to all channels
        this.subscriptions.forEach((channel) => {
          this.ws.send(
            JSON.stringify({
              type: 'subscribe',
              channel,
            })
          );
        });
      });
    }, 3000);
  }

  disconnect() {
    this.ws.close();
  }
}

// Usage
const ws = new YemayaWebSocket(accessToken);
await ws.connect();

// Subscribe to project updates
ws.subscribe('project:proj_abc123');

// Listen for events
ws.on('asset.uploaded', (data) => {
  console.log('New asset:', data.assetId);
});

ws.on('generation.progress', (data) => {
  console.log(`Progress: ${data.progress}%`);
});

ws.on('generation.completed', (data) => {
  console.log('Generation complete:', data.jobId);
});
```

---

## Webhooks

### Register Webhook

```typescript
// TypeScript
const registerWebhook = async (config: {
  url: string;
  events: string[];
  secret?: string;
}) => {
  const response = await fetchWithAuth('https://api.yemaya.io/v1/webhooks', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(config),
  });

  return response.json();
};

// Usage
const { data: webhook } = await registerWebhook({
  url: 'https://my-server.com/webhooks/yemaya',
  events: ['project.created', 'asset.uploaded', 'generation.completed'],
  secret: 'my-webhook-secret',
});

console.log('Webhook ID:', webhook.id);
```

### Verify Webhook Signature

```typescript
// TypeScript - Express.js example
import crypto from 'crypto';
import express from 'express';

const app = express();

app.post(
  '/webhooks/yemaya',
  express.raw({ type: 'application/json' }),
  (req, res) => {
    const signature = req.headers['x-webhook-signature'] as string;
    const payload = req.body.toString();

    // Verify signature
    const expectedSignature =
      'sha256=' +
      crypto
        .createHmac('sha256', process.env.WEBHOOK_SECRET!)
        .update(payload)
        .digest('hex');

    if (
      !crypto.timingSafeEqual(
        Buffer.from(signature),
        Buffer.from(expectedSignature)
      )
    ) {
      return res.status(401).send('Invalid signature');
    }

    // Process webhook
    const event = JSON.parse(payload);
    console.log('Webhook event:', event.type);
    console.log('Data:', event.data);

    res.status(200).send('OK');
  }
);
```

```python
# Python - Flask example
import hmac
import hashlib
from flask import Flask, request

app = Flask(__name__)

@app.route('/webhooks/yemaya', methods=['POST'])
def handle_webhook():
    signature = request.headers.get('X-Webhook-Signature', '')
    payload = request.get_data()

    # Verify signature
    expected = 'sha256=' + hmac.new(
        WEBHOOK_SECRET.encode(),
        payload,
        hashlib.sha256
    ).hexdigest()

    if not hmac.compare_digest(signature, expected):
        return 'Invalid signature', 401

    # Process webhook
    event = request.get_json()
    print(f"Webhook event: {event['type']}")

    return 'OK', 200
```

---

## Error Handling

### Standard Error Handling

```typescript
// TypeScript
class YemayaAPIError extends Error {
  constructor(
    public code: string,
    public message: string,
    public status: number,
    public details?: any
  ) {
    super(message);
  }
}

const handleResponse = async (response: Response) => {
  const data = await response.json();

  if (!response.ok) {
    throw new YemayaAPIError(
      data.error?.code || 'UNKNOWN_ERROR',
      data.error?.message || 'An error occurred',
      response.status,
      data.error?.details
    );
  }

  return data;
};

// Usage with error handling
try {
  const response = await fetchWithAuth('/v1/projects');
  const { data } = await handleResponse(response);
  console.log('Projects:', data);
} catch (error) {
  if (error instanceof YemayaAPIError) {
    switch (error.code) {
      case 'AUTH_REQUIRED':
        // Redirect to login
        break;
      case 'RATE_LIMITED':
        // Wait and retry
        await new Promise((r) =>
          setTimeout(r, error.details?.retryAfter * 1000)
        );
        break;
      case 'VALIDATION_ERROR':
        // Show validation errors
        console.error('Validation errors:', error.details);
        break;
      default:
        console.error(`Error: ${error.message}`);
    }
  }
}
```

---

## See Also

- [SDK Tutorials](./sdk-tutorials.md)
- [Webhook Integration](./webhooks.md)
- [Rate Limiting](./rate-limits.md)
- [API Reference](./endpoints/README.md)
