# Using the CardSight AI API - Collection Breakdown API

## Overview
Analyze your collection by grouping cards by different dimensions (release, year, grade, player, or manufacturer). Returns detailed statistics for each group including value, ROI, and top cards.

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

## Parameters

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| collectionId | UUID | Yes | - | Collection UUID (path) |
| groupBy | string | Yes | - | Dimension to group by: `release`, `year`, `grade`, `player`, `manufacturer` |
| take | integer | No | 20 | Results per page (1-100) |
| skip | integer | No | 0 | Number of results to skip |
| sortBy | string | No | "value" | Metric to sort by: `count`, `value`, `roi`, `percentage` |
| order | string | No | "desc" | Sort order: `asc` or `desc` |
| minCount | number | No | - | Minimum card count to include in results |

## 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.breakdown('550e8400-e29b-41d4-a716-446655440000', {
  groupBy: 'year',
  sortBy: 'value',
  order: 'desc',
  take: 10
})

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

  // Summary stats
  console.log(`Grouped by: ${summary.groupedBy}`)
  console.log(`Total groups: ${summary.totalGroups}`)
  console.log(`Total cards: ${summary.totalCards}`)
  console.log(`Total value: $${summary.totalValue}`)

  if (summary.mostValuableGroup) {
    console.log(`Most valuable: ${summary.mostValuableGroup.name} ($${summary.mostValuableGroup.value})`)
  }

  if (summary.bestPerformingGroup) {
    console.log(`Best ROI: ${summary.bestPerformingGroup.name} (${summary.bestPerformingGroup.roi}%)`)
  }

  // Individual groups
  for (const group of groups) {
    console.log(`\n${group.groupKey}:`)
    console.log(`  Cards: ${group.cardCount} (${group.uniqueCardCount} unique)`)
    console.log(`  Value: $${group.totalCurrentValue}`)
    console.log(`  ROI: ${group.roi}%`)
    console.log(`  % of collection: ${group.percentageOfCollection}%`)
  }

  // Pagination
  console.log(`\nPage ${pagination.page} of ${pagination.pages}`)
}
```

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

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

response = client.collections.breakdown(
    '550e8400-e29b-41d4-a716-446655440000',
    group_by='manufacturer',
    sort_by='value'
)

print(f"Grouped by: {response.summary.grouped_by}")
print(f"Total groups: {response.summary.total_groups}")

for group in response.groups:
    print(f"{group.group_key}: {group.card_count} cards, ${group.total_current_value}")
```

## Direct API Call (cURL)
```bash
curl -X GET "https://api.cardsight.ai/v1/collection/550e8400-e29b-41d4-a716-446655440000/breakdown?groupBy=year&sortBy=value&order=desc" \
  -H "X-Api-Key: your-api-key"
```

## Example Response
```json
{
  "summary": {
    "totalGroups": 5,
    "totalCards": 150,
    "totalQuantity": 165,
    "totalValue": "3200.00",
    "totalInvested": "2500.00",
    "overallRoi": 28.0,
    "groupedBy": "year",
    "mostValuableGroup": {
      "name": "2023",
      "value": "1800.00"
    },
    "bestPerformingGroup": {
      "name": "2021",
      "roi": 45.5
    }
  },
  "groups": [
    {
      "groupKey": "2023",
      "groupId": null,
      "cardCount": 75,
      "uniqueCardCount": 70,
      "totalQuantity": 80,
      "totalBuyPrice": "1200.00",
      "totalCurrentValue": "1800.00",
      "totalSoldPrice": "0.00",
      "averageBuyPrice": "16.00",
      "averageCurrentValue": "24.00",
      "roi": 50.0,
      "percentageOfCollection": 50.0,
      "topCards": [
        {
          "cardId": "550e8400-e29b-41d4-a716-446655440001",
          "cardName": "Shohei Ohtani",
          "currentValue": "150.00"
        }
      ]
    },
    {
      "groupKey": "2022",
      "groupId": null,
      "cardCount": 50,
      "uniqueCardCount": 48,
      "totalQuantity": 55,
      "totalBuyPrice": "800.00",
      "totalCurrentValue": "900.00",
      "totalSoldPrice": "0.00",
      "averageBuyPrice": "16.00",
      "averageCurrentValue": "18.00",
      "roi": 12.5,
      "percentageOfCollection": 33.3,
      "topCards": []
    }
  ],
  "pagination": {
    "total_count": 5,
    "skip": 0,
    "take": 20,
    "page": 1,
    "pages": 1
  }
}
```

## Response Fields

The response contains 3 required sections: `summary`, `groups`, and `pagination`.

### summary (required)

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| totalGroups | number | Yes | Total number of groups |
| totalCards | number | Yes | Total number of cards in collection |
| totalQuantity | number | Yes | Total quantity including duplicates |
| groupedBy | string | Yes | The dimension used for grouping |
| totalValue | string | No | Total collection value (USD) |
| totalInvested | string | No | Total amount invested (USD) |
| overallRoi | number | No | Overall ROI percentage |
| mostValuableGroup | object | No | Group with highest total value |
| bestPerformingGroup | object | No | Group with highest ROI |

### MostValuableGroup Object

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| name | string | Yes | Name of the most valuable group |
| value | string | Yes | Total value of the group (USD) |

### BestPerformingGroup Object

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| name | string | Yes | Name of the best performing group |
| roi | number | Yes | ROI percentage |

### groups (required) - Array of BreakdownGroup

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| groupKey | string | Yes | The grouping key (e.g., "2023", "Topps", "PSA 10") |
| groupId | string | No | UUID of the group entity if applicable |
| cardCount | number | Yes | Number of cards in this group |
| uniqueCardCount | number | Yes | Number of unique cards (ignoring duplicates) |
| totalQuantity | number | No | Total quantity including duplicates |
| totalBuyPrice | string | No | Total purchase price (USD) |
| totalCurrentValue | string | No | Total current market value (USD) |
| totalSoldPrice | string | No | Total sold price for sold cards (USD) |
| averageBuyPrice | string | No | Average purchase price per card (USD) |
| averageCurrentValue | string | No | Average current value per card (USD) |
| roi | number | No | Return on investment percentage |
| percentageOfCollection | number | No | Percentage this group represents of total collection |
| topCards | array | No | Top 5 most valuable cards in this group |

### pagination (required)

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| total_count | number | Yes | Total number of groups |
| skip | number | Yes | Number of groups skipped |
| take | number | Yes | Number of groups included |
| page | number | Yes | Current page number |
| pages | number | Yes | Total number of pages |

## Common Use Cases
- Visualize collection composition by year, manufacturer, or player
- Identify which segments of your collection have the best ROI
- Find your most valuable groupings
- Build pie charts and breakdown visualizations
- Track diversity of collection across different dimensions

## 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
- URL uses singular "collection" not "collections": `/v1/collection/{collectionId}/breakdown`
- The `groupBy` parameter is **required** - you must specify how to group the data
- Valid `groupBy` values: `release`, `year`, `grade`, `player`, `manufacturer`
- Use `sortBy=roi` to find best-performing segments, `sortBy=value` for most valuable
- Dollar values are strings formatted as USD (e.g., "1800.00")
- `mostValuableGroup` and `bestPerformingGroup` may be null if no pricing data exists
- The `topCards` array contains up to 5 most valuable cards per group
