# Final Model Schemas - Clean State

## Overview

This document defines the simplified, clean architecture for AI configuration and billing models.

**Total Models**: 5 (down from 7)
- IntegrationProvider (API keys)
- AIModelConfig (model definitions + pricing)
- AISettings (system defaults + account overrides) - *renamed from GlobalIntegrationSettings*
- AccountSettings (generic key-value store)
- CreditCostConfig (operation-level pricing)

**Models Removed**:
- IntegrationSettings (merged into AISettings/AccountSettings)
- CreditCostConfig.tokens_per_credit (moved to AIModelConfig)

---

## 1. IntegrationProvider (API Keys Only)

Centralized storage for ALL external service API keys.

| Field | Type | Required | Notes |
|-------|------|----------|-------|
| `provider_id` | CharField(50) PK | Yes | openai, runware, stripe, paypal, resend |
| `display_name` | CharField(100) | Yes | Human-readable name |
| `provider_type` | CharField(20) | Yes | ai / payment / email / storage |
| `api_key` | CharField(500) | No | Primary API key |
| `api_secret` | CharField(500) | No | Secondary secret (Stripe, PayPal) |
| `webhook_secret` | CharField(500) | No | Webhook signing secret |
| `api_endpoint` | URLField | No | Custom endpoint (optional) |
| `config` | JSONField | No | Provider-specific config |
| `is_active` | BooleanField | Yes | Enable/disable provider |
| `is_sandbox` | BooleanField | Yes | Test mode flag |
| `updated_by` | FK(User) | No | Audit trail |
| `created_at` | DateTime | Auto | |
| `updated_at` | DateTime | Auto | |

**Seeded Providers**:
- `openai` - AI (text + DALL-E)
- `runware` - AI (images)
- `anthropic` - AI (future)
- `stripe` - Payment
- `paypal` - Payment
- `resend` - Email

---

## 2. AIModelConfig (Single Source of Truth for Models)

All AI models (text + image) with pricing and credit configuration.

| Field | Type | Required | Notes |
|-------|------|----------|-------|
| `id` | AutoField PK | Auto | |
| `model_name` | CharField(100) | Yes | gpt-5.1, dall-e-3, runware:97@1 |
| `model_type` | CharField(20) | Yes | text / image |
| `provider` | CharField(50) | Yes | Links to IntegrationProvider |
| `display_name` | CharField(200) | Yes | Human-readable |
| `is_default` | BooleanField | Yes | One default per type |
| `is_active` | BooleanField | Yes | Enable/disable |
| `cost_per_1k_input` | DecimalField | No | Provider cost (USD) - text models |
| `cost_per_1k_output` | DecimalField | No | Provider cost (USD) - text models |
| `tokens_per_credit` | IntegerField | No | Text: tokens per 1 credit (e.g., 1000) |
| `credits_per_image` | IntegerField | No | Image: credits per image (e.g., 1, 5, 15) |
| `quality_tier` | CharField(20) | No | basic / quality / premium |
| `max_tokens` | IntegerField | No | Model token limit |
| `context_window` | IntegerField | No | Model context size |
| `capabilities` | JSONField | No | vision, function_calling, etc. |
| `created_at` | DateTime | Auto | |
| `updated_at` | DateTime | Auto | |

**Credit Configuration Examples**:

| Model | Type | tokens_per_credit | credits_per_image | quality_tier |
|-------|------|-------------------|-------------------|--------------|
| gpt-5.1 | text | 1000 | - | - |
| gpt-4o-mini | text | 10000 | - | - |
| runware:97@1 | image | - | 1 | basic |
| dall-e-3 | image | - | 5 | quality |
| google:4@2 | image | - | 15 | premium |

---

## 3. AISettings (Renamed from GlobalIntegrationSettings)

System-wide AI defaults. Singleton (pk=1).

| Field | Type | Required | Default | Notes |
|-------|------|----------|---------|-------|
| `id` | AutoField PK | Auto | 1 | Singleton |
| `temperature` | FloatField | Yes | 0.7 | AI temperature (0.0-2.0) |
| `max_tokens` | IntegerField | Yes | 8192 | Max response tokens |
| `image_style` | CharField(30) | Yes | photorealistic | Default image style |
| `image_quality` | CharField(20) | Yes | standard | standard / hd |
| `max_images_per_article` | IntegerField | Yes | 4 | Max in-article images |
| `image_size` | CharField(20) | Yes | 1024x1024 | Default image dimensions |
| `updated_by` | FK(User) | No | | Audit trail |
| `updated_at` | DateTime | Auto | | |

**Removed Fields** (now elsewhere):
- All `*_api_key` fields → IntegrationProvider
- All `*_model` fields → AIModelConfig.is_default
- `default_text_provider` → AIModelConfig.is_default where model_type='text'
- `default_image_service` → AIModelConfig.is_default where model_type='image'

**Image Style Choices**:
- `photorealistic` - Ultra realistic photography
- `illustration` - Digital illustration
- `3d_render` - Computer generated 3D
- `minimal_flat` - Minimal / Flat Design
- `artistic` - Artistic / Painterly
- `cartoon` - Cartoon / Stylized

---

## 4. AccountSettings (Per-Account Overrides)

Generic key-value store for account-specific settings.

| Field | Type | Required | Notes |
|-------|------|----------|-------|
| `id` | AutoField PK | Auto | |
| `account` | FK(Account) | Yes | |
| `key` | CharField(100) | Yes | Setting key |
| `value` | JSONField | Yes | Setting value |
| `created_at` | DateTime | Auto | |
| `updated_at` | DateTime | Auto | |

**Unique Constraint**: `(account, key)`

**AI-Related Keys** (override AISettings defaults):

| Key | Type | Example | Notes |
|-----|------|---------|-------|
| `ai.temperature` | float | 0.7 | Override system default |
| `ai.max_tokens` | int | 8192 | Override system default |
| `ai.image_style` | string | "photorealistic" | Override system default |
| `ai.image_quality` | string | "hd" | Override system default |
| `ai.max_images` | int | 6 | Override system default |
| `ai.image_quality_tier` | string | "quality" | User's preferred tier |

---

## 5. CreditCostConfig (Operation-Level Pricing)

Fixed credit costs per operation type.

| Field | Type | Required | Notes |
|-------|------|----------|-------|
| `operation_type` | CharField(50) PK | Yes | Unique operation ID |
| `display_name` | CharField(100) | Yes | Human-readable |
| `base_credits` | IntegerField | Yes | Fixed credits per operation |
| `is_active` | BooleanField | Yes | Enable/disable |
| `description` | TextField | No | Admin notes |

**Removed**: `tokens_per_credit` (now in AIModelConfig)

---

## Frontend Settings Structure

### Content Generation Settings Tab

```
┌─────────────────────────────────────────────────────────────┐
│  Content Generation Settings                                │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  AI Parameters                                              │
│  ┌─────────────────────────────────────────────────────┐   │
│  │ Temperature        [=====○====] 0.7                 │   │
│  │                    More focused ←→ More creative    │   │
│  │                                                     │   │
│  │ Max Tokens         [8192    ▼]                      │   │
│  │                    Response length limit            │   │
│  └─────────────────────────────────────────────────────┘   │
│                                                             │
│  Image Generation                                           │
│  ┌─────────────────────────────────────────────────────┐   │
│  │ Image Quality                                       │   │
│  │   ○ Basic (1 credit/image)     - Fast, simple      │   │
│  │   ● Quality (5 credits/image)  - Balanced          │   │
│  │   ○ Premium (15 credits/image) - Best quality      │   │
│  │                                                     │   │
│  │ Image Style        [Photorealistic      ▼]         │   │
│  │                                                     │   │
│  │ Images per Article [4 ▼]  (max 8)                  │   │
│  └─────────────────────────────────────────────────────┘   │
│                                                             │
│                              [Save Settings]                │
└─────────────────────────────────────────────────────────────┘
```

### Frontend API Response

```
GET /api/v1/accounts/settings/ai/

Response:
{
  "content_generation": {
    "temperature": 0.7,
    "max_tokens": 8192
  },
  "image_generation": {
    "quality_tiers": [
      {"tier": "basic", "credits": 1, "label": "Basic", "description": "Fast, simple images"},
      {"tier": "quality", "credits": 5, "label": "Quality", "description": "Balanced quality"},
      {"tier": "premium", "credits": 15, "label": "Premium", "description": "Best quality"}
    ],
    "selected_tier": "quality",
    "styles": [
      {"value": "photorealistic", "label": "Photorealistic"},
      {"value": "illustration", "label": "Illustration"},
      {"value": "3d_render", "label": "3D Render"},
      {"value": "minimal_flat", "label": "Minimal / Flat"},
      {"value": "artistic", "label": "Artistic"},
      {"value": "cartoon", "label": "Cartoon"}
    ],
    "selected_style": "photorealistic",
    "max_images": 4,
    "max_allowed": 8
  }
}
```

### Save Settings Request

```
PUT /api/v1/accounts/settings/ai/

Request:
{
  "temperature": 0.8,
  "max_tokens": 4096,
  "image_quality_tier": "premium",
  "image_style": "illustration",
  "max_images": 6
}
```

---

## Data Flow

```
┌──────────────────┐     ┌──────────────────┐     ┌──────────────────┐
│ IntegrationProv. │     │  AIModelConfig   │     │   AISettings     │
│                  │     │                  │     │   (Singleton)    │
│ - API keys       │◄────│ - Model list     │     │                  │
│ - Provider info  │     │ - Pricing        │     │ - Defaults       │
└──────────────────┘     │ - Credits config │     │ - temperature    │
                         │ - quality_tier   │     │ - max_tokens     │
                         └────────┬─────────┘     │ - image_style    │
                                  │               └────────┬─────────┘
                                  │                        │
                                  ▼                        ▼
                         ┌──────────────────────────────────────────┐
                         │            AccountSettings               │
                         │                                          │
                         │  Account-specific overrides:             │
                         │  - ai.temperature = 0.8                  │
                         │  - ai.image_quality_tier = "premium"     │
                         │  - ai.image_style = "illustration"       │
                         └──────────────────────────────────────────┘
                                           │
                                           ▼
                         ┌──────────────────────────────────────────┐
                         │          Frontend Settings UI            │
                         │                                          │
                         │  GET /api/v1/accounts/settings/ai/       │
                         │  - Merges AISettings + AccountSettings   │
                         │  - Returns effective values for account  │
                         └──────────────────────────────────────────┘
```

---

## Migration Summary

| From | To | Action |
|------|----|--------|
| GlobalIntegrationSettings.*_api_key | IntegrationProvider | Already done |
| GlobalIntegrationSettings.*_model | AIModelConfig.is_default | Already done |
| GlobalIntegrationSettings (remaining) | AISettings (rename) | Phase 3 |
| IntegrationSettings | AccountSettings | Phase 3 - delete model |
| CreditCostConfig.tokens_per_credit | AIModelConfig.tokens_per_credit | Already done |

---

## Phase 3 Implementation Steps

1. **Rename Model**: GlobalIntegrationSettings → AISettings
2. **Remove Fields**: All `*_api_key`, `*_model` fields from AISettings
3. **Create API Endpoint**: `/api/v1/accounts/settings/ai/`
4. **Update Frontend**: Load from new endpoint, use quality_tier picker
5. **Delete Model**: IntegrationSettings (after migrating any data)
6. **Cleanup**: Remove deprecated choices/constants

---

## Files to Modify (Phase 3)

| File | Change |
|------|--------|
| `modules/system/global_settings_models.py` | Rename class, remove deprecated fields |
| `modules/system/admin.py` | Update admin for AISettings |
| `modules/system/views.py` | New AI settings API endpoint |
| `modules/system/serializers.py` | AISettingsSerializer |
| `settings.py` | Update admin sidebar |
| `ai/ai_core.py` | Use AISettings instead of GlobalIntegrationSettings |
| Frontend | New settings component with quality tier picker |
