# Architecture

LINGULIA is intentionally simple: a **no-build, dependency-free static PWA**. This keeps it easy
to host, easy to audit, trivial to hand to a partner organisation, and — most importantly —
reliable offline on low-end phones.

## File map

```
index.html              Public landing page (interactive marketing homepage)
app.html                Installable app shell: header, disclaimer, views, bottom tab bar
manifest.webmanifest    PWA install metadata (start_url = app.html)
sw.js                   Service worker — pre-caches everything (incl. both pages); offline
vercel.json             Static deploy headers (service worker, manifest, fonts)
css/styles.css          Mobile-first, high-contrast UI; bundled Ethiopic @font-face
js/
  data.js               Loads + indexes the JSON corpora; ranked search
  tts.js                On-device text-to-speech (Web Speech API) + graceful fallback
  screening.js          Renders PHQ-9 / GAD-7; offline scoring + severity + flags
  ai.js                 OPTIONAL provider-agnostic AI (none | self-hosted LLM)
  app.js                Controller: i18n, routing, search, browse, phrases, about
data/
  corpus.json           Trilingual mental-health terminology
  screening.json        PHQ-9 + GAD-7 (items, options, score bands) in EN/AM/OM
  phrases.json          Clinician–patient phrasebook
  referral.json         Danger signs + referral criteria
fonts/                  Noto Sans Ethiopic (woff2) — bundled for offline Amharic
icons/                  PWA icons (192 / 512 / maskable / favicon)
prompts/                Safety-first system prompt pack for the optional/future AI
docs/                   This documentation
```

## Runtime data flow

```
            ┌─────────────┐   fetch (cache-first)   ┌──────────────┐
  app.js ──►│   data.js   │────────────────────────►│ data/*.json  │
    │       └─────────────┘                          └──────────────┘
    │ render
    ▼
 views (search / browse / screen / phrases / ai / about)
    │
    ├── TTS.speak()  ──► Web Speech API (on-device)
    └── AI.chat()    ──► [optional] network provider (online only)
```

All four JSON files are loaded once at startup and indexed in memory. Search builds a lowercased
"haystack" per entry across every translatable field (English, Amharic, Afaan Oromo, lay terms,
phonetics, definitions) and ranks exact/prefix/substring matches.

## Offline strategy

- `sw.js` pre-caches the **entire app** (shell, JS, CSS, all JSON, fonts, icons) on install, each
  asset added individually so one missing file can't abort the install.
- Fetches are **cache-first** with a network fallback; navigations fall back to `index.html`.
- Bump the `CACHE` version string in `sw.js` whenever you change an asset to force clients to
  refresh.
- Cross-origin calls (e.g. the optional self-hosted LLM endpoint) are explicitly **excluded**
  from caching — those are live and network-only.

## Internationalisation

- UI strings live in a single `STRINGS` table in `app.js`, keyed by string id with `en/am/om`
  values, exposed via `I18N.t(key, lang)`.
- Content strings live in the data files as `{ en, am, om }` objects; a small `L(obj, lang)`
  helper picks the active language with English fallback.
- Switching language re-applies static labels and re-renders the active view.

## Optional AI layer

`js/ai.js` is the **only** part that ever touches the network for generation, and it is **off by
default**. It defines a provider-agnostic contract:

```js
AI.chat(prompt, lang, history) -> Promise<string>
```

with two adapters:

| Provider | Behaviour |
|----------|-----------|
| `none`   | Default. Nothing is sent anywhere. The Ask AI tab shows "not configured". |
| `custom` | **Your own self-hosted / offline LLM.** `POST <your endpoint>` with `{ prompt, language, system, history }`; reads `response_text`/`text`/`content`/OpenAI-style `choices[0].message.content`. Works with llama.cpp, Ollama-style, vLLM/OpenAI-compatible servers, or a thin wrapper. **This is the hook for LINGULIA's own hosted model.** |

Config (provider, key, endpoint) is stored in `localStorage`. The assistant only runs when
`navigator.onLine` **and** a provider is configured; otherwise it degrades to a friendly notice.
The safety system prompt is embedded here (full version in
[`prompts/mental-health-system-prompt.md`](../prompts/mental-health-system-prompt.md)).

## Design principles

1. **Offline is the default, not a fallback.**
2. **Standalone** — no hard third-party dependency.
3. **Safety over capability** — emergencies and referral are front-and-centre; the AI never
   diagnoses.
4. **Reviewable** — every translated entry carries a `draft`/`reviewed` flag surfaced in the UI.
5. **No magic** — plain files a clinician-developer can read and a partner can self-host.
