# NexusMart i18n System Architecture

Complete visual guide to how the multilingual system works.

## 🌍 System Overview

```
┌─────────────────────────────────────────────────────────────────┐
│                    NexusMart Multilingual System                │
│                      (10 Languages Supported)                    │
└─────────────────────────────────────────────────────────────────┘

                         ┌──────────────────┐
                         │   User Browser   │
                         │   /en/products/  │
                         │   /de/products/  │
                         │   /fr/products/  │
                         └────────┬─────────┘
                                  │
                    ┌─────────────┼─────────────┐
                    │                           │
            ┌───────▼────────┐        ┌────────▼──────┐
            │ URL Routing    │        │  Language     │
            │ (i18n_patterns)│        │  Selector     │
            │                │        │  (Navbar)     │
            │ /en/  /de/     │        │               │
            │ /fr/  /es/ ... │        │ POST Language │
            └───────┬────────┘        │ → Session     │
                    │                 └───────┬───────┘
                    │                         │
                    └────────────┬────────────┘
                                 │
                    ┌────────────▼───────────┐
                    │  Django Middleware     │
                    ├────────────────────────┤
                    │ 1. LocaleMiddleware    │
                    │    (Detects language) │
                    │                        │
                    │ 2. LanguageCurrency    │
                    │    SyncMiddleware      │
                    │    (Auto-sync curr.)  │
                    └────────────┬───────────┘
                                 │
                    ┌────────────▼───────────┐
                    │  Context Processor     │
                    ├────────────────────────┤
                    │ • LANGUAGE_CODE        │
                    │ • LANGUAGE_BIDI (RTL)  │
                    │ • available_languages  │
                    │ • currency_map         │
                    └────────────┬───────────┘
                                 │
                    ┌────────────▼───────────┐
                    │  View Processing       │
                    ├────────────────────────┤
                    │ from django.utils      │
                    │ .translation import _  │
                    │                        │
                    │ messages.success(      │
                    │   request,             │
                    │   _("Translatable")    │
                    │ )                      │
                    └────────────┬───────────┘
                                 │
                    ┌────────────▼───────────┐
                    │  Template Rendering    │
                    ├────────────────────────┤
                    │ {% load i18n %}        │
                    │ {% trans "string" %}   │
                    │                        │
                    │ {{ LANGUAGE_CODE }}    │
                    │ dir="{% if            │
                    │   LANGUAGE_BIDI %}     │
                    │   rtl{% endif %}"      │
                    └────────────┬───────────┘
                                 │
                    ┌────────────▼───────────┐
                    │  Translation Files     │
                    ├────────────────────────┤
                    │ locale/de/.../         │
                    │   django.mo (compiled) │
                    │                        │
                    │ locale/fr/.../         │
                    │   django.mo            │
                    │                        │
                    │ [9 compiled files]     │
                    └────────────┬───────────┘
                                 │
                    ┌────────────▼───────────┐
                    │  Rendered HTML         │
                    ├────────────────────────┤
                    │ <html lang="de"        │
                    │   dir="ltr">           │
                    │                        │
                    │ "In den Warenkorb"     │
                    │ (Translated German)    │
                    │                        │
                    │ Currency: EUR €        │
                    │ (Auto-synced)          │
                    └────────────────────────┘
```

---

## 📁 Directory Structure

```
nexusmart/
│
├── nexusmart/
│   ├── settings.py
│   │   ├── USE_I18N = True
│   │   ├── LANGUAGES = [('en', 'English'), ..., ('ar', 'العربية')]
│   │   ├── LOCALE_PATHS = [BASE_DIR / 'locale']
│   │   ├── LocaleMiddleware
│   │   └── language_context processor
│   │
│   ├── urls.py
│   │   └── i18n_patterns(
│   │       prefix_default_language=True,
│   │       path('shop/', ...),
│   │       path('user/', ...),
│   │   )
│   │
│   └── asgi.py, wsgi.py
│
├── shop/
│   ├── views.py
│   │   └── from django.utils.translation import gettext_lazy as _
│   │
│   ├── admin.py
│   │   └── site_header = _("BanshiMart Admin")
│   │
│   ├── context_processors.py
│   │   ├── current_language
│   │   ├── LANGUAGE_CODE
│   │   ├── LANGUAGE_BIDI
│   │   ├── available_languages
│   │   └── language_currency_map
│   │
│   ├── language_views.py
│   │   └── set_language_with_code()
│   │
│   ├── middleware.py
│   │   └── LanguageCurrencySyncMiddleware
│   │
│   ├── models.py
│   ├── urls.py
│   │   └── path('set-language/<lang>/', ...)
│   │
│   └── templates/shop/
│       ├── product_list.html
│       │   ├── {% load i18n %}
│       │   └── {% trans "Our Products" %}
│       │
│       ├── product_detail.html
│       ├── cart.html
│       ├── wishlist.html
│       ├── checkout.html
│       └── ...
│
├── users/
│   └── templates/
│       ├── user_dashboard.html
│       ├── customer_profile.html
│       ├── customer_form.html
│       └── address_*.html
│
├── templates/
│   ├── base.html
│   │   ├── {% load i18n %}
│   │   ├── <html lang="{{ LANGUAGE_CODE }}" 
│   │   │       dir="{% if LANGUAGE_BIDI %}rtl...">
│   │   └── RTL CSS styles
│   │
│   ├── navbar.html
│   │   └── Language selector dropdown
│   │
│   ├── index.html
│   ├── about.html
│   ├── contact.html
│   ├── faq.html
│   └── help.html
│
├── locale/
│   ├── de/LC_MESSAGES/
│   │   ├── django.po          ← Edit for translations
│   │   └── django.mo          ← Compiled (used by Django)
│   │
│   ├── fr/LC_MESSAGES/
│   │   ├── django.po
│   │   └── django.mo
│   │
│   ├── es/LC_MESSAGES/
│   ├── zh/LC_MESSAGES/
│   ├── ja/LC_MESSAGES/
│   ├── ka/LC_MESSAGES/
│   ├── ru/LC_MESSAGES/
│   ├── ar/LC_MESSAGES/
│   └── pt/LC_MESSAGES/
│
├── manage.py
│
└── Documentation Files
    ├── I18N_SETUP.md
    ├── TRANSLATION_QUICKSTART.md
    ├── I18N_VERIFICATION_CHECKLIST.md
    ├── TRANSLATION_STRINGS_REFERENCE.md
    └── i18n_manager.py
```

---

## 🔄 Language Detection Flow

```
User Request
    ↓
┌─ Which language to use? ─┐
│                          │
├─ 1. URL Prefix?          ├─ /de/products/ → German
│                          │
├─ 2. Session Variable?    ├─ request.session['django_language']
│                          │
├─ 3. Accept-Language?     ├─ Browser HTTP header
│                          │
├─ 4. LANGUAGE_CODE        ├─ Default (en)
│                          │
└──────────────────────────┘
          ↓
       Selected Language
          ↓
    django.translation.get_language()
          ↓
    Load corresponding .mo file
          ↓
    Translate strings
          ↓
    Render template in selected language
```

---

## 🌐 Supported Languages

```
┌──────────┬─────────────────┬──────────┬──────────────┐
│ Code     │ Language Name    │ Currency │ Direction    │
├──────────┼─────────────────┼──────────┼──────────────┤
│ en       │ English         │ USD      │ LTR (Left)   │
│ de       │ Deutsch         │ EUR      │ LTR (Left)   │
│ fr       │ Français        │ EUR      │ LTR (Left)   │
│ es       │ Español         │ EUR      │ LTR (Left)   │
│ zh       │ 中文            │ CNY      │ LTR (Left)   │
│ ja       │ 日本語          │ JPY      │ LTR (Left)   │
│ ka       │ ქართული         │ GEL      │ LTR (Left)   │
│ ru       │ Русский         │ RUB      │ LTR (Left)   │
│ ar       │ العربية         │ USD      │ RTL (Right)  │
│ pt       │ Português       │ EUR      │ LTR (Left)   │
└──────────┴─────────────────┴──────────┴──────────────┘
```

---

## 📱 Translation File Workflow

### Generation Phase
```
Developer creates translatable strings
    ↓
{% trans "string" %}  or  _("string")
    ↓
python manage.py makemessages -a
    ↓
Scans all .py and .html files
    ↓
Creates/Updates locale/*/LC_MESSAGES/django.po
    ↓
Empty msgstr fields for translations
```

### Translation Phase
```
locale/de/LC_MESSAGES/django.po
    ↓
#: templates/navbar.html:15
msgid "Add to Cart"
msgstr ""
    ↓
[Translator edits with Poedit or editor]
    ↓
#: templates/navbar.html:15
msgid "Add to Cart"
msgstr "In den Warenkorb"
    ↓
Save django.po file
```

### Compilation Phase
```
python manage.py compilemessages
    ↓
Converts .po (human readable)
    ↓
To .mo (binary compiled)
    ↓
Much faster at runtime
    ↓
locale/de/LC_MESSAGES/django.mo created
    ↓
Django uses .mo at runtime
```

### Runtime Usage
```
User visits /de/products/
    ↓
get_language() returns 'de'
    ↓
Django loads locale/de/LC_MESSAGES/django.mo
    ↓
{% trans "Our Products" %} → "Unsere Produkte"
    ↓
Template rendered in German
```

---

## 🎯 Request Processing Timeline

```
T0: User clicks language "Deutsch" in navbar
    │
T1: POST /shop/set-language/de/
    │
T2: View: set_language_with_code(request, 'de')
    │   ├─ request.session['django_language'] = 'de'
    │   └─ Redirect to referer
    │
T3: Middleware: LocaleMiddleware
    │   └─ activate('de')
    │
T4: Middleware: LanguageCurrencySyncMiddleware
    │   ├─ Gets currency mapping for 'de' → 'EUR'
    │   └─ Sets request.session['django_currency'] = 'EUR'
    │
T5: Context Processor: language_context
    │   ├─ LANGUAGE_CODE = 'de'
    │   ├─ LANGUAGE_BIDI = False
    │   ├─ available_languages = [(en, English), ...]
    │   └─ language_currency_map = {en: USD, de: EUR, ...}
    │
T6: View Function Executes
    │   └─ Uses translations from 'de' .mo file
    │
T7: Template Rendering
    │   ├─ {% load i18n %}
    │   ├─ <html lang="de" dir="ltr">
    │   └─ {% trans "Add to Cart" %} → "In den Warenkorb"
    │
T8: HTML Response
    │   ├─ Language: German
    │   ├─ Currency: EUR
    │   ├─ Direction: LTR
    │   └─ Sent to browser
    │
T9: Browser Renders Page
    └─ User sees German website with EUR pricing
```

---

## 🔐 Session Persistence

```
Session Database
│
├─ session_key: abc123...
│
├─ django_language: 'de'
│   └─ Persists across page loads
│       /de/products/ → /de/cart/ → /de/checkout/
│
├─ django_currency: 'EUR'
│   └─ Auto-synced with language
│
├─ django_timezone: 'Europe/Berlin'
│   └─ Optional: auto-sync with language
│
└─ Other session data (cart, user, etc.)
```

---

## 🚀 Deployment Architecture

```
Production Server
│
├─ Django Application
│   └─ Serves with LocaleMiddleware
│
├─ Static Files (CSS, JS, Images)
│   └─ Language-agnostic
│
├─ Media Files (Products, User Content)
│   └─ Language-agnostic
│
├─ locale/ Directory
│   ├─ Must be readable by Django process
│   ├─ Contains .mo files (not .po)
│   └─ Loaded at startup (performance)
│
├─ Database
│   └─ Stores session language preference
│
└─ Load Balancer (Optional)
    └─ Routes /en/, /de/, /fr/ to same app
       (Django handles all languages)
```

---

## ✅ Implementation Checklist

```
Infrastructure Layer:
✅ Settings: LANGUAGES, LOCALE_PATHS, USE_I18N
✅ Middleware: LocaleMiddleware, LanguageCurrencySyncMiddleware
✅ Context: language_context processor
✅ Views: Language switching view

URL Layer:
✅ i18n_patterns() wrapper

Template Layer:
✅ {% load i18n %} on major templates
✅ {% trans "strings" %} on UI text
✅ Dynamic lang and dir attributes

Python Layer:
✅ gettext_lazy imports in views
✅ _() wrapped strings in admin

Documentation Layer:
✅ I18N_SETUP.md
✅ TRANSLATION_QUICKSTART.md
✅ I18N_VERIFICATION_CHECKLIST.md
✅ i18n_manager.py helper
✅ TRANSLATION_STRINGS_REFERENCE.md

Translation Layer:
⏳ .po files (awaiting generation)
⏳ String translations (awaiting translator)
⏳ .mo files (awaiting compilation)
```

---

## 🎓 Key Concepts

### LTR vs RTL
- **LTR (Left-to-Right)**: English, German, French, etc.
  - Text flows left → right
  - UI elements: cart on right, menu on left

- **RTL (Right-to-Left)**: Arabic, Hebrew, Persian, Urdu
  - Text flows right ← left
  - UI elements: cart on left, menu on right
  - Auto-handled by CSS: `html[dir="rtl"]`

### .po vs .mo Files
- **.po (Portable Object)**:
  - Human-readable text format
  - Edited by translators with Poedit
  - Large file size (~50KB+)
  - Contains both English and translations

- **.mo (Machine Object)**:
  - Compiled binary format
  - Used by Django at runtime
  - Small file size (~10KB for same content)
  - Much faster to load

### Language Detection Priority
1. URL prefix (highest priority)
2. Session variable
3. HTTP Accept-Language header
4. Default LANGUAGE_CODE (lowest priority)

---

## 📊 Performance Impact

```
With i18n Enabled:
├─ Additional middleware: ~2-5ms per request
├─ Locale loading: ~1-2ms (cached)
├─ Template translation: ~1-3ms (cached)
├─ Total overhead: ~5-10ms per request
│
└─ Impact: Minimal (negligible for user)
   (Most time spent on database queries & rendering)
```

---

**System Status**: ✅ Ready for Translation

The architecture is complete. Next step: Run `python manage.py makemessages -a` to generate translation files.
