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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
# Feature: User Dashboard - Architecture Refactor Proposal

## Overview

This document outlines the refactored architecture for the `feature/user-dashboard` module, which includes:
1. **Subscription Status Display** - Show premium status, renewal dates, upgrade options
2. **Custom Deck Creation** - AI-generated word pools for personalized games
3. **Invite Link Generator** - Create shareable room invite links

The architecture strictly enforces modularity, separation of concerns, and scalability.

---

## Recommended File Tree Structure

```
wordGame/
β”œβ”€β”€ ... (existing files)
└── features/
    └── user_dashboard/
        β”œβ”€β”€ __init__.py                    # Package initialization, router registration
        β”œβ”€β”€ router.py                      # API route definitions (max 50 lines)
        β”‚
        β”œβ”€β”€ services/                      # Business logic layer
        β”‚   β”œβ”€β”€ __init__.py
        β”‚   β”œβ”€β”€ subscription_service.py    # Subscription status, billing info
        β”‚   β”œβ”€β”€ deck_service.py            # AI deck generation logic
        β”‚   └── invite_service.py          # Invite link creation & validation
        β”‚
        β”œβ”€β”€ repositories/                  # Data access layer
        β”‚   β”œβ”€β”€ __init__.py
        β”‚   β”œβ”€β”€ subscription_repo.py       # DB queries for subscriptions
        β”‚   β”œβ”€β”€ deck_repo.py               # DB queries for decks
        β”‚   └── invite_repo.py             # DB queries for invites
        β”‚
        β”œβ”€β”€ schemas/                       # Pydantic models for validation
        β”‚   β”œβ”€β”€ __init__.py
        β”‚   β”œβ”€β”€ subscription_schemas.py    # Request/Response models
        β”‚   β”œβ”€β”€ deck_schemas.py
        β”‚   └── invite_schemas.py
        β”‚
        β”œβ”€β”€ utils/                         # Shared utilities
        β”‚   β”œβ”€β”€ __init__.py
        β”‚   β”œβ”€β”€ link_generator.py          # Secure token/link generation
        β”‚   β”œβ”€β”€ ai_prompt_builder.py       # AI prompt construction
        β”‚   └── validators.py              # Input validation helpers
        β”‚
        └── templates/                     # Feature-specific templates
            β”œβ”€β”€ __init__.py                # (optional, for template config)
            β”œβ”€β”€ dashboard.html             # Main dashboard layout
            β”œβ”€β”€ subscription_panel.html    # Subscription status component
            β”œβ”€β”€ deck_creator.html          # Deck creation UI
            └── invite_generator.html      # Invite link generator UI
```

---

## File Responsibilities & Line Limits

### Core Module Files

#### `__init__.py` (max 30 lines)
```python
# Purpose: Package initialization and router registration
# Responsibilities:
#   - Import and expose the router
#   - Define module metadata
#   - Optional: Register middleware specific to this feature
from .router import router

__all__ = ["router"]
```

#### `router.py` (max 50 lines)
```python
# Purpose: API endpoint definitions
# Responsibilities:
#   - Define all HTTP routes for the dashboard
#   - Delegate to service layer (NO business logic)
#   - Handle request validation via schemas
#   - Return appropriate HTTP responses
# Routes:
#   GET  /dashboard              - Main dashboard page
#   GET  /dashboard/subscription - Subscription status
#   POST /dashboard/deck         - Create new AI deck
#   GET  /dashboard/deck/{id}    - Get deck details
#   POST /dashboard/invite       - Generate invite link
#   GET  /dashboard/invite/{code} - Validate/redeem invite
```

---

### Services Layer (`services/`)

#### `subscription_service.py` (max 150 lines)
```python
# Purpose: Subscription business logic
# Responsibilities:
#   - Check subscription status (active, expired, trial)
#   - Calculate renewal dates
#   - Determine upgrade/downgrade eligibility
#   - Format subscription data for display
#   - Handle subscription cancellation logic
# Dependencies: subscription_repo, utils/validators
# Does NOT: Direct DB access (uses repo), HTML generation
```

#### `deck_service.py` (max 180 lines)
```python
# Purpose: AI deck generation business logic
# Responsibilities:
#   - Build AI prompts based on user preferences
#   - Process AI API responses
#   - Validate generated word pools
#   - Manage deck lifecycle (create, update, delete)
#   - Enforce deck limits based on subscription tier
# Dependencies: deck_repo, ai_prompt_builder, validators
# Does NOT: Direct DB access, AI API calls (abstracted), HTML generation
```

#### `invite_service.py` (max 120 lines)
```python
# Purpose: Invite link business logic
# Responsibilities:
#   - Generate unique, secure invite codes
#   - Set expiration policies
#   - Track invite usage statistics
#   - Validate invite codes
#   - Handle invite redemption logic
# Dependencies: invite_repo, link_generator, validators
# Does NOT: Direct DB access, HTML generation
```

---

### Repositories Layer (`repositories/`)

#### `subscription_repo.py` (max 100 lines)
```python
# Purpose: Subscription data access
# Responsibilities:
#   - Query user subscription from Supabase
#   - Update subscription status
#   - Cache subscription data (optional)
#   - Handle data transformation from DB format
# Dependencies: database.py (supabase client)
# Does NOT: Business logic, validation beyond DB constraints
```

#### `deck_repo.py` (max 120 lines)
```python
# Purpose: Deck data access
# Responsibilities:
#   - CRUD operations for custom decks
#   - Query decks by user, category, date
#   - Store AI-generated word pools
#   - Handle deck-word relationships
# Dependencies: database.py
# Does NOT: Business logic, AI processing
```

#### `invite_repo.py` (max 80 lines)
```python
# Purpose: Invite data access
# Responsibilities:
#   - Store invite codes with metadata
#   - Track usage (used_by, used_at)
#   - Query active/expired invites
#   - Soft-delete expired invites
# Dependencies: database.py
# Does NOT: Business logic, code generation
```

---

### Schemas Layer (`schemas/`)

#### `subscription_schemas.py` (max 80 lines)
```python
# Purpose: Subscription data validation
# Models:
#   - SubscriptionResponse (id, status, renewal_date, tier)
#   - UpgradeRequest (target_tier)
#   - CancelSubscriptionResponse
```

#### `deck_schemas.py` (max 100 lines)
```python
# Purpose: Deck data validation
# Models:
#   - DeckCreateRequest (category, difficulty, word_count, ai_params)
#   - DeckResponse (id, name, words, created_at, word_count)
#   - DeckListResponse (decks: list[DeckResponse], total)
```

#### `invite_schemas.py` (max 60 lines)
```python
# Purpose: Invite data validation
# Models:
#   - InviteCreateRequest (room_id, expires_in_hours)
#   - InviteResponse (code, url, expires_at, max_uses)
#   - InviteValidateResponse (valid, room_info, creator)
```

---

### Utilities Layer (`utils/`)

#### `link_generator.py` (max 80 lines)
```python
# Purpose: Secure link/code generation
# Responsibilities:
#   - Generate cryptographically secure tokens
#   - Create URL-safe invite codes
#   - Encode/decode invite payloads
#   - Validate code format
# Does NOT: Database operations, business rules
```

#### `ai_prompt_builder.py` (max 100 lines)
```python
# Purpose: AI prompt construction
# Responsibilities:
#   - Build structured prompts for word generation
#   - Include category-specific constraints
#   - Format user preferences into prompt context
#   - Parse and validate AI responses
# Does NOT: API calls, database operations
```

#### `validators.py` (max 100 lines)
```python
# Purpose: Shared validation utilities
# Responsibilities:
#   - Validate user IDs, room codes
#   - Check date ranges, expiration
#   - Validate word format (length, characters)
#   - Common input sanitization
# Does NOT: Business logic, DB queries
```

---

### Templates Layer (`templates/`)

#### `dashboard.html` (max 100 lines)
```html
<!-- Purpose: Main dashboard layout -->
<!-- Includes: Navigation, user greeting, feature summary cards -->
<!-- Loads: subscription_panel, deck_creator, invite_generator via HTMX -->
```

#### `subscription_panel.html` (max 80 lines)
```html
<!-- Purpose: Subscription status display -->
<!-- Shows: Current tier, renewal date, upgrade button, usage stats -->
<!-- Actions: Upgrade, cancel, view billing -->
```

#### `deck_creator.html` (max 120 lines)
```html
<!-- Purpose: AI deck creation UI -->
<!-- Form: Category selection, difficulty, word count, custom params -->
<!-- Display: Generated deck preview, save button -->
```

#### `invite_generator.html` (max 80 lines)
```html
<!-- Purpose: Invite link generation UI -->
<!-- Form: Room selection, expiration settings -->
<!-- Display: Generated link, copy button, usage stats -->
```

---

## Data Flow Diagrams

### Subscription Status Flow
```
User Request  router.py (GET /dashboard/subscription)
     subscription_service.get_status(user_id)
         subscription_repo.fetch_subscription(user_id)
             Supabase DB
         subscription_service.format_response(data)
     router.py returns JSON/HTML
```

### Deck Creation Flow
```
User Request  router.py (POST /dashboard/deck)
     deck_schemas.DeckCreateRequest.validate(data)
     deck_service.create_deck(user_id, params)
         ai_prompt_builder.build_prompt(params)
         [AI API Call - external service]
         deck_service.validate_words(ai_response)
         deck_repo.save_deck(user_id, words)
             Supabase DB
     router.py returns DeckResponse
```

### Invite Generation Flow
```
User Request  router.py (POST /dashboard/invite)
     invite_schemas.InviteCreateRequest.validate(data)
     invite_service.generate_invite(user_id, room_id, expires)
         link_generator.create_secure_code()
         invite_repo.save_invite(code, metadata)
             Supabase DB
         invite_service.build_invite_url(code)
     router.py returns InviteResponse
```

---

## Scalability Considerations

### Adding New Pool Types
1. Create new schema in `schemas/deck_schemas.py` (e.g., `CustomPoolParams`)
2. Extend `ai_prompt_builder.py` with new prompt templates
3. Add validation rules in `utils/validators.py`
4. **No changes needed** to existing services or repos

### Adding Analytics
1. Create `services/analytics_service.py`
2. Create `repositories/analytics_repo.py`
3. Create `schemas/analytics_schemas.py`
4. Add routes to `router.py`
5. **No changes needed** to existing services

### Adding New Subscription Tiers
1. Update `schemas/subscription_schemas.py` with new tier enum
2. Update `services/subscription_service.py` tier logic
3. **No changes needed** to repos or routers

---

## File Size Enforcement Strategy

If any file approaches 200 lines:

### For Services
- Extract helper functions to `utils/`
- Split by aggregate root (e.g., `deck_service.py`  `deck_create_service.py`, `deck_manage_service.py`)
- Move complex validation to `utils/validators.py`

### For Repositories
- Split by query complexity (simple queries vs. complex joins)
- Extract query builders to separate modules

### For Templates
- Extract reusable components to `templates/components/`
- Use HTMX to load partial views

---

## Integration with Existing Codebase

### Main Application (`main.py`)
```python
# Add to imports
from features.user_dashboard import router as dashboard_router

# Add to app setup
app.include_router(dashboard_router, prefix="/dashboard")
```

### Database (`database.py`)
- No changes needed - existing supabase client is reused

### Authentication
- Reuse existing `get_current_user` from `main.py`
- Add as dependency to dashboard routes

---

## Testing Strategy

```
tests/
└── features/
    └── user_dashboard/
        β”œβ”€β”€ test_subscription_service.py
        β”œβ”€β”€ test_deck_service.py
        β”œβ”€β”€ test_invite_service.py
        β”œβ”€β”€ test_link_generator.py
        └── test_ai_prompt_builder.py
```

**Key Testing Principles:**
- Unit tests for services (mock repos)
- Integration tests for repos (test DB queries)
- Schema validation tests
- Utility function tests

---

## Migration Plan

### Phase 1: Foundation
1. Create directory structure
2. Implement `schemas/` layer
3. Implement `utils/` layer
4. Set up basic `router.py` skeleton

### Phase 2: Data Layer
1. Implement `repositories/` layer
2. Create database tables (if needed)
3. Write repository tests

### Phase 3: Business Logic
1. Implement `services/` layer
2. Write service tests
3. Integrate with existing auth

### Phase 4: UI Layer
1. Create templates
2. Wire up HTMX interactions
3. Test user flows

### Phase 5: Integration
1. Register router in `main.py`
2. End-to-end testing
3. Deploy to staging

---

## Summary

This architecture provides:
-  **Separation of Concerns**: Clear layers (routes  services  repos  DB)
-  **Single Responsibility**: Each file has one well-defined purpose
-  **Scalability**: Easy to add new features without modifying existing code
-  **Maintainability**: Files stay under 200 lines through logical splitting
-  **Testability**: Each layer can be tested in isolation
-  **Reusability**: Utilities can be shared across features

The structure follows clean architecture principles while remaining pragmatic for a FastAPI application.