# Incomplete Python to TypeScript Refactors

This document tracks all incomplete refactors from the Python backend to the TypeScript backend.

## Summary

| Category | Status | Items |
|----------|--------|-------|
| Events System | 73% complete | 85 missing functions |
| Game Loop | **90% complete** | ~~10~~ 1 missing feature (getPeakEnergy complexity) |
| Models/Classes | **90% complete** | ~~6~~ 2 missing classes (ActivityRecord, EducationRecord) |
| Handlers | 95% complete | Minor format differences |
| Intraday Activities | **95% complete** | ~~6~~ 1 difference (probability values) |
| Database | 40% complete | 15+ missing tables |

### Recent Fixes (2025-12-27)
- Added `getIntradayActivity()` and `getDailyPlan()` calls to LoopManager
- Added `parseOneTimeEvents()` hourly processing
- Fixed party location creation to use dynamic locations
- Added fifth class to student schedule
- Extended `GameLocation` interface with missing properties
- Created `OneTimeEvent` class with scheduling support
- Added weekly updates for ALL relationship characters
- Added missing Person properties: hunger, thirst, weight, pronoun, canDrive

---

## Priority 1: Critical Game Logic

### 1.1 Game Loop Missing Features

**File:** `server/src/game/engine/LoopManager.ts`

| Feature | Python Location | Status | Impact |
|---------|-----------------|--------|--------|
| `getIntradayActivity()` for all characters | `loop_manager.py:241-243` | MISSING | NPCs don't follow schedules |
| `get_dailyPlan()` daily generation | `loop_manager.py:231` | MISSING | No daily plans generated |
| `parseLocations()` hourly | `loop_manager.py:244` | MISSING | Location tracking broken |
| `parseOneTimeEvents()` hourly | `loop_manager.py:245` | MISSING | Scheduled events don't fire |
| `updateBio()` hourly | `loop_manager.py:246` | MISSING | Character bios stale |
| `sendRandomCharacterMessage()` daily | `loop_manager.py:166` | MISSING | NPCs never initiate contact |
| `handleHabitChanges()` weekly | `loop_manager.py:194` | MISSING | Habits don't progress |
| Weekly updates for ALL relationships | `loop_manager.py:182-195` | MISSING | Only main character updated |
| Messaging modifier decay | `loop_manager.py:166-178` | MISSING | NPC messaging style static |

### 1.2 Missing Model Classes

**Directory:** `server/src/models/`

| Class | Python Location | Properties | Status |
|-------|-----------------|------------|--------|
| `locationClass` | `models.py` | id, type, image, description, people | NOT IMPLEMENTED |
| `ActivityRecord` | `models.py` | id, type, dateStarted, achievements, performance, level, focus | NOT IMPLEMENTED |
| `EducationRecord` | `models.py` | extends ActivityRecord + educationLevel, location, major, minor, GPA | NOT IMPLEMENTED |
| `oneTimeEvent` | `models.py` | id, message, title, dateType, hour, completionFunc, findDate(), run_func() | NOT IMPLEMENTED |
| `scheduler` | `models.py` | id, title, executions, duration, location, conditions, days | NOT IMPLEMENTED |
| `scheduleDays` | `models.py` | daysOfWeek, hour, type | NOT IMPLEMENTED |

### 1.3 Missing Person Properties

**File:** `server/src/models/Person.ts`

```typescript
// Add these missing properties:
pronoun: string;        // "He" or "She"
hunger: number;         // 0-100
thirst: number;         // 0-100
weight: number;         // kg, default 55
weightType: string;     // from getWeightType()
avatar_settings: {      // Avatar customization
  clothing: string;
  skin_color: string;
  hair: string;
  hair_color: string;
  facial_hair: string;
  accessory: string;
  mouth: string;
};
canDrive: boolean;
minor: string;          // Minor field of study
```

### 1.4 Missing Player Properties

**File:** `server/src/models/Player.ts`

```typescript
// Add these cached game data properties:
elementary_schools: any[];
high_schools: any[];
colleges: any[];
majors: any[];
focuses: any[];
storeItems: any[];
inAppPurchases: any[];
healthConditions: any[];
extraCurriculars: any[];
dateIdeas: any[];
female_hair_types: string[];
male_hair_types: string[];
fps: number;
messageEnergyCost: number;  // default 5
```

---

## Priority 2: Event System Gaps

### 2.1 Missing Event Helper Functions

**File:** `server/src/events/base.ts`

```typescript
// These helper functions need to be implemented:
export function messageFunction(
  fname: string,
  message: string,
  player: Player,
  check: boolean,
  title?: string,
  image?: string,
  energyCost?: number,
  diamondCost?: number,
  moneyCost?: number,
  affinityChange?: number,
  characters?: Person[]
): EventResult | null;

export function questionFunction(
  fname: string,
  message: string,
  player: Player,
  check: boolean,
  answerOptions: AnswerOption[],
  characters?: Person[],
  image?: string
): EventResult | null;
```

### 2.2 Missing Event Categories (85 functions)

**Activity/Learning Events (21):**
- `addSocialActivity`, `autumnActivities`, `bookClub`, `buildRelationshipsAtActivity`
- `campingTrip`, `codingBootcamp`, `codingBootcampProgress`, `collectionHobby`
- `communityEvent`, `cookingClassProgress`, `cookingClasses`, `craftingHobby`
- `gamingGroup`, `gardening`, `gymProgress`, `languageLearningProgress`
- `learnLanguage`, `learnMartialArts`, `learnPainting`, `learnPhotography`
- `musicLessonsProgress`

**Health/Lifestyle Events (9):**
- `eyeStrain`, `familyGameNight`, `familyPhoto`, `familyVacation`
- `healthCondition`, `hikingAdventure`, `meditation`, `musicLessons`
- `skiingVacation`

**Career/Adult Events (7):**
- `adultMissFriends`, `businessFailure`, `latetoSchool`, `openbankAccount`
- `perfectParkingSpot`, `professionalCertification`, `professionalConference`

**Social/Hobby Events (7):**
- `badRestaurantExperience`, `beachDay`, `birdWatching`, `joinClub`
- `joinGym`, `joinSoccerTeam`, `theatreAudition`

**Negative Events (6):**
- `accountHacked`, `carCrash`, `murderAttempt`, `sideHustle`
- `socialMediaCanceled`, `teachSiblingSkill`

**Learning Progress Events (6):**
- `martialArtsProgress`, `runningHabit`, `runningProgress`
- `readingChallenge`, `soccerProgress`, `yogaProgress`

**Utility Functions (8):**
- `getActivityRecord`, `get_allFriends`, `handleLearningActivities`
- `hasActivity`, `incrementActivityPerformance`, `negativeHabitEvent`

---

## Priority 3: Stat Calculation Differences

### 3.1 getPeakEnergy() Oversimplified

**File:** `server/src/game/engine/GameEngine.ts:94-102`

**Current (TypeScript):** Age-based only
```typescript
getPeakEnergy(person: Person): number {
  const age = person.ageYears;
  if (age < 10) return 80;
  // ... fixed values by age
}
```

**Required (Python logic):**
- Sum energy costs from ALL habits (quitting habits: +5)
- Iterate through ALL activities checking activity records
- Apply energy modifiers from job levels
- Apply energy modifiers from educational focuses
- Formula: `calcEnergy = energy - peakEnergy`

### 3.2 handleFinances() Missing Complexity

**File:** `server/src/game/engine/GameEngine.ts:390-400`

**Missing:**
- `spendingHabits` consideration (frugal: 0.2, normal: 0.1, extravagant: 0.05)
- Activity record iteration for job income
- Part-time job modifier (0.3x)

### 3.3 handleMoods() Different Logic

**Python:** Sets `mood` property based on energy/happiness combinations
**TypeScript:** Modifies `stress` and `happiness` values instead

---

## Priority 4: Intraday Activity Differences

### 4.1 Missing Fifth Class

**File:** `server/src/game/engine/intradayActivity.ts:489-512`

Add missing class at hour 13:
```typescript
// After hour 11 third class, before hour 14 last class
if (hour === 13) {
  events.push(createDailyEvent(13, school, 'Your fifth class starts'));
}
```

### 4.2 Party Location Bug

**File:** `server/src/game/engine/intradayActivity.ts:444-456`

**Current:** Party incorrectly uses home location
**Fix:** Create dynamic party location like Python:
```typescript
const partyId = `party-${player.c.id}`;
let partyLocation = player.l.find(l => l.id === partyId);
if (!partyLocation) {
  partyLocation = { id: partyId, type: 'party', name: 'Party' };
  player.l.push(partyLocation);
}
```

### 4.3 Weekend Detection Mismatch

**Python:** Uses string names ('Saturday', 'Sunday')
**TypeScript:** Uses numbers (6, 7)

Ensure consistent data type across codebase.

### 4.4 Weekend Evening Probability Mismatch

**Python:** 25% study, 25% party, 50% relax
**TypeScript:** 33% study, 33% party, 33% relax

---

## Priority 5: Handler/Message Format Differences

### 5.1 Speed Update Response Format

**File:** `server/src/handlers/gameControl.ts:108-111`

**Python:** `{ type: 'u', gameSpeed: value }`
**TypeScript:** `{ type: 'speedUpdate', speed: value }`

For iOS compatibility, should match Python format.

### 5.2 Missing Message Queue Processing

**File:** `server/src/handlers/events.ts`

Python processes message queue after events:
```python
if player.messageQueue and len(player.messageQueue) > 0:
    player.message = player.messageQueue.pop(0)
    await sendEventMessage(...)
```

### 5.3 Missing Achievement Triggers

**Files:** `server/src/handlers/romance.ts`, `server/src/handlers/activities.ts`

Python triggers achievements for:
- `relationship_started` after romance actions
- `job_applied` after job applications

### 5.4 Account Deletion Confirmation Mismatch

**Python:** `'DELETE'`
**TypeScript:** `'DELETE MY ACCOUNT'`

---

## Priority 6: Database Schema Gaps

### 6.1 Missing Tables (NOT created by TypeScript)

**Monetization:**
- `energy_refill_purchases`
- `diamond_transactions`
- `time_skip_purchases`

**Retention/Achievements:**
- `player_achievements`
- `daily_rewards_state`
- `daily_reward_claims`
- `daily_quests`
- `player_daily_quests`
- `player_statistics`
- `daily_login_rewards`
- `player_login_streak`

**Dating/Relationships:**
- `match_attempts`
- `relationship_events`
- `player_relationship_events`
- `date_activities`
- `date_history`

**AI Features:**
- `generated_images`
- `image_generation_queue`
- `event_images`
- `image_generation_stats`

**Analytics:**
- `character_memory`
- `api_usage`

**Compliance:**
- `data_export_requests`
- `account_deletion_requests`

### 6.2 Table Name Mismatch

**Python:** `lifesim_savegames`
**TypeScript:** `players`

### 6.3 Missing Character Field Denormalization

TypeScript should extract and store:
- `firstname`, `lastname`, `ageYears`, `ageDays` at top level for queries

---

## Priority 7: Default Value Differences

| Property | Python | TypeScript |
|----------|--------|-----------|
| `person.affinity` | `random(-24, 25)` | `50` |
| `person.happiness` | `random(0, 100)` | `50` |
| `person.health` | `1` | `100` |
| `person.diamonds` | `35` | `0` |
| `person.occupation` | `'preschool'` | `''` |
| `person.education` | `'None'` | `''` |

---

## Immediate Action Items

### Must Fix (Breaks Game):
1. [x] Add `getIntradayActivity()` calls to LoopManager for all characters - **FIXED**
2. [x] Add `get_dailyPlan()` calls at hour 0 - **FIXED**
3. [x] Fix party location creation in intradayActivity.ts - **FIXED**
4. [x] Implement `locationClass` model - **FIXED** (extended GameLocation interface)
5. [x] Add missing fifth class for students - **FIXED**

### Should Fix (Gameplay Impact):
6. [x] Implement `oneTimeEvent` class with `parseOneTimeEvents()` - **FIXED**
7. [x] Add weekly updates for relationship characters - **FIXED**
8. [ ] Fix `getPeakEnergy()` to include habits/activities
9. [x] Add `handleHabitChanges()` weekly call - **FIXED** (via handleWeeklyUpdates)
10. [x] Implement missing Person properties (hunger, thirst, weight) - **FIXED**

### Nice to Have (Polish):
11. [ ] Add missing 85 event functions
12. [ ] Create missing database tables
13. [ ] Match message format with Python exactly
14. [ ] Add achievement trigger hooks

---

*Last Updated: 2025-12-27*
*Generated by comparing Python (`ws/`) and TypeScript (`server/src/`) codebases*
