# Interface System (C++ Style)

## 🎯 Philosophy

Like C++ header files (.h), we enforce **strict interfaces** that MUST be implemented. Any missing method = **RED SCREEN ERROR** at startup.

## 📦 Interface Hierarchy

```
StrictInterface (base)
├── ProgressItemInterface           # For progress tracking items
│   ├── VocabularyDiscoveryItem
│   ├── VocabularyMasteryItem
│   └── Content Items (Phrase, Dialog, Text, Audio, Image, Grammar)
│
├── ProgressSystemInterface         # For progress systems
│   ├── ProgressTracker
│   └── PrerequisiteEngine
│
└── DRSExerciseInterface           # For exercise modules
    ├── VocabularyModule
    ├── TextAnalysisModule
    ├── GrammarAnalysisModule
    ├── TranslationModule
    └── OpenResponseModule
```

## 🔥 1. StrictInterface (Base)

**Location**: `src/DRS/interfaces/StrictInterface.js`

**Purpose**: Ultra-strict base class with visual error enforcement.

**Features**:
- Validates implementation at construction
- Full-screen red error overlay if method missing
- Sound alert in dev mode
- Screen shake animation
- Impossible to ignore

**Error Display**:
```
┌─────────────────────────────────────────────┐
│                                             │
│           🔥 FATAL ERROR 🔥                │
│                                             │
│      Implementation Missing                 │
│                                             │
│  Class: VocabularyModule                   │
│  Missing Method: validate()                │
│                                             │
│  ❌ MUST implement all interface methods   │
│                                             │
│     [ DISMISS (Fix Required!) ]            │
│                                             │
└─────────────────────────────────────────────┘
```

## 📋 2. ProgressItemInterface

**Location**: `src/DRS/interfaces/ProgressItemInterface.js`

**Purpose**: Contract for all progress tracking items.

### Required Methods (4)

```javascript
validate()           // Validate item data
serialize()          // Convert to JSON
getWeight()          // Return item weight for progress calculation
canComplete(state)   // Check prerequisites
```

### Implementations

| Class | Weight | Prerequisites |
|-------|--------|---------------|
| VocabularyDiscoveryItem | 1 | None |
| VocabularyMasteryItem | 1 | Discovered |
| PhraseItem | 6 | Vocabulary mastered |
| DialogItem | 12 | Vocabulary mastered |
| TextItem | 15 | Vocabulary mastered |
| AudioItem | 12 | Vocabulary mastered |
| ImageItem | 6 | Vocabulary discovered |
| GrammarItem | 6 | Vocabulary discovered |

### Example Implementation

```javascript
import ProgressItemInterface from '../interfaces/ProgressItemInterface.js';

class MyItem extends ProgressItemInterface {
    constructor(id, metadata) {
        super('my-item', id, metadata);
    }

    // ⚠️ REQUIRED
    validate() {
        if (!this.metadata.requiredField) {
            throw new Error('Missing requiredField');
        }
        return true;
    }

    // ⚠️ REQUIRED
    serialize() {
        return {
            ...this._getBaseSerialization(),
            customData: this.metadata.custom
        };
    }

    // ⚠️ REQUIRED
    getWeight() {
        return ProgressItemInterface.WEIGHTS['my-item'] || 5;
    }

    // ⚠️ REQUIRED
    canComplete(userProgress) {
        // Check prerequisites
        return true;
    }
}
```

## 🔧 3. ProgressSystemInterface

**Location**: `src/DRS/interfaces/ProgressSystemInterface.js`

**Purpose**: Contract for all progress management systems.

### Required Methods (17)

**Vocabulary Tracking:**
- `markWordDiscovered(word, metadata)`
- `markWordMastered(word, metadata)`
- `isWordDiscovered(word)`
- `isWordMastered(word)`

**Content Tracking:**
- `markPhraseCompleted(id, metadata)`
- `markDialogCompleted(id, metadata)`
- `markTextCompleted(id, metadata)`
- `markAudioCompleted(id, metadata)`
- `markImageCompleted(id, metadata)`
- `markGrammarCompleted(id, metadata)`

**Prerequisites:**
- `canComplete(itemType, itemId, context)`

**Progress:**
- `getProgress(chapterId)`

**Persistence:**
- `saveProgress(bookId, chapterId)`
- `loadProgress(bookId, chapterId)`

**Utility:**
- `reset(bookId, chapterId)`

### Implementations

- **ProgressTracker** - Weight-based progress with items
- **PrerequisiteEngine** - Prerequisite checking and mastery tracking

## 🎮 4. DRSExerciseInterface

**Location**: `src/DRS/interfaces/DRSExerciseInterface.js`

**Purpose**: Contract for all DRS exercise modules.

### Required Methods (10)

**Lifecycle:**
- `init(config, content)` - Initialize exercise
- `render(container)` - Render UI
- `destroy()` - Clean up

**Exercise Logic:**
- `validate(userAnswer)` - Validate answer
  - Returns: `{ isCorrect, score, feedback, explanation }`
- `getResults()` - Get results
  - Returns: `{ score, attempts, timeSpent, completed, details }`
- `handleUserInput(event, data)` - Handle user input

**Progress Tracking:**
- `markCompleted(results)` - Mark as completed
- `getProgress()` - Get progress
  - Returns: `{ percentage, currentStep, totalSteps, itemsCompleted, itemsTotal }`

**Metadata:**
- `getExerciseType()` - Return exercise type string
- `getExerciseConfig()` - Return config object
  - Returns: `{ type, difficulty, estimatedTime, prerequisites, metadata }`

### Implementations

- **VocabularyModule** - Flashcard spaced repetition
- **TextAnalysisModule** - AI-powered text comprehension
- **GrammarAnalysisModule** - AI grammar correction
- **TranslationModule** - AI translation validation
- **OpenResponseModule** - Free-form AI evaluation

## ✅ 5. ImplementationValidator

**Location**: `src/DRS/services/ImplementationValidator.js`

**Purpose**: Validate ALL implementations at application startup.

### Validation Phases

```javascript
🔍 VALIDATING DRS IMPLEMENTATIONS...

📦 PART 1: Validating Progress Items...
  ✅ VocabularyDiscoveryItem - OK
  ✅ VocabularyMasteryItem - OK
  ✅ PhraseItem - OK
  ✅ DialogItem - OK
  ✅ TextItem - OK
  ✅ AudioItem - OK
  ✅ ImageItem - OK
  ✅ GrammarItem - OK

🔧 PART 2: Validating Progress Systems...
  ✅ ProgressTracker - OK
  ✅ PrerequisiteEngine - OK

🎮 PART 3: Validating DRS Exercise Modules...
  ✅ VocabularyModule - OK
  ✅ TextAnalysisModule - OK
  ✅ GrammarAnalysisModule - OK
  ✅ TranslationModule - OK
  ✅ OpenResponseModule - OK

✅ ALL DRS IMPLEMENTATIONS VALID
```

### Integration with Application.js

```javascript
// At startup (lines 55-62)
console.log('🔍 Validating progress item implementations...');
const { default: ImplementationValidator } = await import('./DRS/services/ImplementationValidator.js');
const isValid = await ImplementationValidator.validateAll();

if (!isValid) {
    throw new Error('❌ Implementation validation failed - check console for details');
}
```

## 🚨 Enforcement Rules

### NON-NEGOTIABLE

1. ❌ **Missing method** → RED SCREEN ERROR → App refuses to start
2. ❌ **Wrong signature** → Runtime error on call
3. ❌ **Wrong return format** → Runtime error on usage
4. ✅ **All methods implemented** → App starts normally

### Validation Happens

- ✅ At application startup (before any UI renders)
- ✅ On module registration
- ✅ At interface instantiation

## ✨ Benefits

1. 🛡️ **Impossible to forget implementation** - Visual error forces fix
2. 📋 **Self-documenting** - Interface defines exact contract
3. 🔒 **Type safety** - Like TypeScript but enforced at runtime
4. 🧪 **Testable** - Can mock interfaces for unit tests
5. 🔄 **Maintainable** - Adding new method updates all implementations

## 📋 Interface Compliance Checklist

Before creating a new implementation:

- [ ] Identified correct interface to extend
- [ ] Implemented ALL required methods
- [ ] Correct method signatures
- [ ] Correct return formats
- [ ] Validation logic in place
- [ ] Added to ImplementationValidator
- [ ] Tested with validation at startup
- [ ] Documentation updated

## 🔍 Testing Your Implementation

```javascript
// Manual test in console
const validator = await import('./DRS/services/ImplementationValidator.js');
const result = await validator.default.validateAll();
console.log(result); // true if valid, throws error otherwise
```

## 🚧 Adding New Interface Methods

When adding a new method to an interface:

1. Update the interface class
2. Update ALL implementations
3. Update ImplementationValidator
4. Update this documentation
5. Test with validation
6. Commit changes

**Result**: All implementations will show RED SCREEN ERROR until updated.

## 📖 Further Reading

- `docs/creating-new-module.md` - How to create new modules
- `docs/progress-system.md` - Progress tracking details
- `README.md` - Project overview
