(function (global) {
  'use strict';

  // Массив известных Emotion: сочетаний базовых контекстов
  // Формат элемента: { id: number, contextIds: number[] }
  if (!Array.isArray(global.Emotions)) {
    global.Emotions = [];
  }

  function normalizeIds(ids) {
    if (!Array.isArray(ids)) return [];
    var arr = [];
    for (var i = 0; i < ids.length; i++) {
      var v = parseInt(ids[i], 10);
      if (!isNaN(v) && v > 0) {
        if (arr.indexOf(v) === -1) {
          arr.push(v);
        }
      }
    }
    arr.sort(function (a, b) { return a - b; });
    return arr;
  }

  function arraysEqual(a, b) {
    if (a.length !== b.length) return false;
    for (var i = 0; i < a.length; i++) {
      if (a[i] !== b[i]) return false;
    }
    return true;
  }

  function findEmotionIdByContexts(contextIds) {
    var norm = normalizeIds(contextIds);
    if (!norm.length) return 0;
    for (var i = 0; i < global.Emotions.length; i++) {
      if (arraysEqual(global.Emotions[i].contextIds, norm)) {
        return global.Emotions[i].id;
      }
    }
    return 0;
  }

  function getNextEmotionId() {
    var maxId = 0;
    for (var i = 0; i < global.Emotions.length; i++) {
      if (global.Emotions[i].id > maxId) {
        maxId = global.Emotions[i].id;
      }
    }
    return maxId + 1;
  }

  function getOrCreateEmotionId(contextIds) {
    var norm = normalizeIds(contextIds);
    if (!norm.length) return 0;
    var existingId = findEmotionIdByContexts(norm);
    if (existingId) return existingId;
    var newId = getNextEmotionId();
    global.Emotions.push({ id: newId, contextIds: norm });
    if (Array.isArray(global.KnownEmotionIds) && global.KnownEmotionIds.indexOf(newId) === -1) {
      global.KnownEmotionIds.push(newId);
    }
    return newId;
  }

  global.Emotions_findEmotionId = findEmotionIdByContexts;
  global.Emotions_getOrCreateEmotionId = getOrCreateEmotionId;

})(window);

