# 5. Building Block View

### 5.1 Whitebox Overall System

The Rail Game system is structured as a client-server architecture with the following top-level building blocks:

- **Frontend Application**: Browser-based React SPA handling user interface and interactions
- **Backend API**: Python-based RESTful API server managing game logic and data access
- **Database**: PostgreSQL with PostGIS for persistent storage and spatial queries
- **External Services**: OpenStreetMap and other third-party APIs for map data and additional features

```mermaid
graph TD
    A[Frontend Application] -->|REST API| B[Backend API]
    B -->|SQL Queries| C[Database]
    B -->|API Calls| D[External Services]
    A -->|Map Tiles| D
```

### 5.2 Level 1 Building Blocks

#### 5.2.1 Frontend Application

**Responsibility**: Provides the user interface for railway network building, management, and visualization.

**Interfaces**:

- User interactions via browser
- RESTful API calls to Backend API
- Integration with Leaflet for map rendering

**Key Components**:

- Map View: Displays railway networks and allows interaction
- Network Builder: Tools for creating and editing railway tracks and stations
- Dashboard: User profile, resources, and game statistics
- Authentication UI: Login, registration, and profile management

#### 5.2.2 Backend API

**Responsibility**: Handles game logic, data processing, and serves as the interface between frontend and database.

**Interfaces**:

- RESTful HTTP endpoints for frontend communication
- Database connections via SQLAlchemy ORM
- Potential WebSocket connections for real-time updates

**Key Components**:

- User Management: Authentication, profiles, and sessions
- Railway Engine: Logic for network building, route calculation, and scheduling
- Game Logic: Resource management, scoring, and achievements
- Data Access Layer: Abstraction for database operations

#### 5.2.3 Database

**Responsibility**: Persistent storage of user data, railway networks, and game state.

**Interfaces**:

- SQL connections from Backend API
- Spatial queries via PostGIS extensions

**Key Components**:

- User Schema: Accounts, profiles, and authentication data
- Railway Schema: Tracks, stations, trains, and schedules
- Game Schema: Resources, achievements, and leaderboards

#### 5.2.4 External Services

**Responsibility**: Provides external data sources and integrations.

**Interfaces**:

- API calls from Backend or Frontend
- Data feeds for map tiles, geographical information, and real-time data

**Key Components**:

- OpenStreetMap: Source of map tiles and railway data
- Authentication Providers: OAuth integrations (e.g., Google, GitHub)
- Analytics Services: User tracking and performance monitoring

### 5.3 Level 2 Building Blocks

#### 5.3.1 Frontend Components

```mermaid
graph TD
    A[Map Component] -->|Leaflet| B[Toolbar Component]
    A -->|Leaflet| C[Modal Components]
    A -->|Redux| D[State Management]
```

- **Map Component**: React Leaflet-based map showing OpenStreetMap tiles with station markers and track polylines drawn from the shared network snapshot models
- **Toolbar Component**: Tools for building tracks, placing stations, and managing trains
- **Modal Components**: Dialogs for settings, confirmations, and detailed views
- **State Management**: Redux store for game state and UI state

#### 5.3.2 Backend Modules

```mermaid
graph TD
    A[API Layer] -->|REST Endpoints| B[Health Router]
    A -->|REST Endpoints| C[Network Router]
    C -->|Domain Models| D[Network Service]
    D -->|Shared Schemas| E[Frontend Data Contracts]
```

- **Health Module**: Lightweight readiness probes used by infrastructure checks.
- **Network Module**: Serves read-only snapshots of stations, tracks, and trains using shared domain models (camelCase aliases for client compatibility).
- **OSM Ingestion CLI**: Script pairings (`stations_import`/`stations_load`, `tracks_import`/`tracks_load`) that harvest OpenStreetMap fixtures and persist normalized station and track geometries into PostGIS.
- **Authentication Module**: JWT-based user registration, authentication, and authorization. The current prototype supports on-the-fly account creation backed by an in-memory user store and issues short-lived access tokens to validate the client flow end-to-end.
- **Railway Calculation Module**: Algorithms for route optimization and scheduling (planned).
- **Resource Management Module**: Logic for game economy and progression (planned).
- **Real-time Module**: WebSocket handlers for live updates (if implemented).

#### 5.3.3 Database Tables

- **Users Table**: User accounts and profile information
- **Railways Table**: User-created railway networks (spatial data)
- **Trains Table**: Train configurations and schedules
- **Stations Table**: Station locations and properties (spatial data)
- **Achievements Table**: User progress and leaderboard data

### 5.4 Project Directory Structure

The repository will be organized to mirror the logical architecture and isolate concerns between frontend, backend, infrastructure, and shared assets.

```text
rail-game/
|-- backend/
|   |-- app/
|   |   |-- api/            # FastAPI/Flask route handlers and request lifecycles
|   |   |-- core/           # Configuration, startup hooks, cross-cutting utilities
|   |   |-- models/         # SQLAlchemy models, Pydantic schemas, migrations helpers
|   |   |-- services/       # Domain services for scheduling, routing, resource logic
|   |   `-- websocket/      # Real-time transport adapters and event handlers
|   |-- tests/              # Backend unit, integration, and contract tests
|   `-- requirements/       # Dependency manifests and lockfiles per environment
|-- frontend/
|   |-- public/             # Static assets served without processing
|   |-- src/
|   |   |-- components/     # Reusable React UI components and widgets
|   |   |-- hooks/          # Custom hooks for map interaction, data fetching, state sync
|   |   |-- pages/          # Route-level views composing feature modules
|   |   |-- state/          # Redux/Context stores, slices, and middleware
|   |   |-- styles/         # Global stylesheets, design tokens, CSS modules
|   |   `-- utils/          # Frontend-only helpers for formatting and calculations
|   `-- tests/              # Component, store, and integration tests (Jest/React Testing Library)
|-- docs/                   # Architecture docs, ADRs, onboarding guides
|-- infra/                  # Docker, Terraform, CI/CD workflows, deployment manifests
|-- scripts/                # Automation for setup, linting, database tasks, data imports
|-- data/                   # Seed datasets, fixtures, export/import scripts (kept out of VCS if large)
`-- tests/                  # Cross-cutting end-to-end suites and shared test utilities
```

Shared code that spans application layers should be surfaced through well-defined APIs within `backend/app/services` or exposed via frontend data contracts to keep coupling low. Infrastructure automation and CI/CD assets remain isolated under `infra/` to support multiple deployment targets.
