# System Design — Daily Email Intelligence Agent

**Solution:** Multi-inbox email digest → WhatsApp (UltraMsg)  
**Host:** Namecheap cPanel (PHP + cron)

---

## 1. High-level architecture

```mermaid
flowchart LR
  subgraph Sources["Email sources"]
    G[Gmail IMAP]
    O[Outlook IMAP]
    Y[Yahoo / other IMAP]
  end

  subgraph Host["Namecheap cPanel"]
    C[Cron schedule<br/>e.g. 20:00 daily]
    R[run.php<br/>Agent runner]
    E[.env secrets]
    L[logs/cron.log]
    C --> R
    E --> R
    R --> L
  end

  subgraph Intelligence["Digest engine"]
    F[Fetch & normalize]
    S[Classify Action Needed / FYI]
    A[Optional OpenAI summary]
    F --> S
    S --> A
  end

  subgraph Delivery["WhatsApp"]
    U[UltraMsg API]
    W[Your WhatsApp]
    U --> W
  end

  G --> F
  O --> F
  Y --> F
  R --> F
  A --> U
```

---

## 2. Runtime sequence (one daily run)

```mermaid
sequenceDiagram
  participant Cron as cPanel Cron
  participant App as run.php
  participant Mail as IMAP mailboxes
  participant AI as OpenAI (optional)
  participant WA as UltraMsg
  participant User as WhatsApp user

  Cron->>App: Trigger at scheduled time
  App->>App: Load .env (accounts, tokens, timezone)
  App->>Mail: Fetch last N hours (read-only)
  Mail-->>App: Subjects, senders, snippets, unread flags
  alt OPENAI_API_KEY set
    App->>AI: Summarize + classify
    AI-->>App: Digest text
  else No AI key
    App->>App: Rule-based Action Needed / FYI
  end
  App->>WA: POST /messages/chat
  WA-->>User: Daily digest WhatsApp message
  App->>App: Write result to logs
```

---

## 3. Component map (what lives where)

| Layer | Component | Role |
|-------|-----------|------|
| Scheduler | cPanel Cron | Starts the agent every day |
| Entry point | `run.php` | Orchestrates one full run |
| Config | `.env` | Accounts, UltraMsg keys, timezone, AI key |
| Collector | `php/EmailFetcher.php` | Multi-account IMAP fetch |
| Brain | `php/Summarizer.php` | Action Needed vs FYI (+ optional AI) |
| Messenger | `php/WhatsApp.php` | UltraMsg (or Meta) send |
| Ops | `logs/` | Success / error trail |

---

## 4. Data flow (simplified)

```text
Multiple inboxes
      ↓
Collect today's mail (IMAP, read-only)
      ↓
Normalize (account, from, subject, time, snippet, unread)
      ↓
Prioritize
  • Action Needed → unread / requests / deadlines / approvals
  • FYI → newsletters / receipts / low urgency
      ↓
Compose short WhatsApp digest (≤ ~3900 chars)
      ↓
UltraMsg → your phone
```

---

## 5. What UltraMsg unlocks in this design

Once you provide UltraMsg credentials, the **delivery layer goes live**:

| You provide | System uses it for |
|-------------|--------------------|
| `ULTRAMSG_INSTANCE_ID` | API instance endpoint |
| `ULTRAMSG_TOKEN` | Authenticated send |
| `WHATSAPP_TO` | Destination number (you / leadership) |
| Email account IMAP details | Collection layer |
| Optional `OPENAI_API_KEY` | Smarter summaries |

With those values in `.env` on cPanel, the system can:

- Pull mixed mailboxes  
- Build Action Needed / FYI digest  
- Send WhatsApp every day automatically  
- Log each run  

No extra app UI is required for v1 — the “interface” is WhatsApp itself.

---

## 6. Security design

```text
/home/USER/email-whatsapp-digest/     ← outside public_html
  ├── run.php
  ├── .env                            ← secrets (not web-accessible)
  ├── php/
  └── logs/
```

- IMAP access is **read-only** (does not delete mail)  
- Secrets stay in `.env`, not in code  
- Cron runs server-side; no public URL required for daily digest  

---

## 7. Deployment topology (Namecheap)

```text
You (WhatsApp)
      ↑
UltraMsg cloud
      ↑
Namecheap cPanel server
  • cron 0 20 * * *
  • php run.php
  • .env + IMAP out to Gmail/Outlook/...
```

---

## 8. Extensibility (future design options)

| Extension | Description |
|-----------|-------------|
| Multi-recipient | Send same digest to several managers |
| VIP rules | Always elevate specific senders to Action Needed |
| Bilingual digest | English + Arabic sections |
| Escalation | Second WhatsApp ping if critical keywords found |
| Dashboard | Optional web report (later phase) |

---

**Status:** Design ready for configuration + UltraMsg credentials + pilot dry-run.  
