# Model/Service Architecture Implementation Plan ## Overview This document outlines the implementation plan for building a unified model/service architecture across the Paper Dynasty application, with primary focus on the Discord bot component which serves as the local cache for API data during gameplay. ## Current State Analysis ### PostgreSQL Models (Discord Bot) - **Location**: `in_game/gameplay_models.py` - **Framework**: SQLModel-based with ~20+ domain models - **Core Entities**: `Game`, `Team`, `Player`, `Card`, `Lineup`, `Play`, `ManagerAi` - **Features**: Complex relationships, proper foreign keys, cascading deletes - **Purpose**: Local cache for API data during gameplay sessions ### Existing Service Patterns - **API Layer**: `api_calls.py` - HTTP requests to FastAPI backend - **Data Cache**: `in_game/data_cache.py` - Dataclass wrappers for API responses - **Query Layer**: `in_game/gameplay_queries.py` - SQLModel query functions - **Legacy DB**: `db_calls_gameplay.py` - Peewee-based patterns (to be deprecated) ### Current Data Flow ``` FastAPI Database → HTTP API → Local PostgreSQL Cache → Game Logic ``` ## Proposed Architecture ### Directory Structure ``` models/ # Domain models (refactored from gameplay_models.py) ├── base.py # Base model classes and mixins ├── game.py # Game-related models ├── player.py # Player/Card models ├── team.py # Team models └── stats.py # Statistics models services/ # Business logic layer ├── base.py # Base service class with common patterns ├── game_service.py # Game management operations ├── team_service.py # Team operations ├── card_service.py # Card/Player operations └── cache_service.py # Data synchronization with API repositories/ # Data access layer ├── base.py # Base repository with CRUD operations ├── game_repo.py # Game-specific queries ├── team_repo.py # Team-specific queries └── player_repo.py # Player/Card queries ``` ## Implementation Phases ### Phase 1: Service Layer Foundation (Weeks 1-2) **Objectives:** - Create base service/repository classes - Extract existing `gameplay_queries.py` into proper service modules - Establish consistent patterns for dependency injection **Tasks:** 1. Create `services/base.py` with common service patterns 2. Create `repositories/base.py` with CRUD operations 3. Extract game operations from `gameplay_queries.py` → `services/game_service.py` 4. Extract team operations → `services/team_service.py` 5. Extract player/card operations → `services/card_service.py` 6. Create comprehensive unit tests for new service layer **Files to Create:** - `services/__init__.py` - `services/base.py` - `services/game_service.py` - `services/team_service.py` - `services/card_service.py` - `repositories/__init__.py` - `repositories/base.py` - `repositories/game_repo.py` - `repositories/team_repo.py` - `repositories/player_repo.py` **Success Criteria:** - All existing queries moved to appropriate services - Service classes follow consistent patterns - 100% test coverage for new service layer - No breaking changes to existing cog functionality ### Phase 2: Model Refactoring (Weeks 3-4) **Objectives:** - Refactor existing models with base classes - Add proper validation and optimize relationships - Implement model mixins for shared behavior **Tasks:** 1. Create `models/base.py` with base model classes 2. Split `gameplay_models.py` into logical modules: - `models/game.py` - Game, Play, GameCardsetLink - `models/team.py` - Team, Lineup, RosterLink - `models/player.py` - Player, Card, PositionRating - `models/stats.py` - BattingCard, PitchingCard, Scouting models 3. Add base mixins for common fields (timestamps, soft deletes) 4. Optimize database indexes and constraints 5. Update all imports across the codebase 6. Run full test suite to ensure no regressions **Files to Modify:** - `in_game/gameplay_models.py` → Split into `models/` directory - All files importing from `gameplay_models.py` - Database migration files **Success Criteria:** - Models follow consistent inheritance patterns - All relationships properly defined with optimized queries - Database performance maintained or improved - Zero test failures after refactoring ### Phase 3: Service Integration (Weeks 5-6) **Objectives:** - Replace direct SQLModel queries in cogs with service calls - Implement proper transaction management and error handling - Add caching strategies at service level **Tasks:** 1. Refactor `cogs/gameplay.py` to use service layer 2. Refactor `cogs/players/` modules to use services 3. Refactor `command_logic/logic_gameplay.py` 4. Implement service dependency injection in cogs 5. Add comprehensive error handling with proper exception types 6. Implement service-level caching for frequently accessed data 7. Add logging and monitoring to service operations **Files to Modify:** - `cogs/gameplay.py` - `cogs/players/*.py` - `command_logic/logic_gameplay.py` - `in_game/ai_manager.py` - `in_game/game_helpers.py` **Success Criteria:** - No direct database access in cogs (all through services) - Proper error handling and transaction management - Improved performance through service-level caching - All existing functionality preserved ### Phase 4: API Synchronization & Optimization (Weeks 7-8) **Objectives:** - Build unified data sync service for API ↔ PostgreSQL cache - Implement background sync tasks and health checks - Add performance monitoring and optimization **Tasks:** 1. Create `services/cache_service.py` for API synchronization 2. Implement background tasks for data freshness 3. Add conflict resolution for concurrent modifications 4. Create health check endpoints for data consistency 5. Implement performance monitoring and alerting 6. Add database connection pooling optimization 7. Create data migration utilities for schema changes **Files to Create:** - `services/cache_service.py` - `services/sync_service.py` - `monitoring/health_checks.py` - `monitoring/performance_metrics.py` **Success Criteria:** - Automatic data synchronization with API - Health monitoring and alerting in place - Performance metrics collection - Zero data consistency issues ## Migration Strategy ### Backwards Compatibility - All changes will maintain backwards compatibility during transition - Original `gameplay_models.py` will remain until Phase 2 completion - Gradual migration with feature flags for rollback capability ### Testing Strategy - Comprehensive unit tests for all new service classes - Integration tests for service layer interactions - Performance tests to ensure no regressions - Load tests for cache synchronization under heavy gameplay ### Rollback Plan - Each phase can be independently rolled back - Feature flags allow selective activation of new architecture - Database migrations are reversible - Monitoring alerts for performance degradation ## Benefits ### Separation of Concerns - Clear boundaries between models, business logic, and data access - Easier to reason about and maintain code - Reduced coupling between components ### Testability - Service layer can be easily mocked and tested - Better unit test coverage and reliability - Faster test execution with mocked dependencies ### Maintainability - Centralized business logic and consistent patterns - Easier onboarding for new developers - Reduced code duplication ### Performance - Optimized queries and caching strategies - Better database connection management - Reduced API calls through intelligent caching ### Scalability - Easy to extend with new features and models - Prepared for microservice architecture if needed - Better resource utilization ## Timeline - **Total Duration**: 8 weeks - **Phase 1**: Weeks 1-2 (Foundation) - **Phase 2**: Weeks 3-4 (Model Refactoring) - **Phase 3**: Weeks 5-6 (Service Integration) - **Phase 4**: Weeks 7-8 (Optimization) ## Risk Mitigation ### Technical Risks - **Database Performance**: Continuous monitoring during migration - **Data Consistency**: Comprehensive testing and validation - **Breaking Changes**: Gradual migration with backwards compatibility ### Timeline Risks - **Scope Creep**: Clear phase boundaries and success criteria - **Testing Overhead**: Automated testing pipeline - **Integration Issues**: Early integration testing and validation ## Success Metrics - Zero downtime during migration - Performance maintained or improved (< 5% regression acceptable) - 100% test coverage for new architecture - Reduced average development time for new features by 30% - Improved code maintainability score (SonarQube metrics) --- *This plan serves as the foundation for modernizing the Paper Dynasty architecture while maintaining stability and performance during the transition.*