# GymFlow Application Requirements Specification

## 1. Introduction
This document serves as the authoritative source of truth for the GymFlow application functionality. It is derived from a deep analysis of the production codebase (React frontend + Node.js/Prisma backend). These requirements are intended to guide future development and serve as the basis for automated test generation (Playwright).

## 2. System Actors
*   **Guest**: An unauthenticated user (restricted to Login/Register).
*   **User**: A standard authenticated user with access to tracking, plans, and capabilities.
*   **Admin**: A super-user with additional privileges to manage other users (block, delete, reset passwords).

---

## 3. Functional Requirements

### 3.1. Authentication & Integrity
The system relies on JWT-based authentication.

*   **3.1.1 Login**
    *   **Input**: Email, Password.
    *   **Logic**:
        *   Must validate email existence.
        *   Must validate password matches hash.
        *   **Block Check**: Must prevent login if `User.isBlocked` is true, returning a 403 error.
    *   **UI**:
        *   Show "Invalid credentials" on failure.
        *   Redirect to Tracker upon success.
        *   **Language Toggle**: User must be able to switch between English (EN) and Russian (RU) before logging in.
*   **3.1.2 Registration**
    *   **Input**: Email, Password.
    *   **Logic**:
        *   Email must be unique.
        *   Creates a `UserProfile` with default values (e.g., default weight 70kg, default rest timer 120s) upon account creation.
        *   Sets `isFirstLogin` to true.
*   **3.1.3 First-Time Setup (Password Change)**
    *   **Trigger**: If `User.isFirstLogin` is true.
    *   **Requirement**: User must be forced to change password immediately after initial login.
    *   **Effect**: Updates `User.password` and sets `isFirstLogin` to false.
*   **3.1.4 Profile Management**
    *   **Fields**: Weight, Height, Gender, Birth Date.
    *   **Logic**:
        *   Updates to `UserProfile` table.
        *   Dates are handled as ISO strings or timestamps.

### 3.2. Workout Management (Plans)

*   **3.1.5 Default Exercises (Seeding)**
    *   **Concept**: New users are initialized with a set of default exercises.
    *   **Configuration**:
        *   The file path is defined by `DEFAULT_EXERCISES_CSV_PATH` in `.env`.
        *   Format: CSV (`name`, `type`, `bodyWeightPercentage`, `isUnilateral`).
    *   **Logic**:
        *   Upon successful registration (3.1.2), the system reads the CSV.
        *   It creates `Exercise` records in the DB linked to the new user.
        *   Failure to read/parse the CSV is non-blocking (logs an error but allows user creation).
Users can structure their training via Plans.

*   **3.2.1 Plan Creation/Editing**
    *   **Data**: Name (required), Description (optional).
    *   **Exercises**: 
        *   User selects exercises from the global/personal library.
        *   **Ordering**: Exercises must be ordered (0-indexed).
        *   **Weighted Flag**: specific exercises in a plan can be marked as `isWeighted` (visual indicator).
        *   **Rest Time**: specific exercises can have a defined `restTime` (seconds).
    *   **Logic**: Supports reordering capabilities via drag-and-drop in UI.
*   **3.2.2 Plan Deletion**
    *   Standard soft or hard delete (Cascades to PlanExercises).
*   **3.2.3 Create Plan from Session**
    *   **Trigger**: Action menu in History session.
    *   **Logic**:
        *   Creates a new Plan pre-filled with data from the selected session.
        *   **Step Generation**: Mirrors sets 1:1. Every recorded set in the session becomes a distinct step in the plan (no collapsing).
        *   **Attributes**: 
            *   `startWeight`: inherited from set. 
            *   `restTime`: uses User's default rest timer setting.
            *   `isWeighted`: true if the specific set had weight > 0.

*   **3.2.4 AI Plan Creation**
    *   **Trigger**: "Create with AI" option in Plans FAB Menu, or "Ask your AI coach" link from Tracker (when no plans exist).
    *   **UI Flow**:
        *   Opens a dedicated Side Sheet in the Plans view.
        *   **Inputs**:
            *   **Duration**: Slider (5 min to 2+ hours, 5 min step). Default 60 min.
            *   **Equipment**: Selector (No equipment, Essentials, Free weights, Complete gym). Default "No equipment".
            *   **Level**: Selector (Beginner, Intermediate, Advanced). Default "Intermediate".
            *   **Intensity**: Selector (Low, Moderate, High). Default "Moderate".
            *   **Additional Constraints**: Textarea (optional).
        *   **Action**: "Generate" button initiates AI call.
        *   **Preview**: Displays generated plan table. User can "Generate" again to retry, or "Save Plan" to finalize.
    *   **AI Logic**:
        *   System sends structured prompt to AI service (`geminiService`) embedding all parameters.
        *   **Naming Rules**:
            *   Exercise names must NOT contain "Weighted" (use `isWeighted` flag).
            *   Exclude variants (e.g. "or ...") and form notes.
        *   **Structure**: Each item in list = ONE set.
        *   AI returns JSON with `name`, `description`, `exercises` (with `type`, `unilateral` for new ones).
    *   **Result**: Saves the generated `WorkoutPlan` to DB and displays it in the Plans list.

### 3.3. Exercise Library
*   **3.3.1 Exercise Types**
    The system supports distinct exercise types which dictate valid data entry fields:
    *   `STRENGTH`: Requires **Weight (kg)** and **Reps**.
    *   `BODYWEIGHT`: Requires **Reps** (and optional added Weight).
    *   `CARDIO`: Requires **Duration (s)** and **Distance (m)**.
    *   `STATIC`: Requires **Duration (s)**.
    *   `HIGH_JUMP`: Requires **Height (cm)**.
    *   `LONG_JUMP`: Requires **Distance (m)**.
    *   `PLYOMETRIC`: Requires **Reps**.
*   **3.3.2 Custom Exercises**
    *   User can create new exercises.
    *   **Unilateral Flag**: Boolean flag `isUnilateral`. If true, sets recorded for this exercise can specify a `side` (LEFT/Right/ALTERNATELY or L/R/A in UI).
    *   **Side Editing**: Users must be able to edit the side (checking L/A/R) in Active Session, History, and Quick Log modes.
    *   **Bodyweight %**: For bodyweight-based calculations.

### 3.4. Workout Tracking (The "Tracker")
The core feature. States: **Idle**, **Active Session**, **Sporadic Mode**.

*   **3.4.0 Idle State (Visuals)**
    *   **Days Off Logic**:
        *   Displays "Do your very first workout today." for new users (0 workouts).
        *   Displays "Last workout: Today" if `endTime` of last standard session was today.
        *   Displays "Days off training: N" otherwise.
    *   **Color Coding**:
        *   **1 Day**: Green.
        *   **2-4 Days**: Gradient (Green to Red).
        *   **5+ Days**: Red.
    *   **Constraint**: The text "Ready?" must NOT be displayed.

*   **3.4.1 Active Session (Standard)**
    *   **Initiation**:
        *   Can start "Free Workout" (no plan).
        *   Can start from a "Plan".
        *   **Input**: User confirms current Body Weight before starting.
        *   **Constraint**: User cannot have more than one active standard session (where `endTime` is null). API returns 400 if one exists.
    *   **The "Active" State**:
        *   **Persistence**: Session remains active in DB if browser is closed. `GET /sessions/active` restores state.
        *   **Timer**: Client-side logic calculates `now - startTime`.
    *   **Logging Sets**:
        *   **Input**: Exercise, Metrics (Weight/Reps/etc. based on Type), Side (if unilateral).
        *   **Smart Matching**: If a Plan is active, the system attempts to match the logged set to the current step in the plan based on the exercise ID and the number of sets already performed vs. planned.
        *   **Response**: Returns the created set and the `activeExerciseId` (for UI to auto-advance focus in plan).
    *   **Session Termination**:
        *   **Finish**: Updates `endTime` to now.
            *   **Profile Sync**: If the session had a `userBodyWeight` set, it updates the `UserProfile.weight`.
        *   **Quit (No Save)**:
            *   **Destructive Action**: Hard deletes the `WorkoutSession` and all associated `WorkoutSets` from the DB.
*   **3.4.2 Active Session (Quick Log)**
    *   **Concept**: A special session type (`QUICK_LOG`) that aggregates all sporadic sets for a single day.
    *   **Logic**:
        *   `GET /sessions/quick-log`: Finds strictly one session for the current calendar day (00:00-23:59 local server time) of type `QUICK_LOG`.
        *   `POST /sessions/quick-log/set`:
            *   Finds OR Creates the daily Quick Log session.
            *   Appends the set.
    *   **UI**: Separate "Sporadic Mode" view specialized for fast, one-off entries without a timer or plan context. Matches "Free Session" timer logic (see 3.4.3).

*   **3.4.3 Rest Timer**
    *   **Concept**: A configurable timer to track rest periods between sets.
    *   **Contexts**:
        *   **Free Session / Quick Log**:
            *   Manual setup.
            *   Default value: 2 minutes (120s).
            *   **Persistence**: The last manually set value becomes the new default for the user.
        *   **Planned Session**:
            *   **Config**: Each step in a plan can have a specific `restTime` (seconds).
            *   **Auto-Set**: When a set is logged, the timer RESETS (updates duration) to the value defined for the *current* step, but does **NOT** start automatically.
            *   **Fallback**: If plan step has no `restTime`, use User's default.
    *   **Behavior**:
        *   **Start**: Manual trigger by user (NEVER auto-starts).
        *   **Edit Value**:
            *   **Input**: Manual entry via FAB expand menu.
            *   **Format**: Strict "MM:SS" format (digits and colon only).
            *   **Constraints**: Max value `99:59`. Seconds > 59 are automatically clamped to 59.
            *   **Alignment**: Digits are right-aligned; input width is fixed to tightly fit `00:00`.
        *   **Countdown**: Visual display.
        *   **Completion**:
            *   Audio signal (3 seconds).
            *   Visual alert (Red color for 3 seconds).
            *   Auto-reset to next expected rest time.
    *   **UI Component**:
        *   Floating Action Button (FAB).
        *   **Idle**: Green Icon.
        *   **Running**: Shows digits.
        *   **Finished**: Red animation.


### 3.5. History & Analysis
*   **3.5.1 Session History**
    *   Displays all finished sessions.
    *   Groups by Date.
    *   **Quick Logs**: Displayed alongside standard workouts, identifiable by type.
*   **3.5.2 Statistics**
    *   Visualizes progress over time.
    *   **Key Metrics**: Volume (Weight * Reps), Frequency, Body Weight trends.
*   **3.5.3 Data Export**
    *   **Trigger**: "Export CSV" button in History view.
    *   **Logic**:
        *   Generates a denormalized CSV file containing all workout history.
        *   **Structure**: One row per set.
        *   **Columns**: Includes session attributes (time, plan, note, bodyweight) and set attributes (exercise details, metrics, side, linked exercise flags).
    *   **Output**: Browser download of a `.csv` file.

### 3.6. User Interface Logic
*   **3.6.1 Navigation**
    *   **Mobile**: Bottom navigation bar.
    *   **Desktop**: Side rail navigation.
    *   **Responsiveness**: Main layout container adapts padding/margins based on viewport breakpoint.
*   **3.6.2 Input Behavior**
    *   **Search**: Exercise selectors must support text search filtering.
    *   **Auto-Clear**: Search inputs should clear/select text on focus for rapid entry.

### 3.7. Admin Capabilities
Accessible only if `User.role === 'ADMIN'`.

*   **User List**: View all registered users (showing Block status, First Login status).
*   **Actions**:
    *   **Toggle Block**: Ban/Unban access.
    *   **Delete User**: Permanent removal.
    *   **Reset Password**: Admin can manually trigger password reset flows.

### 3.8. AI Coach
- **Conversational Interface**: Chat-like interface for asking fitness-related questions.
- **Context Awareness**: Access to user's workout history and profile for personalized advice.
- **RAG Integration**: Retrieval Augmented Generation using recent workout logs.
- **Plan Generation**: Ability to generate structured workout plans based on user prompt.
- **Markdown Support**: Rich text formatting for AI responses (bold, lists, code blocks).
- **Bookmarking**: Users can save helpful AI messages for later reference.
- **History Persistence**: Chat history is preserved locally across reloads.

## 4. Technical Constants & Constraints
*   **Database**: SQLite (via Prisma).
*   **API Schema**: REST-like (JSON).
*   **Timezones**: Dates stored as UTC in DB, displayed in Local Time on client.
*   **Offline Mode**: Currently NOT supported (requires active connection for mutations).
