File size: 9,840 Bytes
a08f3c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
'use strict';

/**
 * ╔══════════════════════════════════════════════════════════════════════════╗
 *  Features Engine — v19.0 | محرك 100 ميزة + Presets                       ║
 * ╠══════════════════════════════════════════════════════════════════════════╣
 *  ✅ 100 ميزة في 8 فئات: حماية، أداء، اقتصاد، لاعبين، عوالم، ترفيه، إدارة، بوتات  ║
 *  ✅ 5 Presets: Survival Pro, Creative Build, Minigames Hub, Hardcore, Custom  ║
 *  ✅ REST API: GET/POST /api/features + Preset Apply                         ║
 *  ✅ Auto-Apply: يطبق الميزات المفعلة عند التشغيل                          ║
 *  ✅ Plugin Detection: كشف البلاجن المثبتة وتطابقها مع الميزات            ║
 *  ✅ Dependencies: تفعيل تلقائي للعلاقات                                    ║
 *  ✅ Export/Import: حفظ وتحميل إعدادات الميزات                             ║
 * ╚══════════════════════════════════════════════════════════════════════════╝
 */

const fs = require('fs');
const path = require('path');
const { EventEmitter } = require('events');

const tsNow = () => new Date().toISOString().replace('T', ' ').slice(0, 19);

class FeaturesEngine extends EventEmitter {
  constructor(config = {}) {
    super();
    this.configPath = config.configPath || path.join(__dirname, 'features-config.json');
    this.dataPath = config.dataPath || path.join(__dirname, 'features-data.json');
    this.features = {};
    this.categories = {};
    this.presets = {};
    this.activePreset = 'custom';
    this.modifiedFeatures = new Set();
    this._log('ENGINE', 'تم إنشاء Features Engine');
  }

  _log(tag, msg) {
    const ts = tsNow();
    console.log(`[${ts}] [FEATURES] ${tag}  ${msg}`);
  }

  init() {
    this._loadConfig();
    this._loadData();
    this._log('✅', `تم تحميل ${Object.keys(this.features).length} ميزة في ${Object.keys(this.categories).length} فئة`);
    this._log('📦', `${Object.keys(this.presets).length} Presets متاحة`);
  }

  _loadConfig() {
    try {
      const raw = fs.readFileSync(this.configPath, 'utf8');
      const data = JSON.parse(raw);
      this.features = data.features || {};
      this.categories = data.categories || {};
      this.presets = data.presets || {};
      this._log('📂', 'تم تحميل features-config.json');
    } catch (e) {
      this._log('⚠️', `خطأ في تحميل features-config.json: ${e.message}`);
      this.features = {};
      this.categories = {};
      this.presets = {};
    }
  }

  _loadData() {
    try {
      if (fs.existsSync(this.dataPath)) {
        const raw = fs.readFileSync(this.dataPath, 'utf8');
        const data = JSON.parse(raw);
        this.activePreset = data.activePreset || 'custom';
        if (data.features) {
          for (const [id, overrides] of Object.entries(data.features)) {
            if (this.features[id]) {
              this.features[id] = { ...this.features[id], ...overrides };
            }
          }
        }
        this._log('📂', `تم تحميل البيانات المحفوظة (Preset: ${this.activePreset})`);
      }
    } catch (e) {
      this._log('⚠️', `خطأ في تحميل البيانات: ${e.message}`);
    }
  }

  saveData() {
    try {
      const features = {};
      for (const [id, f] of Object.entries(this.features)) {
        features[id] = { enabled: f.enabled, config: f.config };
      }
      const data = {
        version: '19.0',
        activePreset: this.activePreset,
        features,
        savedAt: tsNow()
      };
      fs.writeFileSync(this.dataPath, JSON.stringify(data, null, 2));
      this._log('💾', 'تم حفظ البيانات');
    } catch (e) {
      this._log('❌', `خطأ في الحفظ: ${e.message}`);
    }
  }

  applyPreset(presetId) {
    const preset = this.presets[presetId];
    if (!preset) {
      this._log('❌', `Preset غير موجود: ${presetId}`);
      return false;
    }
    this._log('📦', `تطبيق Preset: ${preset.name}`);
    for (const f of Object.values(this.features)) {
      f.enabled = preset.enabledFeatures.includes(f.id);
    }
    for (const depId of preset.enabledFeatures) {
      this._enableDependencies(depId);
    }
    this.activePreset = presetId;
    this.saveData();
    this.emit('presetApplied', presetId, preset);
    this._log('✅', `تم تطبيق ${preset.name} — ${preset.enabledFeatures.length} ميزة مفعلة`);
    return true;
  }

  _enableDependencies(featureId) {
    const f = this.features[featureId];
    if (!f || !f.dependencies) return;
    for (const depId of f.dependencies) {
      if (this.features[depId] && !this.features[depId].enabled) {
        this.features[depId].enabled = true;
        this._log('🔗', `تفعيل تلقائي: ${depId} (dependency لـ ${featureId})`);
        this._enableDependencies(depId);
      }
    }
  }

  toggleFeature(featureId, enabled) {
    if (!this.features[featureId]) {
      this._log('❌', `ميزة غير موجودة: ${featureId}`);
      return false;
    }
    this.features[featureId].enabled = enabled;
    this.modifiedFeatures.add(featureId);
    if (enabled) {
      this._enableDependencies(featureId);
    }
    this.activePreset = 'custom';
    this.saveData();
    this.emit('featureToggled', featureId, enabled);
    this._log('🔄', `${enabled ? 'تفعيل' : 'تعطيل'}: ${featureId}`);
    return true;
  }

  updateFeatureConfig(featureId, config) {
    if (!this.features[featureId]) return false;
    this.features[featureId].config = { ...this.features[featureId].config, ...config };
    this.modifiedFeatures.add(featureId);
    this.saveData();
    this.emit('featureConfigUpdated', featureId, config);
    return true;
  }

  getFeature(id) {
    return this.features[id] || null;
  }

  getFeaturesByCategory(categoryId) {
    return Object.values(this.features).filter(f => f.category === categoryId);
  }

  getAllFeatures() {
    return Object.values(this.features);
  }

  getEnabledFeatures() {
    return Object.values(this.features).filter(f => f.enabled);
  }

  getDisabledFeatures() {
    return Object.values(this.features).filter(f => !f.enabled);
  }

  getCategories() {
    return Object.entries(this.categories)
      .sort(([, a], [, b]) => a.order - b.order)
      .map(([id, cat]) => ({ id, ...cat }));
  }

  getPresets() {
    return Object.entries(this.presets).map(([id, p]) => ({ id, ...p }));
  }

  getPreset(id) {
    return this.presets[id] || null;
  }

  getActivePreset() {
    return { id: this.activePreset, ...this.presets[this.activePreset] };
  }

  getStats() {
    const all = Object.values(this.features);
    const enabled = all.filter(f => f.enabled).length;
    const disabled = all.length - enabled;
    const byCategory = {};
    for (const f of all) {
      if (!byCategory[f.category]) byCategory[f.category] = { total: 0, enabled: 0 };
      byCategory[f.category].total++;
      if (f.enabled) byCategory[f.category].enabled++;
    }
    return { total: all.length, enabled, disabled, byCategory, activePreset: this.activePreset };
  }

  matchPlugins(detectedPlugins) {
    const matches = [];
    const unmatched = [];
    for (const plugin of detectedPlugins) {
      const nameLower = (plugin.name || '').toLowerCase().replace(/[\s\-_]/g, '');
      let found = false;
      for (const f of Object.values(this.features)) {
        const featureName = (f.name || '').toLowerCase().replace(/[\s\-_]/g, '');
        if (nameLower.includes(featureName) || featureName.includes(nameLower)) {
          matches.push({ plugin: plugin.name, feature: f.id, enabled: f.enabled });
          found = true;
          break;
        }
      }
      if (!found) {
        unmatched.push(plugin.name);
      }
    }
    return { matches, unmatched, totalPlugins: detectedPlugins.length, totalFeatures: Object.keys(this.features).length };
  }

  exportConfig() {
    return {
      version: '19.0',
      activePreset: this.activePreset,
      exportedAt: tsNow(),
      features: Object.fromEntries(
        Object.entries(this.features).map(([id, f]) => [id, { enabled: f.enabled, config: f.config }])
      )
    };
  }

  importConfig(data) {
    if (!data || !data.features) return false;
    let imported = 0;
    for (const [id, overrides] of Object.entries(data.features)) {
      if (this.features[id]) {
        this.features[id] = { ...this.features[id], ...overrides };
        imported++;
      }
    }
    if (data.activePreset && this.presets[data.activePreset]) {
      this.activePreset = data.activePreset;
    }
    this.saveData();
    this._log('📥', `تم استيراد ${imported} ميزة`);
    this.emit('configImported', imported);
    return true;
  }

  getApiData() {
    return {
      version: '19.0',
      stats: this.getStats(),
      categories: this.getCategories(),
      features: Object.values(this.features).map(f => ({
        id: f.id, name: f.name, category: f.category,
        enabled: f.enabled, description: f.description,
        config: f.config, dependencies: f.dependencies,
        commands: f.commands
      })),
      presets: this.getPresets(),
      activePreset: this.activePreset
    };
  }
}

module.exports = { FeaturesEngine };