# 🏠 SmartLife Monitor - خطة المشروع الكاملة
## منصة مراقبة أجهزة LifeSmart متعددة المستأجرين (SaaS)

---

## 📋 نظرة عامة على المشروع

### الهدف
بناء منصة SaaS احترافية لمراقبة أجهزة LifeSmart الذكية مع نظام تنبيهات ذكي، تدعم اللغتين العربية والإنجليزية، متجاوبة مع الجوال، متعددة المستخدمين والصلاحيات.

### المميزات الرئيسية
- ✅ **متعدد المستأجرين (Multi-Tenant)**: كل عميل يرى أجهزته فقط
- ✅ **نظام صلاحيات متدرج**: مدير عام → عميل → مستخدم فرعي
- ✅ **ثنائي اللغة**: عربي/إنجليزي مع RTL كامل
- ✅ **متجاوب**: يعمل على الجوال والتابلت والكمبيوتر
- ✅ **تنبيهات ذكية**: شروط مخصصة (درجة حرارة، رطوبة، حركة، إلخ)
- ✅ **لوحة تحكم تفاعلية**: رسوم بيانية ومؤشرات حية

---

## 🏗️ البنية التقنية (Tech Stack)

### Backend (الخادم)
```
├── Language: Python 3.11+
├── Framework: FastAPI (عالي الأداء + WebSocket)
├── Database: PostgreSQL 15+ (بيانات رئيسية)
├── Cache: Redis 7+ (جلسات + تخزين مؤقت + قوائم انتظار)
├── Task Queue: Celery (مهام خلفية + تنبيهات)
├── ORM: SQLAlchemy 2.0 + Alembic (migrations)
└── Auth: JWT + OAuth2
```

### Frontend (الواجهة)
```
├── Framework: Next.js 14 (App Router)
├── UI Library: React 18
├── Styling: TailwindCSS + shadcn/ui
├── Icons: Lucide React
├── Charts: Recharts / Chart.js
├── State: Zustand + React Query
├── i18n: next-intl (عربي/إنجليزي)
└── Real-time: Socket.io Client
```

### Infrastructure (البنية التحتية)
```
├── Server: AlmaLinux 9.7
├── Web Server: Nginx (reverse proxy + SSL)
├── Process Manager: Systemd + Gunicorn
├── SSL: Let's Encrypt (Certbot)
├── Containerization: Docker + Docker Compose
└── Monitoring: Prometheus + Grafana (اختياري)
```

---

## 👥 نظام المستخدمين والصلاحيات

### الأدوار (Roles)

| الدور | الصلاحيات |
|-------|----------|
| **Super Admin** (مدير عام) | إدارة كاملة - إضافة/حذف عملاء - عرض كل البيانات - إعدادات النظام |
| **Tenant Admin** (مدير عميل) | إدارة أجهزته - إضافة مستخدمين فرعيين - إعداد التنبيهات |
| **Tenant User** (مستخدم فرعي) | عرض الأجهزة - استقبال التنبيهات (صلاحيات محدودة) |

### هيكل البيانات
```
Super Admin
    ├── Tenant 1 (Client A)
    │   ├── Devices (10 devices)
    │   ├── Alert Rules (5 rules)
    │   └── Sub-users (3 users)
    │
    ├── Tenant 2 (Client B)
    │   ├── Devices (25 devices)
    │   ├── Alert Rules (12 rules)
    │   └── Sub-users (8 users)
    │
    └── Tenant N...
```

---

## 📊 قاعدة البيانات - Schema

### الجداول الرئيسية

```sql
-- 1. المستأجرين (العملاء)
CREATE TABLE tenants (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name VARCHAR(255) NOT NULL,
    name_ar VARCHAR(255),
    email VARCHAR(255) UNIQUE NOT NULL,
    phone VARCHAR(50),
    lifesmart_app_key VARCHAR(255),
    lifesmart_app_token TEXT,
    lifesmart_user_id VARCHAR(255),
    lifesmart_region VARCHAR(50) DEFAULT 'global',
    subscription_plan VARCHAR(50) DEFAULT 'basic',
    max_devices INT DEFAULT 50,
    max_users INT DEFAULT 5,
    is_active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 2. المستخدمين
CREATE TABLE users (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID REFERENCES tenants(id) ON DELETE CASCADE,
    email VARCHAR(255) UNIQUE NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    full_name VARCHAR(255) NOT NULL,
    full_name_ar VARCHAR(255),
    role VARCHAR(50) NOT NULL CHECK (role IN ('super_admin', 'tenant_admin', 'tenant_user')),
    phone VARCHAR(50),
    avatar_url TEXT,
    language VARCHAR(10) DEFAULT 'ar',
    timezone VARCHAR(50) DEFAULT 'Asia/Riyadh',
    is_active BOOLEAN DEFAULT TRUE,
    last_login TIMESTAMP,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 3. الأجهزة
CREATE TABLE devices (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID REFERENCES tenants(id) ON DELETE CASCADE,
    lifesmart_device_id VARCHAR(255) NOT NULL,
    lifesmart_hub_id VARCHAR(255),
    name VARCHAR(255) NOT NULL,
    name_ar VARCHAR(255),
    device_type VARCHAR(100) NOT NULL,
    device_model VARCHAR(100),
    location VARCHAR(255),
    location_ar VARCHAR(255),
    icon VARCHAR(100),
    is_online BOOLEAN DEFAULT FALSE,
    last_seen TIMESTAMP,
    metadata JSONB DEFAULT '{}',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    UNIQUE(tenant_id, lifesmart_device_id)
);

-- 4. قراءات الأجهزة (Time Series)
CREATE TABLE device_readings (
    id BIGSERIAL PRIMARY KEY,
    device_id UUID REFERENCES devices(id) ON DELETE CASCADE,
    reading_type VARCHAR(50) NOT NULL, -- temperature, humidity, motion, power, etc.
    value DECIMAL(10, 2) NOT NULL,
    unit VARCHAR(20),
    recorded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_readings_device_time ON device_readings(device_id, recorded_at DESC);

-- 5. قواعد التنبيهات
CREATE TABLE alert_rules (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID REFERENCES tenants(id) ON DELETE CASCADE,
    device_id UUID REFERENCES devices(id) ON DELETE CASCADE,
    name VARCHAR(255) NOT NULL,
    name_ar VARCHAR(255),
    condition_type VARCHAR(50) NOT NULL, -- greater_than, less_than, equals, between
    reading_type VARCHAR(50) NOT NULL,
    threshold_value DECIMAL(10, 2),
    threshold_min DECIMAL(10, 2),
    threshold_max DECIMAL(10, 2),
    severity VARCHAR(20) DEFAULT 'warning', -- info, warning, critical
    notification_channels JSONB DEFAULT '["email", "push"]',
    cooldown_minutes INT DEFAULT 15,
    is_active BOOLEAN DEFAULT TRUE,
    created_by UUID REFERENCES users(id),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 6. سجل التنبيهات
CREATE TABLE alert_logs (
    id BIGSERIAL PRIMARY KEY,
    alert_rule_id UUID REFERENCES alert_rules(id) ON DELETE SET NULL,
    device_id UUID REFERENCES devices(id) ON DELETE CASCADE,
    tenant_id UUID REFERENCES tenants(id) ON DELETE CASCADE,
    title VARCHAR(255) NOT NULL,
    message TEXT,
    severity VARCHAR(20),
    reading_value DECIMAL(10, 2),
    is_read BOOLEAN DEFAULT FALSE,
    is_resolved BOOLEAN DEFAULT FALSE,
    resolved_at TIMESTAMP,
    resolved_by UUID REFERENCES users(id),
    triggered_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 7. جلسات المستخدمين
CREATE TABLE user_sessions (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID REFERENCES users(id) ON DELETE CASCADE,
    token_hash VARCHAR(255) NOT NULL,
    device_info JSONB,
    ip_address INET,
    expires_at TIMESTAMP NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 8. سجل النشاطات
CREATE TABLE activity_logs (
    id BIGSERIAL PRIMARY KEY,
    user_id UUID REFERENCES users(id),
    tenant_id UUID REFERENCES tenants(id),
    action VARCHAR(100) NOT NULL,
    entity_type VARCHAR(50),
    entity_id UUID,
    details JSONB,
    ip_address INET,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```

---

## 🔌 تكامل LifeSmart API

### المتطلبات
1. **App Key** و **App Token** من [LifeSmart Open Platform](http://www.ilifesmart.com/open/login)
2. **User ID** من تطبيق LifeSmart
3. **Region**: china, north_america, europe, japan, asia_pacific, global

### نقاط النهاية الرئيسية

```python
# lifesmart_client.py

class LifeSmartClient:
    BASE_URLS = {
        'china': 'https://api.ilifesmart.com',
        'global': 'https://api.us.ilifesmart.com',
        'europe': 'https://api.eu.ilifesmart.com',
    }
    
    async def get_devices(self) -> List[Device]:
        """جلب قائمة الأجهزة"""
        
    async def get_device_status(self, device_id: str) -> DeviceStatus:
        """جلب حالة جهاز معين"""
        
    async def control_device(self, device_id: str, command: dict) -> bool:
        """التحكم في جهاز"""
        
    async def subscribe_to_updates(self, callback: Callable):
        """الاشتراك في التحديثات الحية (WebSocket)"""
```

### أنواع الأجهزة المدعومة
| النوع | الموديلات | القراءات |
|-------|----------|----------|
| **حساسات البيئة** | SL_SC_THL, SL_SC_G | درجة حرارة، رطوبة، إضاءة |
| **حساسات الحركة** | SL_SC_MHW, SL_SC_BM | حركة، وجود |
| **مفاتيح** | SL_SW_ND1/2/3 | حالة (تشغيل/إيقاف) |
| **أقفال** | SL_LK_LS, SL_LK_GTM | حالة القفل، البطارية |
| **مقابس** | SL_OL_W, SL_OE_DE | استهلاك الطاقة |
| **ستائر** | SL_SW_WIN, SL_CN_IF | نسبة الفتح |

---

## 🎨 تصميم الواجهة (UI/UX)

### الصفحات الرئيسية

```
📱 SmartLife Monitor
│
├── 🔐 Auth Pages
│   ├── /login - تسجيل الدخول
│   ├── /forgot-password - نسيت كلمة المرور
│   └── /reset-password - إعادة تعيين
│
├── 📊 Dashboard (لوحة التحكم)
│   ├── / - نظرة عامة (إحصائيات + أجهزة + تنبيهات)
│   └── /analytics - تحليلات مفصلة
│
├── 📟 Devices (الأجهزة)
│   ├── /devices - قائمة الأجهزة
│   ├── /devices/[id] - تفاصيل جهاز
│   └── /devices/map - خريطة الأجهزة
│
├── 🔔 Alerts (التنبيهات)
│   ├── /alerts - سجل التنبيهات
│   ├── /alerts/rules - قواعد التنبيهات
│   └── /alerts/rules/new - إنشاء قاعدة جديدة
│
├── 👥 Users (المستخدمين) [Tenant Admin+]
│   ├── /users - إدارة المستخدمين
│   └── /users/[id] - تفاصيل مستخدم
│
├── 🏢 Tenants (العملاء) [Super Admin]
│   ├── /tenants - إدارة العملاء
│   ├── /tenants/new - إضافة عميل
│   └── /tenants/[id] - تفاصيل عميل
│
└── ⚙️ Settings (الإعدادات)
    ├── /settings/profile - الملف الشخصي
    ├── /settings/notifications - إعدادات الإشعارات
    ├── /settings/integration - ربط LifeSmart
    └── /settings/system - إعدادات النظام [Admin]
```

### مكونات الواجهة

```
Components
├── Layout
│   ├── Sidebar (قائمة جانبية قابلة للطي)
│   ├── Header (شريط علوي + بحث + إشعارات + لغة)
│   └── MobileNav (قائمة سفلية للجوال)
│
├── Dashboard
│   ├── StatsCard (بطاقة إحصائية)
│   ├── DeviceCard (بطاقة جهاز)
│   ├── AlertBanner (شريط تنبيه)
│   ├── TemperatureGauge (مقياس حرارة)
│   ├── HumidityChart (رسم رطوبة)
│   └── DeviceStatusGrid (شبكة حالة الأجهزة)
│
├── Forms
│   ├── AlertRuleForm (نموذج قاعدة تنبيه)
│   ├── DeviceForm (نموذج جهاز)
│   └── UserForm (نموذج مستخدم)
│
└── Common
    ├── DataTable (جدول بيانات)
    ├── Modal (نافذة منبثقة)
    ├── LanguageSwitcher (مبدل اللغة)
    └── ThemeToggle (وضع ليلي/نهاري)
```

---

## 🔔 نظام التنبيهات

### أنواع الشروط

```python
class AlertConditionType(Enum):
    GREATER_THAN = "greater_than"      # أكبر من
    LESS_THAN = "less_than"            # أقل من
    EQUALS = "equals"                   # يساوي
    NOT_EQUALS = "not_equals"          # لا يساوي
    BETWEEN = "between"                 # بين قيمتين
    OUTSIDE = "outside"                 # خارج نطاق
    CHANGED = "changed"                 # تغير
    OFFLINE = "offline"                 # انقطع الاتصال
```

### أمثلة على القواعد

```json
{
  "name": "تنبيه ارتفاع درجة الحرارة",
  "device_type": "temperature_sensor",
  "condition": {
    "type": "greater_than",
    "reading": "temperature",
    "value": 35,
    "unit": "celsius"
  },
  "severity": "critical",
  "notifications": ["email", "push", "sms"],
  "cooldown": 15
}
```

### قنوات الإشعارات
- **Email**: رسائل بريد إلكتروني (SendGrid/SMTP)
- **Push**: إشعارات المتصفح (Web Push)
- **SMS**: رسائل نصية (Twilio - اختياري)
- **Webhook**: للتكامل مع أنظمة أخرى

---

## 📁 هيكل المشروع

```
smartlife/
├── backend/
│   ├── app/
│   │   ├── __init__.py
│   │   ├── main.py                 # FastAPI entry point
│   │   ├── config.py               # Settings & configuration
│   │   ├── database.py             # Database connection
│   │   │
│   │   ├── api/
│   │   │   ├── __init__.py
│   │   │   ├── deps.py             # Dependencies (auth, db session)
│   │   │   └── v1/
│   │   │       ├── __init__.py
│   │   │       ├── auth.py         # Authentication endpoints
│   │   │       ├── users.py        # User management
│   │   │       ├── tenants.py      # Tenant management
│   │   │       ├── devices.py      # Device endpoints
│   │   │       ├── alerts.py       # Alert rules & logs
│   │   │       └── dashboard.py    # Dashboard stats
│   │   │
│   │   ├── core/
│   │   │   ├── __init__.py
│   │   │   ├── security.py         # JWT, password hashing
│   │   │   ├── permissions.py      # RBAC permissions
│   │   │   └── exceptions.py       # Custom exceptions
│   │   │
│   │   ├── models/
│   │   │   ├── __init__.py
│   │   │   ├── tenant.py
│   │   │   ├── user.py
│   │   │   ├── device.py
│   │   │   ├── alert.py
│   │   │   └── reading.py
│   │   │
│   │   ├── schemas/
│   │   │   ├── __init__.py
│   │   │   ├── tenant.py
│   │   │   ├── user.py
│   │   │   ├── device.py
│   │   │   ├── alert.py
│   │   │   └── common.py
│   │   │
│   │   ├── services/
│   │   │   ├── __init__.py
│   │   │   ├── lifesmart_client.py # LifeSmart API client
│   │   │   ├── alert_engine.py     # Alert processing
│   │   │   ├── notification.py     # Send notifications
│   │   │   └── sync_service.py     # Device sync service
│   │   │
│   │   └── tasks/
│   │       ├── __init__.py
│   │       ├── celery_app.py       # Celery configuration
│   │       ├── sync_devices.py     # Periodic device sync
│   │       └── check_alerts.py     # Alert checking task
│   │
│   ├── alembic/                    # Database migrations
│   │   ├── versions/
│   │   └── env.py
│   │
│   ├── tests/
│   │   ├── conftest.py
│   │   ├── test_auth.py
│   │   ├── test_devices.py
│   │   └── test_alerts.py
│   │
│   ├── requirements.txt
│   ├── alembic.ini
│   └── Dockerfile
│
├── frontend/
│   ├── src/
│   │   ├── app/
│   │   │   ├── [locale]/
│   │   │   │   ├── layout.tsx
│   │   │   │   ├── page.tsx
│   │   │   │   ├── (auth)/
│   │   │   │   │   ├── login/page.tsx
│   │   │   │   │   └── forgot-password/page.tsx
│   │   │   │   ├── (dashboard)/
│   │   │   │   │   ├── layout.tsx
│   │   │   │   │   ├── page.tsx
│   │   │   │   │   ├── devices/
│   │   │   │   │   ├── alerts/
│   │   │   │   │   ├── users/
│   │   │   │   │   ├── tenants/
│   │   │   │   │   └── settings/
│   │   │   │   └── globals.css
│   │   │   └── api/              # API routes (if needed)
│   │   │
│   │   ├── components/
│   │   │   ├── ui/               # shadcn components
│   │   │   ├── layout/
│   │   │   ├── dashboard/
│   │   │   ├── devices/
│   │   │   ├── alerts/
│   │   │   └── common/
│   │   │
│   │   ├── lib/
│   │   │   ├── api.ts            # API client
│   │   │   ├── auth.ts           # Auth utilities
│   │   │   ├── utils.ts          # Helper functions
│   │   │   └── socket.ts         # WebSocket client
│   │   │
│   │   ├── hooks/
│   │   │   ├── useAuth.ts
│   │   │   ├── useDevices.ts
│   │   │   └── useAlerts.ts
│   │   │
│   │   ├── stores/
│   │   │   ├── authStore.ts
│   │   │   └── deviceStore.ts
│   │   │
│   │   ├── messages/
│   │   │   ├── ar.json           # Arabic translations
│   │   │   └── en.json           # English translations
│   │   │
│   │   └── types/
│   │       └── index.ts
│   │
│   ├── public/
│   │   └── images/
│   │
│   ├── package.json
│   ├── tailwind.config.ts
│   ├── next.config.js
│   └── Dockerfile
│
├── docker/
│   ├── docker-compose.yml
│   ├── docker-compose.prod.yml
│   └── nginx/
│       ├── nginx.conf
│       └── ssl/
│
├── scripts/
│   ├── setup-server.sh           # AlmaLinux setup script
│   ├── deploy.sh                 # Deployment script
│   └── backup.sh                 # Database backup
│
├── docs/
│   ├── API.md
│   ├── DEPLOYMENT.md
│   └── USER_GUIDE.md
│
├── .env.example
├── .gitignore
└── README.md
```

---

## 🚀 خطوات النشر على AlmaLinux 9.7

### 1. إعداد الخادم الأساسي

```bash
#!/bin/bash
# scripts/setup-server.sh

# تحديث النظام
sudo dnf update -y
sudo dnf install -y epel-release

# تثبيت الأدوات الأساسية
sudo dnf install -y git curl wget vim nano htop

# تثبيت Python 3.11
sudo dnf install -y python3.11 python3.11-pip python3.11-devel

# تثبيت Node.js 20 LTS
curl -fsSL https://rpm.nodesource.com/setup_20.x | sudo bash -
sudo dnf install -y nodejs

# تثبيت PostgreSQL 15
sudo dnf install -y postgresql15-server postgresql15
sudo postgresql-setup --initdb
sudo systemctl enable --now postgresql

# تثبيت Redis 7
sudo dnf install -y redis
sudo systemctl enable --now redis

# تثبيت Nginx
sudo dnf install -y nginx
sudo systemctl enable nginx

# تثبيت Docker (اختياري)
sudo dnf config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
sudo dnf install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin
sudo systemctl enable --now docker

# إعداد Firewall
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload

# إعداد SELinux
sudo setsebool -P httpd_can_network_connect 1
```

### 2. إعداد قاعدة البيانات

```bash
# إنشاء قاعدة البيانات والمستخدم
sudo -u postgres psql << EOF
CREATE USER smartlife WITH PASSWORD 'your_secure_password';
CREATE DATABASE smartlife_db OWNER smartlife;
GRANT ALL PRIVILEGES ON DATABASE smartlife_db TO smartlife;
\q
EOF

# تعديل pg_hba.conf للسماح بالاتصال
sudo vim /var/lib/pgsql/15/data/pg_hba.conf
# أضف: local smartlife_db smartlife md5

sudo systemctl restart postgresql
```

### 3. إعداد التطبيق

```bash
# إنشاء مستخدم للتطبيق
sudo useradd -m -s /bin/bash smartlife
sudo mkdir -p /var/www/smartlife
sudo chown smartlife:smartlife /var/www/smartlife

# نسخ الملفات
sudo -u smartlife git clone https://github.com/YOUR_REPO/smartlife.git /var/www/smartlife

# إعداد Backend
cd /var/www/smartlife/backend
python3.11 -m venv venv
source venv/bin/activate
pip install -r requirements.txt

# إعداد Frontend
cd /var/www/smartlife/frontend
npm install
npm run build
```

### 4. إعداد Systemd Services

```ini
# /etc/systemd/system/smartlife-api.service
[Unit]
Description=SmartLife API Server
After=network.target postgresql.service redis.service

[Service]
User=smartlife
Group=smartlife
WorkingDirectory=/var/www/smartlife/backend
Environment="PATH=/var/www/smartlife/backend/venv/bin"
EnvironmentFile=/var/www/smartlife/.env
ExecStart=/var/www/smartlife/backend/venv/bin/gunicorn app.main:app -w 4 -k uvicorn.workers.UvicornWorker -b 127.0.0.1:8000
Restart=always

[Install]
WantedBy=multi-user.target
```

```ini
# /etc/systemd/system/smartlife-celery.service
[Unit]
Description=SmartLife Celery Worker
After=network.target redis.service

[Service]
User=smartlife
Group=smartlife
WorkingDirectory=/var/www/smartlife/backend
Environment="PATH=/var/www/smartlife/backend/venv/bin"
EnvironmentFile=/var/www/smartlife/.env
ExecStart=/var/www/smartlife/backend/venv/bin/celery -A app.tasks.celery_app worker -l info
Restart=always

[Install]
WantedBy=multi-user.target
```

```ini
# /etc/systemd/system/smartlife-celerybeat.service
[Unit]
Description=SmartLife Celery Beat
After=network.target redis.service

[Service]
User=smartlife
Group=smartlife
WorkingDirectory=/var/www/smartlife/backend
Environment="PATH=/var/www/smartlife/backend/venv/bin"
EnvironmentFile=/var/www/smartlife/.env
ExecStart=/var/www/smartlife/backend/venv/bin/celery -A app.tasks.celery_app beat -l info
Restart=always

[Install]
WantedBy=multi-user.target
```

### 5. إعداد Nginx

```nginx
# /etc/nginx/conf.d/smartlife.conf
upstream smartlife_api {
    server 127.0.0.1:8000;
}

server {
    listen 80;
    server_name your-domain.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    server_name your-domain.com;

    ssl_certificate /etc/letsencrypt/live/your-domain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/your-domain.com/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;

    # Frontend (Next.js static export or SSR)
    location / {
        root /var/www/smartlife/frontend/out;
        try_files $uri $uri.html $uri/ =404;
    }

    # API Proxy
    location /api/ {
        proxy_pass http://smartlife_api;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    # WebSocket
    location /ws/ {
        proxy_pass http://smartlife_api;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
    }

    # Security headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;
}
```

### 6. SSL Certificate

```bash
# تثبيت Certbot
sudo dnf install -y certbot python3-certbot-nginx

# الحصول على شهادة SSL
sudo certbot --nginx -d your-domain.com

# تجديد تلقائي
sudo systemctl enable certbot-renew.timer
```

---

## ⚙️ ملف التكوين (.env)

```env
# Application
APP_NAME=SmartLife Monitor
APP_ENV=production
DEBUG=false
SECRET_KEY=your-super-secret-key-change-this

# Database
DATABASE_URL=postgresql://smartlife:password@localhost:5432/smartlife_db

# Redis
REDIS_URL=redis://localhost:6379/0

# JWT
JWT_SECRET_KEY=your-jwt-secret-key
JWT_ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30
REFRESH_TOKEN_EXPIRE_DAYS=7

# LifeSmart API (Default - can be overridden per tenant)
LIFESMART_DEFAULT_REGION=global

# Email (SendGrid)
SENDGRID_API_KEY=your-sendgrid-api-key
EMAIL_FROM=noreply@your-domain.com

# SMS (Twilio - Optional)
TWILIO_ACCOUNT_SID=
TWILIO_AUTH_TOKEN=
TWILIO_PHONE_NUMBER=

# Frontend URL
FRONTEND_URL=https://your-domain.com

# CORS
CORS_ORIGINS=["https://your-domain.com"]
```

---

## 📅 خطة التنفيذ (Timeline)

| المرحلة | المدة | المهام |
|--------|-------|--------|
| **المرحلة 1** | أسبوع 1-2 | إعداد المشروع + قاعدة البيانات + المصادقة |
| **المرحلة 2** | أسبوع 3-4 | تكامل LifeSmart API + مزامنة الأجهزة |
| **المرحلة 3** | أسبوع 5-6 | لوحة التحكم الأساسية + عرض الأجهزة |
| **المرحلة 4** | أسبوع 7-8 | نظام التنبيهات + الإشعارات |
| **المرحلة 5** | أسبوع 9-10 | إدارة المستأجرين + الصلاحيات |
| **المرحلة 6** | أسبوع 11-12 | الاختبار + النشر + التوثيق |

---

## ✅ قائمة التحقق للإطلاق

- [ ] إعداد خادم AlmaLinux
- [ ] تثبيت وتكوين PostgreSQL
- [ ] تثبيت وتكوين Redis
- [ ] نشر Backend API
- [ ] نشر Frontend
- [ ] إعداد Nginx + SSL
- [ ] تكوين Celery workers
- [ ] اختبار تكامل LifeSmart
- [ ] اختبار نظام التنبيهات
- [ ] إعداد النسخ الاحتياطي
- [ ] إعداد المراقبة (Monitoring)
- [ ] توثيق API
- [ ] دليل المستخدم

---

## 📞 الدعم والموارد

- **LifeSmart Open Platform**: http://www.ilifesmart.com/open/login
- **LifeSmart API Reference**: وثائق المطورين في المنصة
- **مشاريع مرجعية**:
  - https://github.com/MapleEve/lifesmart-for-homeassistant
  - https://github.com/skyzhishui/custom_components

---

**تاريخ الإنشاء**: 2026-01-28
**الإصدار**: 1.0
