# Integration Settings Architecture Analysis

## Current Setup (As of Dec 10, 2025)

### 1. How It Works Now

**System Architecture:**
```
┌─────────────────────────────────────────────────────────────┐
│  INTEGRATION SETTINGS (System-Wide API Keys)                │
│  Stored in: IntegrationSettings model                       │
│  Account: AWS Admin (slug: aws-admin)                       │
└─────────────────────────────────────────────────────────────┘
                              │
                              │ Fallback mechanism
                              ↓
        ┌─────────────────────────────────────────┐
        │                                         │
        ↓                                         ↓
┌──────────────────┐                  ┌──────────────────┐
│  SUPER USER      │                  │  NORMAL USER     │
│  dev@igny8.com   │                  │  paid2@paid.com  │
│                  │                  │                  │
│  Role: developer │                  │  Role: owner     │
│  Superuser: True │                  │  Superuser: False│
│  Account:        │                  │  Account:        │
│  AWS Admin       │                  │  Paid 2          │
└──────────────────┘                  └──────────────────┘
        │                                         │
        │ Can access & modify                     │ Cannot access
        │ Integration Settings                    │ Integration Settings
        │                                         │
        ↓                                         ↓
┌──────────────────┐                  ┌──────────────────┐
│  FRONTEND:       │                  │  FRONTEND:       │
│  Settings →      │                  │  (No access to   │
│  Integration     │                  │   settings page) │
│  Page            │                  │                  │
└──────────────────┘                  └──────────────────┘
                                                  │
                                                  │ Uses AI functions
                                                  ↓
                                      ┌──────────────────────┐
                                      │  BACKEND:            │
                                      │  get_model_config()  │
                                      │  Falls back to       │
                                      │  aws-admin settings  │
                                      └──────────────────────┘
```

### 2. Current Database State

**AWS Admin Account Integration Settings:**
- **OpenAI**: Active, has API key, model: gpt-4o-mini
- **Runware**: Active, has API key
- **Image Generation**: Active, no API key (uses OpenAI/Runware settings)

**Normal User Accounts:**
- Have NO integration settings in database
- Use aws-admin settings via fallback

### 3. Permission Architecture

**IntegrationSettingsViewSet:**
```python
permission_classes = [
    IsAuthenticatedAndActive,    # Must be logged in and active
    HasTenantAccess,              # Must have account
    IsSystemAccountOrDeveloper    # Must be superuser/developer/system user
]
```

**Who Can Access:**
- ✅ dev@igny8.com (superuser=True, role=developer)
- ❌ paid2@paid.com (superuser=False, role=owner)

**Exception - task_progress endpoint:**
```python
@action(..., permission_classes=[IsAuthenticatedAndActive])
def task_progress(self, request, task_id=None):
```
- ✅ All authenticated users can check task progress

### 4. How Normal Users Use System API Keys

**Flow:**
1. Normal user calls AI function (auto_cluster, generate_ideas, etc.)
2. Backend calls `get_model_config(function_name, account)`
3. Function checks user's account for IntegrationSettings
4. **User account has no settings → Fallback triggered**
5. Checks system accounts in order: `aws-admin` → `default-account` → `default`
6. Uses aws-admin account's OpenAI settings
7. AI function executes with system API key

**Code Reference:** `backend/igny8_core/ai/settings.py` lines 54-72

### 5. Your Questions Answered

**Q: What is super user relation for integration config which are globally used?**

**A:** Super user (dev@igny8.com) belongs to AWS Admin account. Integration settings are stored per-account in the database:
- AWS Admin account has the integration settings
- Super user can access/modify these via Integration Settings page in frontend
- These settings are "globally used" because ALL normal users fall back to them

**Q: Do we have to use only backend Django admin to make changes?**

**A:** No! You have TWO options:

1. **Frontend Integration Settings Page** (Recommended)
   - Login as dev@igny8.com
   - Go to Settings → Integration
   - Modify OpenAI/Runware settings
   - Changes saved to IntegrationSettings model for aws-admin account

2. **Django Admin** (Alternative)
   - Access: http://api.igny8.com/admin/
   - Navigate to System → Integration Settings
   - Find aws-admin account settings
   - Modify directly

**Q: Can normal users access integration settings?**

**A:** Currently: **NO** (by design)

The permission class `IsSystemAccountOrDeveloper` blocks normal users from:
- Viewing integration settings page
- Modifying API keys
- Testing connections

Normal users transparently use system API keys via fallback.

### 6. Current Issues You Mentioned

**Issue 1: "Super user is now unable to change settings"**

**Status:** This should work! Let me verify:
- dev@igny8.com has is_superuser=True ✓
- dev@igny8.com has role=developer ✓
- Permission class allows superuser/developer ✓

**Possible causes if not working:**
- Frontend routing issue (Integration page not accessible)
- Permission check failing due to HasTenantAccess
- Frontend not sending proper Authorization header

**Issue 2: "There are some wrong configs in aws-admin integration services"**

**Current Config:**
```json
OpenAI:
  - model: "gpt-4o-mini"
  - active: true
  - has API key: true

Runware:
  - active: true
  - has API key: true

Image Generation:
  - active: true
  - has API key: false  ← WRONG! Should use OpenAI or Runware key
```

**Fix needed:** Image generation settings should reference OpenAI or Runware, not have its own API key field.

### 7. Recommendations

**Option A: Keep Current Architecture (Recommended)**
- Super user controls all API keys via AWS Admin account
- Normal users transparently use system keys
- Simple, centralized control
- **Action needed:**
  1. Verify super user can access Integration Settings page
  2. Fix image_generation config (remove apiKey field, ensure provider is set)
  3. Test that normal users can use AI functions

**Option B: Allow Per-Account API Keys**
- Each account can configure their own API keys
- Fallback to system if not configured
- More complex, but gives users control
- **Action needed:**
  1. Remove IsSystemAccountOrDeveloper from viewset
  2. Add UI to show "using system defaults" vs "custom keys"
  3. Update get_model_config to prefer user keys over system

**Option C: Hybrid Approach**
- Normal users can VIEW system settings (read-only)
- Only super users can MODIFY
- Allows transparency without risk
- **Action needed:**
  1. Create separate permission for view vs modify
  2. Update frontend to show read-only view for normal users

### 8. Verification Commands

**Check if super user can access Integration Settings:**
```bash
# Login as dev@igny8.com in frontend
# Navigate to Settings → Integration
# Should see OpenAI/Runware/Image Generation tabs
```

**Check integration settings in database:**
```bash
docker compose exec -T igny8_backend python manage.py shell <<'EOF'
from igny8_core.modules.system.models import IntegrationSettings
from igny8_core.auth.models import Account

aws = Account.objects.get(slug='aws-admin')
for s in IntegrationSettings.objects.filter(account=aws):
    print(f"{s.integration_type}: active={s.is_active}, has_key={bool(s.config.get('apiKey'))}")
EOF
```

**Test normal user AI function access:**
```bash
# Login as paid2@paid.com
# Try auto_cluster on keywords
# Should work using aws-admin OpenAI key
```

### 9. Next Steps

Based on your needs, tell me:

1. **Can dev@igny8.com access the Integration Settings page in the frontend?**
   - If NO: We need to debug permission/routing issue
   - If YES: Proceed to fix wrong configs

2. **What wrong configs need to be fixed in aws-admin integration?**
   - Specific model versions?
   - API key rotation?
   - Image generation settings?

3. **Do you want to keep current architecture (super user only) or allow normal users to configure their own keys?**

I'm ready to help fix specific issues once you clarify the current state and desired behavior.
