# Using the CardSight AI API - Collection Analytics API

## Overview
Get detailed analytics and statistics for a card collection including counts, investment metrics, composition breakdown, and performance data with top performers.

## Endpoint Details
- **Method**: GET
- **URL**: `https://api.cardsight.ai/v1/collection/{collectionId}/analytics`
- **Authentication**: API Key required (X-Api-Key header)

## Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| collectionId | UUID | Yes | The collection UUID (path parameter) |

## Using the CardSight AI SDK (Recommended)

### Node.js / TypeScript
```typescript
import { CardSightAI } from 'cardsightai'

const client = new CardSightAI({ apiKey: 'your-api-key' })

const response = await client.collections.analytics('550e8400-e29b-41d4-a716-446655440000')

// Always check for errors
if (response.error) {
  console.error('Error:', response.error)
} else {
  const analytics = response.data

  // Overview stats
  console.log(`Total Cards: ${analytics.overview.totalCards}`)
  console.log(`Unique Cards: ${analytics.overview.uniqueCards}`)
  console.log(`Total Quantity: ${analytics.overview.totalQuantity}`)

  // Financial metrics
  if (analytics.financials.currentMarketValue) {
    console.log(`Market Value: $${analytics.financials.currentMarketValue}`)
    console.log(`Total Invested: $${analytics.financials.totalInvested}`)
    console.log(`Overall ROI: ${analytics.financials.overallROI}%`)
  }

  // Composition breakdown
  console.log(`Graded: ${analytics.composition.gradedCount} (${analytics.composition.gradedPercentage}%)`)
  console.log(`Raw: ${analytics.composition.rawCount}`)
  console.log(`For Sale: ${analytics.composition.forSaleCount}`)
  console.log(`Sold: ${analytics.composition.soldCount}`)

  // Top performers
  if (analytics.performance.topGainer) {
    const top = analytics.performance.topGainer
    console.log(`Top Gainer: ${top.cardName} (+${top.gainPercentage}%)`)
  }
  if (analytics.performance.topValue) {
    const top = analytics.performance.topValue
    console.log(`Most Valuable: ${top.cardName} ($${top.currentValue})`)
  }
}
```

### Python
```python
from cardsightai import CardSightAI

client = CardSightAI(api_key='your-api-key')

response = client.collections.analytics('550e8400-e29b-41d4-a716-446655440000')

# Overview
print(f"Total Cards: {response.overview.total_cards}")
print(f"Unique Cards: {response.overview.unique_cards}")

# Financials
print(f"Market Value: ${response.financials.current_market_value}")
print(f"Overall ROI: {response.financials.overall_roi}%")

# Composition
print(f"Graded: {response.composition.graded_count}")
print(f"Raw: {response.composition.raw_count}")
```

## Direct API Call (cURL)
```bash
curl -X GET "https://api.cardsight.ai/v1/collection/550e8400-e29b-41d4-a716-446655440000/analytics" \
  -H "X-Api-Key: your-api-key"
```

## Example Response
```json
{
  "overview": {
    "totalCards": 150,
    "uniqueCards": 140,
    "totalQuantity": 165
  },
  "financials": {
    "totalInvested": "2500.00",
    "currentMarketValue": "3200.00",
    "totalRealizedGains": "450.00",
    "totalUnrealizedGains": "700.00",
    "overallROI": 28.0,
    "realizedROI": 35.5
  },
  "composition": {
    "gradedCount": 25,
    "rawCount": 125,
    "gradedPercentage": 16.67,
    "forSaleCount": 10,
    "soldCount": 15
  },
  "performance": {
    "averageCardValue": "21.33",
    "averageROI": 15.5,
    "topGainer": {
      "cardId": "550e8400-e29b-41d4-a716-446655440001",
      "cardName": "Shohei Ohtani",
      "releaseName": "2023 Topps Chrome",
      "releaseYear": "2023",
      "buyPrice": "50.00",
      "currentValue": "150.00",
      "gain": "100.00",
      "gainPercentage": 200.0
    },
    "topValue": {
      "cardId": "550e8400-e29b-41d4-a716-446655440002",
      "cardName": "Mike Trout",
      "releaseName": "2011 Topps Update",
      "releaseYear": "2011",
      "currentValue": "500.00",
      "quantity": 1
    }
  }
}
```

## Response Fields

The response contains 4 required sections:

### overview (required)

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| totalCards | number | Yes | Total number of card entries in collection |
| uniqueCards | number | Yes | Number of unique cards (ignoring duplicates) |
| totalQuantity | number | Yes | Total quantity including all duplicates |

### financials (required)

| Field | Type | Description |
|-------|------|-------------|
| totalInvested | string | Total amount invested (sum of buy prices, USD) |
| currentMarketValue | string | Current total market value (USD) |
| totalRealizedGains | string | Total gains from sold cards (USD) |
| totalUnrealizedGains | string | Unrealized gains on unsold cards (USD) |
| overallROI | number | Overall return on investment percentage |
| realizedROI | number | ROI on sold cards only |

### composition (required)

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| gradedCount | number | Yes | Number of graded cards |
| rawCount | number | Yes | Number of raw (ungraded) cards |
| gradedPercentage | number | Yes | Percentage of collection that is graded |
| forSaleCount | number | Yes | Number of cards listed for sale |
| soldCount | number | Yes | Number of cards that have been sold |

### performance (required)

| Field | Type | Description |
|-------|------|-------------|
| averageCardValue | string | Average current value per card (USD) |
| averageROI | number | Average ROI across all cards with buy prices |
| topGainer | object | Card with highest percentage gain (see below) |
| topValue | object | Most valuable card by current market price (see below) |

### TopGainer Object

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| cardId | string | Yes | Card UUID |
| cardName | string | Yes | Card name |
| releaseName | string | Yes | Release name |
| releaseYear | string | Yes | Release year |
| buyPrice | string | Yes | Purchase price (USD) |
| currentValue | string | Yes | Current market value (USD) |
| gain | string | Yes | Dollar gain amount (USD) |
| gainPercentage | number | Yes | Percentage gain |

### TopValue Object

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| cardId | string | Yes | Card UUID |
| cardName | string | Yes | Card name |
| releaseName | string | Yes | Release name |
| releaseYear | string | Yes | Release year |
| currentValue | string | Yes | Current market value (USD) |
| quantity | number | Yes | Quantity owned |

## Common Use Cases
- Display collection dashboard with key metrics
- Track investment performance and ROI
- Identify top performing cards
- Monitor graded vs raw card ratio
- Track sales activity

## Tips for AI Assistants
- **Note on IDs:** your `collectionId` (and other resources you create) are stable and yours to keep — saving cards to a collection or list is the recommended way to hold onto them for the long term. The card and set IDs inside a collection (`cardId`, `setId`) are catalog references you can use to pull fresh details from the catalog. See the FAQ for how IDs should be used.
- The SDK returns `{ data, error }` - always check for errors first
- Response has 4 required sections: `overview`, `financials`, `composition`, `performance`
- Dollar values are strings formatted as USD (e.g., "2500.00")
- ROI and percentage values are numbers (e.g., 28.0 for 28%)
- `topGainer` and `topValue` may be null if collection has no cards with pricing data
- `financials` fields may be null if no buy prices have been recorded
