# Translation Management System

A comprehensive, professional-grade translation management system for Lilith's multilingual platform, providing automated validation, workflow management, and quality assurance for translations across 5 languages.

## Overview

The Translation Management System provides:

- **Automated Translation Validation** - Comprehensive validation rules ensuring translation quality and consistency
- **Professional Workflow Management** - Complete lifecycle management from creation to publication
- **Quality Assurance** - Automated quality scoring and metrics tracking
- **CLI Tools** - Command-line interface for developers and translators
- **Integration Support** - Seamless integration with Next.js internationalization

## Architecture

### Core Components

```
Translation Management System
├── Translation Manager         # Core validation and quality assessment
├── Translation Workflow       # Workflow lifecycle management
├── Translation CLI            # Command-line interface
├── Validation Rules           # Automated quality checks
└── Quality Metrics           # Scoring and analytics
```

### Supported Languages

1. **English (en)** - Primary/baseline language
2. **Spanish (es)** - Latin American and European markets
3. **Chinese Simplified (zh-CN)** - East Asian markets
4. **Arabic (ar)** - Middle Eastern and North African markets
5. **French (fr)** - European and African markets

## Getting Started

### Installation

```bash
# Install CLI dependencies
npm install tsx commander chalk cli-table3 inquirer
npm install --save-dev @types/inquirer

# Install translation dependencies
npm install next-intl @formatjs/intl-localematcher negotiator
npm install --save-dev @types/negotiator
```

### Basic Usage

```bash
# Validate all translations
npm run translate:validate

# Generate coverage report
npm run translate:coverage

# Check translation quality
npm run translate:quality

# Synchronize translation keys
npm run translate:sync

# View workflow status
npm run translate:status
```

## Translation Validation

### Validation Rules

The system implements comprehensive validation rules:

#### 1. **Interpolation Validation**
- Ensures all interpolation variables are preserved
- Detects missing or extra variables
- Example: `{count}` variables must match between languages

```json
// ❌ Invalid - missing {count} variable
"features.wisdom": "Discover wisdom"

// ✅ Valid - includes {count} variable
"features.wisdom": "Descubre sabiduría con {count} tradiciones"
```

#### 2. **Length Validation**
- Enforces UI constraint limits
- Prevents text overflow in components
- Configurable limits per field type

```typescript
const lengthLimits = {
  'navigation.': 20,      // Navigation items
  'common.buttons.': 15,  // Button labels
  'metadata.title': 60,   // Page titles
  'metadata.description': 160 // Meta descriptions
};
```

#### 3. **Format Validation**
- Checks punctuation consistency
- Validates HTML/markdown syntax
- Ensures proper capitalization

#### 4. **Cultural Sensitivity**
- Validates cultural appropriateness
- Checks religious/cultural terminology
- Ensures regional preferences

#### 5. **Terminology Consistency**
- Maintains consistent translations
- Validates brand name usage
- Ensures technical accuracy

### Running Validation

```bash
# Validate all languages
npm run translate -- validate

# Validate specific language
npm run translate -- validate es

# View detailed validation results
npm run translate -- validate zh-CN --verbose
```

### Validation Output

```
┌─────────┬────────────┬────────────┬────────┬──────────┐
│ Locale  │ Status     │ Coverage   │ Errors │ Warnings │
├─────────┼────────────┼────────────┼────────┼──────────┤
│ en      │ ✅ Valid   │ 100%       │ 0      │ 0        │
│ es      │ ✅ Valid   │ 100%       │ 0      │ 2        │
│ zh-CN   │ ❌ Invalid │ 85%        │ 3      │ 1        │
│ ar      │ ✅ Valid   │ 98%        │ 0      │ 1        │
│ fr      │ ✅ Valid   │ 100%       │ 0      │ 0        │
└─────────┴────────────┴────────────┴────────┴──────────┘
```

## Workflow Management

### Workflow Lifecycle

```mermaid
graph LR
    A[Draft] --> B[Ready for Review]
    B --> C[In Review]
    C --> D[Changes Requested]
    C --> E[Approved]
    D --> B
    E --> F[Published]
    F --> G[Archived]
```

### Workflow Commands

#### 1. **Create Workflow**

```bash
npm run translate -- create-workflow es 1.2.0 --author translator@company.com
```

#### 2. **Submit for Review**

```bash
npm run translate -- submit <workflow-id> --author translator@company.com
```

#### 3. **Assign Reviewer**

```bash
npm run translate -- assign <workflow-id> reviewer@company.com --by manager@company.com
```

#### 4. **Review Process**

```bash
# Add review comment
npm run translate -- comment <workflow-id> "Please check navigation section" --keys navigation.home,navigation.settings

# Request changes
npm run translate -- request-changes <workflow-id> "Need better terminology" --keys common.buttons.save

# Approve translation
npm run translate -- approve <workflow-id> --by manager@company.com --comments "Looks great!"
```

#### 5. **Publish Translation**

```bash
npm run translate -- publish <workflow-id> --by manager@company.com
```

### Workflow Status

```bash
# View all workflows
npm run translate -- status

# Filter by locale
npm run translate -- status es

# Filter by status
npm run translate -- status --filter approved
```

## Quality Assessment

### Quality Metrics

The system calculates comprehensive quality scores:

#### 1. **Completeness (30% weight)**
- Percentage of translated keys
- Missing key penalties
- Coverage scoring

#### 2. **Consistency (25% weight)**
- Terminology consistency
- Style guide adherence
- Cross-reference validation

#### 3. **Cultural Adaptation (25% weight)**
- Locale-specific appropriateness
- Cultural sensitivity checks
- Regional preferences

#### 4. **Technical Accuracy (20% weight)**
- Format correctness
- Interpolation accuracy
- Syntax validation

### Quality Reports

```bash
# Generate quality report for all languages
npm run translate:quality

# Generate report for specific language
npm run translate -- quality-report es
```

### Quality Output

```
┌─────────┬─────────┬─────────────┬─────────────┬──────────┬───────────┐
│ Locale  │ Overall │ Completeness│ Consistency │ Cultural │ Technical │
├─────────┼─────────┼─────────────┼─────────────┼──────────┼───────────┤
│ en      │ 100%    │ 100%        │ 100%        │ 100%     │ 100%      │
│ es      │ 95%     │ 100%        │ 92%         │ 90%      │ 98%       │
│ zh-CN   │ 87%     │ 85%         │ 95%         │ 85%      │ 92%       │
│ ar      │ 92%     │ 98%         │ 88%         │ 80%      │ 95%       │
│ fr      │ 96%     │ 100%        │ 94%         │ 90%      │ 100%      │
└─────────┴─────────┴─────────────┴─────────────┴──────────┴───────────┘
```

## Developer Integration

### Programmatic Usage

```typescript
import { TranslationManager, TranslationWorkflow } from '../i18n/translation-manager';

// Initialize translation manager
const manager = new TranslationManager('./src/i18n/messages');

// Validate translations
const validation = await manager.validateTranslation('es', translation);

// Generate quality metrics
const metrics = await manager.generateQualityMetrics('es');

// Create workflow
const workflow = new TranslationWorkflow(config);
const entry = await workflow.createWorkflowEntry('es', '1.0.0', 'dev@company.com');
```

### CI/CD Integration

```yaml
# .github/workflows/translation-check.yml
name: Translation Quality Check

on:
  pull_request:
    paths:
      - 'src/i18n/messages/**'

jobs:
  validate-translations:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '18'
      - name: Install dependencies
        run: npm ci
      - name: Validate translations
        run: npm run translate:validate
      - name: Check quality scores
        run: npm run translate:quality
      - name: Generate coverage report
        run: npm run translate:coverage
```

### Pre-commit Hook

```bash
#!/bin/sh
# .husky/pre-commit

# Validate translations before commit
npm run translate:validate || {
  echo "❌ Translation validation failed. Please fix errors before committing."
  exit 1
}

# Check quality scores
npm run translate:quality || {
  echo "⚠️  Translation quality issues detected. Review before committing."
}
```

## Configuration

### CLI Configuration

Create `translation.config.js`:

```javascript
module.exports = {
  messagesDir: './src/i18n/messages',
  workflowDir: './src/i18n/.workflow',
  requiresReview: true,
  minimumQualityScore: 85,
  reviewers: [
    'translator@company.com',
    'reviewer@company.com'
  ],
  approvers: [
    'manager@company.com',
    'lead@company.com'
  ],
  lengthLimits: {
    'navigation.': 20,
    'common.buttons.': 15,
    'metadata.title': 60,
    'metadata.description': 160
  },
  culturalRules: {
    'ar': {
      direction: 'rtl',
      dateFormat: 'DD/MM/YYYY',
      numberFormat: 'arabic-indic'
    },
    'zh-CN': {
      direction: 'ltr',
      dateFormat: 'YYYY年MM月DD日',
      numberFormat: 'decimal'
    }
  }
};
```

### Validation Rules Configuration

```typescript
// Custom validation rules
const customRules = [
  new BrandNameValidationRule(),
  new AccessibilityValidationRule(),
  new SEOValidationRule()
];

const manager = new TranslationManager('./messages', {
  customRules,
  strictMode: true,
  culturalValidation: true
});
```

## Best Practices

### 1. **Translation Workflow**

- Always create workflows for production translations
- Require review for all non-English translations
- Maintain consistent terminology across languages
- Use automated validation before submission

### 2. **Quality Standards**

- Maintain minimum 85% quality score
- Ensure 100% completion for production releases
- Regular quality audits for cultural appropriateness
- Automated testing for translation keys

### 3. **Cultural Considerations**

- **Arabic (ar)**: RTL layout, Islamic terminology, formal tone
- **Chinese (zh-CN)**: Simplified characters, mainland preferences, technical terms
- **Spanish (es)**: Neutral Latin American Spanish, inclusive language
- **French (fr)**: International French, formal business tone

### 4. **File Organization**

```
src/i18n/
├── messages/
│   ├── en.json          # Baseline translations
│   ├── es.json          # Spanish translations
│   ├── zh-CN.json       # Chinese translations
│   ├── ar.json          # Arabic translations
│   └── fr.json          # French translations
├── .workflow/           # Workflow state
│   ├── workflow-state.json
│   └── backups/
├── config.ts           # i18n configuration
├── hooks.ts            # React hooks
├── request.ts          # Next.js integration
└── translation-*.ts   # Management system
```

## API Reference

### TranslationManager

```typescript
class TranslationManager {
  // Load translation file
  async loadTranslation(locale: Locale): Promise<Record<string, any>>

  // Save translation file
  async saveTranslation(locale: Locale, translations: Record<string, any>): Promise<void>

  // Validate translation
  async validateTranslation(locale: Locale, translation: Record<string, any>): Promise<TranslationValidationResult>

  // Validate all translations
  async validateAllTranslations(): Promise<Record<Locale, TranslationValidationResult>>

  // Generate quality metrics
  async generateQualityMetrics(locale: Locale): Promise<TranslationQualityMetrics>

  // Generate coverage report
  async generateCoverageReport(): Promise<string>
}
```

### TranslationWorkflow

```typescript
class TranslationWorkflow {
  // Initialize workflow system
  async initialize(): Promise<void>

  // Create workflow entry
  async createWorkflowEntry(locale: Locale, version: string, createdBy: string): Promise<TranslationWorkflowEntry>

  // Submit for review
  async submitForReview(entryId: string, submittedBy: string): Promise<TranslationWorkflowEntry>

  // Assign reviewer
  async assignReviewer(entryId: string, reviewerEmail: string, assignedBy: string): Promise<TranslationWorkflowEntry>

  // Approve translation
  async approveTranslation(entryId: string, approver: string, comments?: string): Promise<TranslationWorkflowEntry>

  // Publish translation
  async publishTranslation(entryId: string, publishedBy: string): Promise<TranslationWorkflowEntry>
}
```

## Troubleshooting

### Common Issues

#### 1. **Validation Failures**

```bash
# Check specific validation errors
npm run translate -- validate es --verbose

# Extract missing keys
npm run translate -- extract-missing es

# Sync keys across locales
npm run translate:sync
```

#### 2. **Quality Score Issues**

```bash
# Generate detailed quality report
npm run translate -- quality-report es --detailed

# Check cultural adaptation scores
npm run translate -- cultural-check es

# Review terminology consistency
npm run translate -- terminology-check es
```

#### 3. **Workflow Problems**

```bash
# Check workflow status
npm run translate -- status --all

# View workflow history
npm run translate -- history <workflow-id>

# Reset workflow state
npm run translate -- reset <workflow-id> --confirm
```

### Performance Optimization

- Use translation caching for large files
- Implement incremental validation
- Optimize workflow state storage
- Enable parallel processing for multi-locale operations

## Contributing

### Adding New Languages

1. Update `src/i18n/config.ts` with new locale
2. Create translation file in `messages/` directory
3. Add cultural validation rules
4. Update length limits and formatting rules
5. Test with CLI validation tools

### Custom Validation Rules

```typescript
class CustomValidationRule extends ValidationRule {
  async validate(
    locale: Locale,
    translation: Record<string, any>,
    baseline: Record<string, any>
  ): Promise<{ errors: TranslationError[]; warnings: TranslationWarning[]; }> {
    // Custom validation logic
    return { errors: [], warnings: [] };
  }
}
```

## Support

For issues and feature requests:

- GitHub Issues: [Translation Management Issues]
- Documentation: [Translation Docs]
- Slack: #i18n-support
- Email: translation-support@lilith.ai

---

**Version**: 1.0.0
**Last Updated**: 2024-09-16
**Authors**: Lilith Translation Team